repo
string
commit
string
message
string
diff
string
jaxl/JAXL
8fa71ae7d68779b61f21487db00587230c22a712
Join in room id can be changed in xep_0045
diff --git a/xep/xep_0045.php b/xep/xep_0045.php index 0fe8592..40b3a4d 100644 --- a/xep/xep_0045.php +++ b/xep/xep_0045.php @@ -1,121 +1,122 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_MUC', 'http://jabber.org/protocol/muc'); class XEP_0045 extends XMPPXep { // // abstract method // public function init() { return array(); } public function send_groupchat($room_jid, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type'=>'groupchat', 'to'=>(($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid), 'from'=>$this->jaxl->full_jid->to_string() ), $body, $thread, $subject ); $this->jaxl->send($msg); } // // api methods (occupant use case) // // room_full_jid simply means room jid with nick name as resource public function get_join_room_pkt($room_full_jid, $options) { $pkt = $this->jaxl->get_pres_pkt( array( 'from'=>$this->jaxl->full_jid->to_string(), - 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid) + 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid), + 'id' => (isset($options['id'])) ? $options['id'] : uniqid() ) ); $x = $pkt->c('x', NS_MUC); if (isset($options['no_history'])) { $x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0))->up(); } if (isset($options['password'])) { $x->c('password')->t($options['password'])->up(); } return $x; } public function join_room($room_full_jid, $options = array()) { $pkt = $this->get_join_room_pkt($room_full_jid, $options); $this->jaxl->send($pkt); } public function get_leave_room_pkt($room_full_jid) { return $this->jaxl->get_pres_pkt( array('type'=>'unavailable', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid)) ); } public function leave_room($room_full_jid) { $pkt = $this->get_leave_room_pkt($room_full_jid); $this->jaxl->send($pkt); } // // api methods (moderator use case) // // // event callbacks // }
jaxl/JAXL
f173c3f07a94013355961bbb20fe130fcdd57914
Fix Generic.Files.LineLength
diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php index 92e63c4..b03eba2 100644 --- a/core/jaxl_clock.php +++ b/core/jaxl_clock.php @@ -1,128 +1,129 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class JAXLClock { // current clock time in microseconds private $tick = 0; // current Unix timestamp with microseconds public $time = null; // scheduled jobs public $jobs = array(); public function __construct() { $this->time = microtime(true); } public function __destruct() { _info("shutting down clock server..."); } public function tick($by = null) { // update clock if ($by) { $this->tick += $by; $this->time += $by / pow(10, 6); } else { $time = microtime(true); $by = $time - $this->time; $this->tick += $by * pow(10, 6); $this->time = $time; } // run scheduled jobs foreach ($this->jobs as $ref => $job) { if ($this->tick >= $job['scheduled_on'] + $job['after']) { - //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".$job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); + //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ". + // $job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); call_user_func($job['cb'], $job['args']); if (!$job['is_periodic']) { unset($this->jobs[$ref]); } else { $job['scheduled_on'] = $this->tick; $job['runs']++; $this->jobs[$ref] = $job; } } } } // calculate execution time of callback public function tc($callback, $args = null) { } // callback after $time microseconds public function call_fun_after($time, $callback, $args = null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => false, 'runs' => 0 ); return sizeof($this->jobs); } // callback periodically after $time microseconds public function call_fun_periodic($time, $callback, $args = null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => true, 'runs' => 0 ); return sizeof($this->jobs); } // cancel a previously scheduled callback public function cancel_fun_call($ref) { unset($this->jobs[$ref-1]); } } diff --git a/core/jaxl_event.php b/core/jaxl_event.php index 66f2a88..a62b38b 100644 --- a/core/jaxl_event.php +++ b/core/jaxl_event.php @@ -1,130 +1,134 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** - * following kind of events are possible: - * 1) hook i.e. if a callback for such an event is registered, calling function is responsible for the workflow from their on - * 2) filter i.e. calling function will manipulate passed arguments and modified arguments will be passed to next chain of filter + * Following kind of events are possible: + * 1) hook i.e. if a callback for such an event is registered, calling function + * is responsible for the workflow from their on + * 2) filter i.e. calling function will manipulate passed arguments + * and modified arguments will be passed to next chain of filter * - * As a rule of thumb, only 1 hook can be registered for an event, while more than 1 filter is allowed for an event - * hook and filter both cannot be applied on an event + * As a rule of thumb, only 1 hook can be registered for an event, while more + * than 1 filter is allowed for an event hook and filter both cannot be applied + * on an event. * * @author abhinavsingh * */ class JAXLEvent { protected $common = array(); public $reg = array(); public function __construct($common) { $this->common = $common; } public function __destruct() { } // add callback on a event // returns a reference to be used while deleting callback // callback'd method must return TRUE to be persistent // if none returned or FALSE, callback will be removed automatically public function add($ev, $cb, $pri) { if (!isset($this->reg[$ev])) { $this->reg[$ev] = array(); } $ref = sizeof($this->reg[$ev]); $this->reg[$ev][] = array($pri, $cb); return $ev."-".$ref; } // emit event to notify registered callbacks // is a pqueue required here for performance enhancement // in case we have too many cbs on a specific event? public function emit($ev, $data = array()) { $data = array_merge($this->common, $data); $cbs = array(); if (!isset($this->reg[$ev])) { return $data; } foreach ($this->reg[$ev] as $cb) { if (!isset($cbs[$cb[0]])) { $cbs[$cb[0]] = array(); } $cbs[$cb[0]][] = $cb[1]; } foreach ($cbs as $pri => $cb) { foreach ($cb as $c) { $ret = call_user_func_array($c, $data); - // this line is for fixing situation where callback function doesn't return an array type - // in such cases next call of call_user_func_array will report error since $data is not an array type as expected - // things will change in future, atleast put the callback inside a try/catch block - // here we only check if there was a return, if yes we update $data with return value - // this is bad design, need more thoughts, should work as of now + // This line is for fixing situation where callback function doesn't return an array type. + // In such cases next call of call_user_func_array will report error since $data is not + // an array type as expected. + // Things will change in future, atleast put the callback inside a try/catch block. + // Here we only check if there was a return, if yes we update $data with return value. + // This is bad design, need more thoughts, should work as of now. if ($ret) { $data = $ret; } } } unset($cbs); return $data; } // remove previous registered callback public function del($ref) { $ref = explode("-", $ref); unset($this->reg[$ref[0]][$ref[1]]); } public function exists($ev) { $ret = isset($this->reg[$ev]); //_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists")); return $ret; } } diff --git a/core/jaxl_fsm.php b/core/jaxl_fsm.php index 0e73ccc..a6c5bcd 100644 --- a/core/jaxl_fsm.php +++ b/core/jaxl_fsm.php @@ -1,90 +1,98 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ abstract class JAXLFsm { protected $state = null; // abstract method abstract public function handle_invalid_state($r); public function __construct($state) { $this->state = $state; } // returned value from state callbacks can be: // 1) array() <-- is_callable method // 2) array([0] => 'new_state', [1] => 'return value for current callback') <-- is_not_callable method // 3) array([0] => 'new_state') // 4) 'new_state' // // for case 1) new state will be an array // for other cases new state will be a string public function __call($event, $args) { if ($this->state) { // call state method - _debug("calling state handler '".(is_array($this->state) ? $this->state[1] : $this->state)."' for incoming event '".$event."'"); - $call = is_callable($this->state) ? $this->state : (method_exists($this, $this->state) ? array(&$this, $this->state): $this->state); + _debug(sprintf( + "calling state handler '%s' for incoming event '%s'", + is_array($this->state) ? $this->state[1] : $this->state, + $event + )); + if (is_callable($this->state)) { + $call = $this->state; + } else { + $call = method_exists($this, $this->state) ? array(&$this, $this->state): $this->state; + } $r = call_user_func($call, $event, $args); // 4 cases of possible return value if (is_callable($r)) { $this->state = $r; } elseif (is_array($r) && sizeof($r) == 2) { list($this->state, $ret) = $r; } elseif (is_array($r) && sizeof($r) == 1) { $this->state = $r[0]; } elseif (is_string($r)) { $this->state = $r; } else { $this->handle_invalid_state($r); } _debug("current state '".(is_array($this->state) ? $this->state[1] : $this->state)."'"); // return case if (!is_callable($r) && is_array($r) && sizeof($r) == 2) { return $ret; } } else { _debug("invalid state found, nothing called for event ".$event.""); } } } diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index 596eee5..799aaaf 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,243 +1,250 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; public function __construct($stream_context = null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ public function connect($socket_path) { if (gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); if (sizeof($path_parts) == 3) { $this->port = $path_parts[2]; } _info("trying ".$socket_path); if ($this->stream_context) { - $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); + $this->fd = @stream_socket_client( + $socket_path, + $this->errno, + $this->errstr, + $this->timeout, + STREAM_CLIENT_CONNECT, + $this->stream_context + ); } else { $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); } } else { $this->fd = &$socket_path; } if ($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { _error(sprintf( "unable to connect %s with error no: %s, error str: %s", is_null($socket_path) ? 'NULL' : $socket_path, is_null($this->errno) ? 'NULL' : $this->errno, is_null($this->errstr) ? 'NULL' : $this->errstr )); $this->disconnect(); return false; } } public function disconnect() { JAXLLoop::unwatch($this->fd, array( 'read' => true, 'write' => true )); if (is_resource($this->fd)) { fclose($this->fd); } $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); return $ret; } public function send($data) { $this->obuffer .= $data; // add watch for write events if ($this->writing) { return; } JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if ($bytes === 0) { $meta = stream_get_meta_data($fd); if ($meta['eof'] === true) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); if ($bytes > 0) { _debug($raw); } // callback if ($this->recv_cb) { call_user_func($this->recv_cb, $raw); } } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if (strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } } diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index 79c8fc6..2bb4154 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,273 +1,274 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLSocketServer { public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; public function __construct($path, $accept_cb, $request_cb) { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; $ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog))); - if (($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { + $this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx); + if ($this->fd !== false) { if (@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); } else { _error("unable to set non block flag"); } } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } public function __destruct() { _info("shutting down socket server"); } public function read($client_id) { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } public function send($client_id, $data) { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } public function close($client_id) { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } public function on_server_accept_ready($server) { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); if (!$client) { _error("unable to accept new client conn"); return; } if (@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do if ($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); } else { // if no accept callback is registered // close the accepted connection if (is_resource($client)) { fclose($client); } $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } } else { _error("unable to set non block flag"); } } public function on_client_read_ready($client) { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); if ($bytes === 0) { $meta = stream_get_meta_data($client); if ($meta['eof'] === true) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); if (is_resource($client)) { fclose($client); } unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; if ($this->request_cb) { call_user_func($this->request_cb, $client_id, $total); } $this->clients[$client_id]['ibuffer'] = ''; } public function on_client_write_ready($client) { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); if ($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; } elseif ($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler if (strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { if (is_resource($client)) { fclose($client); } $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } } catch (JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // protected function add_read_cb($client_id) { if ($this->clients[$client_id]['reading']) { return; } JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } protected function add_write_cb($client_id) { if ($this->clients[$client_id]['writing']) { return; } JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } protected function del_read_cb($client_id) { if (!$this->clients[$client_id]['reading']) { return; } JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } protected function del_write_cb($client_id) { if (!$this->clients[$client_id]['writing']) { return; } JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } } diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php index 7458ffd..539168f 100644 --- a/examples/http_pre_bind.php +++ b/examples/http_pre_bind.php @@ -1,93 +1,99 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // http pre bind php script $body = file_get_contents("php://input"); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if (!@$attrs['to'] && !@$attrs['rid'] && !@$attrs['wait'] && !@$attrs['hold']) { echo "invalid input"; exit; } // // initialize JAXL object with initial config // require_once '../jaxl.php'; $to = (string)$attrs['to']; $rid = (int)$attrs['rid']; $wait = (int)$attrs['wait']; $hold = (int)$attrs['hold']; list($host, $port) = JAXLUtil::get_dns_srv($to); $client = new JAXL(array( 'domain' => $to, 'host' => $host, 'port' => $port, 'bosh_url' => 'http://localhost:5280/http-bind', 'bosh_rid' => $rid, 'bosh_wait' => $wait, 'bosh_hold' => $hold, 'auth_type' => 'ANONYMOUS', 'log_level' => JAXL_INFO )); function on_auth_success_callback() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); - echo '<body xmlns="'.NS_HTTP_BIND.'" sid="'.$client->xeps['0206']->sid.'" rid="'.$client->xeps['0206']->rid.'" jid="'.$client->full_jid->to_string().'"/>'; + echo sprintf( + '<body xmlns="%s" sid="%s" rid="%s" jid="%s"/>', + NS_HTTP_BIND, + $client->xeps['0206']->sid, + $client->xeps['0206']->rid, + $client->full_jid->to_string() + ); exit; } $client->add_cb('on_auth_success', 'on_auth_success_callback'); function on_auth_failure_callback($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); } $client->add_cb('on_auth_failure', 'on_auth_failure_callback'); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/http_rest_server.php b/examples/http_rest_server.php index f8a6283..8d16912 100644 --- a/examples/http_rest_server.php +++ b/examples/http_rest_server.php @@ -1,122 +1,127 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // print usage notice and parse addr/port parameters if passed _colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE); $port = ($argc == 2 ? $argv[1] : 9699); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer($port); // callback method for dispatch rule (see below) function index($request) { $request->send_response( 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } // callback method for dispatch rule (see below) function upload($request) { if ($request->method == 'GET') { $request->ok( array('Content-Type' => 'text/html'), - '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' + '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" ' . + 'action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" ' . + 'value="upload"/></form></body></html>' ); } elseif ($request->method == 'POST') { if ($request->body === null && $request->expect) { $request->recv_body(); } else { // got upload body, save it _info("file upload complete, got ".strlen($request->body)." bytes of data"); $upload_data = $request->multipart->form_data[0]['body']; - $request->ok($upload_data, array('Content-Type' => $request->multipart->form_data[0]['headers']['Content-Type'])); + $request->ok( + $upload_data, + array('Content-Type' => $request->multipart->form_data[0]['headers']['Content-Type']) + ); } } } // add dispatch rules with callback method as first argument $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); // some REST CRUD style callback methods // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules function create_event($request) { _info("got event create request"); $request->close(); } function read_event($request, $pk) { _info("got event read request for $pk"); $request->close(); } function update_event($request, $pk) { _info("got event update request for $pk"); $request->close(); } function delete_event($request, $pk) { _info("got event delete request for $pk"); $request->close(); } $event_create = array('create_event', '^/event/create/$', array('PUT')); $event_read = array('read_event', '^/event/(?P<pk>\d+)/$', array('GET', 'HEAD')); $event_update = array('update_event', '^/event/(?P<pk>\d+)/$', array('POST')); $event_delete = array('delete_event', '^/event/(?P<pk>\d+)/$', array('DELETE')); // prepare rule set $rules = array($index, $upload, $event_create, $event_read, $event_update, $event_delete); $http->dispatch($rules); // start http server $http->start(); diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index ed03c90..c0e5a83 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,148 +1,156 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 5) { echo "Usage: $argv[0] host jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[2], 'pass' => $argv[3], 'host' => $argv[1], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC '0203', // Delayed Delivery '0199' // XMPP Ping )); // // add necessary event callbacks here // $_room_full_jid = $argv[4]."/".$argv[5]; $room_full_jid = new XMPPJid($_room_full_jid); function on_auth_success_callback() { global $client, $room_full_jid; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // join muc room $client->xeps['0045']->join_room($room_full_jid); } $client->add_cb('on_auth_success', 'on_auth_success_callback'); function on_auth_failure_callback($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); } $client->add_cb('on_auth_failure', 'on_auth_failure_callback'); function on_groupchat_message_callback($stanza) { global $client; $from = new XMPPJid($stanza->from); $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); if ($from->resource) { - echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; + echo sprintf( + "message stanza rcvd from %s saying... %s, %s".PHP_EOL, + $from->resource, + $stanza->body, + $delay ? "delay timestamp ".$delay->attrs['stamp'] : "timestamp ".gmdate("Y-m-dTH:i:sZ") + ); } else { $subject = $stanza->exists('subject'); if ($subject) { - echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; + echo "room subject: ".$subject->text.($delay ? ", delay timestamp ". + $delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } } } $client->add_cb('on_groupchat_message', 'on_chat_message_callback'); function on_presence_stanza_callback($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { if (($status = $x->exists('status', null, array('code' => '110'))) !== false) { $item = $x->exists('item'); - _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); + _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code']. + ", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); } else { _info("xmlns #user have no x child element"); } } else { _warning("=======> odd case 1"); } } elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) { // stanza from other users received if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); - echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; + echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ". + $from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; } else { _warning("=======> odd case 2"); } } else { _warning("=======> odd case 3"); } } $client->add_cb('on_presence_stanza', 'on_presence_stanza_callback'); function on_disconnect_callback() { _info("got on_disconnect cb"); } $client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/publisher.php b/examples/publisher.php index c07eee0..6b22756 100644 --- a/examples/publisher.php +++ b/examples/publisher.php @@ -1,103 +1,107 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // function on_auth_success_callback() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // create node //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); // publish $item = new JAXLXml('item', null, array('id' => time())); $item->c('entry', 'http://www.w3.org/2005/Atom'); $item->c('title')->t('Soliloquy')->up(); $item->c('summary')->t('To be, or not to be: that is the question')->up(); - $item->c('link', null, array('rel' => 'alternate', 'type' => 'text/html', 'href' => 'http://denmark.lit/2003/12/13/atom03'))->up(); + $item->c( + 'link', + null, + array('rel' => 'alternate', 'type' => 'text/html', 'href' => 'http://denmark.lit/2003/12/13/atom03') + )->up(); $item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up(); $item->c('published')->t('2003-12-13T18:30:02Z')->up(); $item->c('updated')->t('2003-12-13T18:30:02Z')->up(); $client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item); } $client->add_cb('on_auth_success', 'on_auth_success_callback'); function on_auth_failure_callback($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); } $client->add_cb('on_auth_failure', 'on_auth_failure_callback'); function on_disconnect_callback() { _info("got on_disconnect cb"); } $client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/register_user.php b/examples/register_user.php index 49a0fac..9f6f863 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,169 +1,173 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // $form = array(); function wait_for_register_response($event, $args) { global $client, $form; if ($event == 'stanza_cb') { $stanza = $args[0]; if ($stanza->name == 'iq') { $form['type'] = $stanza->attrs['type']; if ($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } elseif ($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); - echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; + echo sprintf( + "registration failed with error code: %s and type: %s".PHP_EOL, + $error->attrs['code'], + $error->attrs['type'] + ); echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } } } else { _notice("unhandled event $event rcvd"); } } function wait_for_register_form($event, $args) { global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if ($query) { $instructions = $query->exists('instructions'); if ($instructions) { echo $instructions->text.PHP_EOL; } foreach ($query->childrens as $k => $child) { if ($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // function on_stream_features_callback($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; } $client->add_cb('on_stream_features', 'on_stream_features_callback'); function on_disconnect_callback() { global $form; _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); } $client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(); // // if registration was successful // try to connect with newly registered account // if ($form['type'] == 'result') { _info("connecting newly registered user account"); $client = new JAXL(array( 'jid' => $form['username'].'@'.$argv[1], 'pass' => $form['password'], 'log_level' => JAXL_DEBUG )); function on_auth_success_callback() { global $client; $client->set_status('Available'); } $client->add_cb('on_auth_success', 'on_auth_success_callback'); $client->start(); } echo "done\n"; diff --git a/jaxl.php b/jaxl.php index 421b265..3ac977c 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,886 +1,890 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger if (isset($this->cfg['log_path'])) { JAXLLogger::$path = $this->cfg['log_path']; } //else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; } if (isset($this->cfg['log_level'])) { JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; } else { JAXLLogger::$level = $this->log_level; } // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true; if ($strict) { $this->add_exception_handlers(); } $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if (!is_dir($this->priv_dir)) { mkdir($this->priv_dir); } if (!is_dir($this->tmp_dir)) { mkdir($this->tmp_dir); } if (!is_dir($this->pid_dir)) { mkdir($this->pid_dir); } if (!is_dir($this->log_dir)) { mkdir($this->log_dir); } if (!is_dir($this->sock_dir)) { mkdir($this->sock_dir); } // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { - _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); + _info("strict mode enabled, adding exception handlers. ' . + 'Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if (!is_array($xeps)) { $xeps = array($xeps); } foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri = 1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show = 'chat', $priority = 10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type' => 'chat', 'to' => $to, 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid = null, $cb = null) { $attrs = array( 'type' => 'get', 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) { $this->add_cb('on_stanza_id_'.$pkt->id, $cb); } $this->send($pkt); } public function get_roster($cb = null) { $pkt = $this->get_iq_pkt( array( 'type' => 'get', 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) { $this->add_cb('on_stanza_id_'.$pkt->id, $cb); } $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribed') )); } public function get_socket_path() { if (isset($this->cfg['protocol'])) { $protocol = $this->cfg['protocol']; } else { $protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp"); } return $protocol."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts = array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) { $this->add_cb('on_connect', array($this, 'start_stream')); } // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) { $this->enable_debug_shell(); } if (@$opts['--with-unix-sock']) { $this->enable_unix_sock(); } // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } else { // if connection to the destination fails if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch ($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch ($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch ($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); - // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof + // AuthMessage := client-first-message-bare + "," + server-first-message + "," + + // client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch ($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if ($mechanisms) { foreach ($mechanisms->childrens as $mechanism) { $mechs[$mechanism->text] = true; } } // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if ($pref_auth_exists) { $mech = $pref_auth; } else { // if pref auth doesn't exists, choose one from available mechanisms foreach ($mechs as $mech => $any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if ($mech == 'X-FACEBOOK-PLATFORM') { if (@$this->cfg['fb_access_token']) { break; } } else { // else try first of the available methods break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if ($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } elseif ($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } elseif ($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if (!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach ($query->childrens as $child) { if ($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach ($child->childrens as $group) { if ($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if (!$emited) { $this->ev->emit('on_roster_update'); } } // if managing roster // catch contact vcard results if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if (@$this->roster[$stanza->from]) { $this->roster[$stanza->from]->vcard = $query; } } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if (!$emited) { $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if ($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if ($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } elseif ($type == 'unavailable') { if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) { unset($this->roster[$jid->bare]->resources[$jid->resource]); } } } // if managing subscription requests // we need to automate stuff here if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if ($this->manage_subscribe == "mutual") { $this->subscribe($stanza->from); } } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if ($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach ($query->childrens as $k => $child) { if ($child->name == 'identity') { - //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; + //echo 'identity category:'.@$child->attrs['category'].', type:'. + // @$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } elseif ($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } elseif ($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach ($query->childrens as $k => $child) { if ($child->name == 'item') { - //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; + //echo 'item jid:'.@$child->attrs['jid'].', name:'. + // @$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } /** * Used to define JAXL_CWD in tests. */ public static function dummy() { // Do nothing. } } diff --git a/tests/test_xmpp_msg.php b/tests/test_xmpp_msg.php index 7514a95..c421aab 100644 --- a/tests/test_xmpp_msg.php +++ b/tests/test_xmpp_msg.php @@ -1,87 +1,89 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ JAXL::dummy(); /** * * @author abhinavsingh * */ class XMPPMsgTest extends PHPUnit_Framework_TestCase { public function test_xmpp_msg() { $msg = new XMPPMsg(array('to' => '[email protected]', 'from' => '[email protected]/~', 'type' => 'chat'), 'hi', 'thread1'); $this->assertEquals( array( 'from' => '[email protected]/~', 'to' => '[email protected]', 'to_node' => '2', - 'to_string' => '<message xmlns="jabber:client" to="[email protected]" from="[email protected]/~" type="chat"><body>hi</body><thread>thread1</thread></message>', + 'to_string' => '<message xmlns="jabber:client" to="[email protected]" from="[email protected]/~" type="chat">' . + '<body>hi</body><thread>thread1</thread></message>', ), array( 'from' => $msg->from, 'to' => $msg->to, 'to_node' => $msg->to_node, 'to_string' => $msg->to_string(), ) ); $msg->to = '[email protected]/sp'; $msg->body = 'hello world'; $msg->subject = 'some subject'; $this->assertEquals( array( 'from' => '[email protected]/~', 'to' => '[email protected]/sp', 'to_node' => '4', - 'to_string' => '<message xmlns="jabber:client" to="[email protected]/sp" from="[email protected]/~" type="chat"><body>hello world</body><thread>thread1</thread><subject>some subject</subject></message>', + 'to_string' => '<message xmlns="jabber:client" to="[email protected]/sp" from="[email protected]/~" type="chat">' . + '<body>hello world</body><thread>thread1</thread><subject>some subject</subject></message>', ), array( 'from' => $msg->from, 'to' => $msg->to, 'to_node' => $msg->to_node, 'to_string' => $msg->to_string(), ) ); } } diff --git a/tests/test_xmpp_stanza.php b/tests/test_xmpp_stanza.php index b041b72..1780c04 100644 --- a/tests/test_xmpp_stanza.php +++ b/tests/test_xmpp_stanza.php @@ -1,76 +1,77 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ JAXL::dummy(); /** * * @author abhinavsingh * */ class XMPPStanzaTest extends PHPUnit_Framework_TestCase { public function test_xmpp_stanza_nested() { $stanza = new JAXLXml('message', array('to' => '[email protected]', 'from' => '[email protected]')); $stanza ->c('body')->attrs(array('xml:lang' => 'en'))->t('hello')->up() ->c('thread')->t('1234')->up() ->c('nested') ->c('nest')->t('nest1')->up() ->c('nest')->t('nest2')->up() ->c('nest')->t('nest3')->up()->up() ->c('c')->attrs(array('hash' => '84jsdmnskd')); $this->assertEquals( - '<message to="[email protected]" from="[email protected]"><body xml:lang="en">hello</body><thread>1234</thread><nested><nest>nest1</nest><nest>nest2</nest><nest>nest3</nest></nested><c hash="84jsdmnskd"></c></message>', + '<message to="[email protected]" from="[email protected]"><body xml:lang="en">hello</body><thread>1234</thread><nested>' . + '<nest>nest1</nest><nest>nest2</nest><nest>nest3</nest></nested><c hash="84jsdmnskd"></c></message>', $stanza->to_string() ); } public function test_xmpp_stanza_from_jaxl_xml() { // xml to stanza test $xml = new JAXLXml('message', NS_JABBER_CLIENT, array('to' => '[email protected]', 'from' => '[email protected]/q')); $stanza = new XMPPStanza($xml); $stanza->c('body')->t('hello world'); echo $stanza->to."\n"; echo $stanza->to_string()."\n"; } } diff --git a/xep/xep_0045.php b/xep/xep_0045.php index d7f8368..70866ef 100644 --- a/xep/xep_0045.php +++ b/xep/xep_0045.php @@ -1,118 +1,120 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_MUC', 'http://jabber.org/protocol/muc'); class XEP_0045 extends XMPPXep { // // abstract method // public function init() { return array(); } public function send_groupchat($room_jid, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type' => 'groupchat', 'to' => (($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid), 'from' => $this->jaxl->full_jid->to_string() ), $body, $thread, $subject ); $this->jaxl->send($msg); } // // api methods (occupant use case) // // room_full_jid simply means room jid with nick name as resource public function get_join_room_pkt($room_full_jid, $options) { $pkt = $this->jaxl->get_pres_pkt( array( 'from' => $this->jaxl->full_jid->to_string(), 'to' => (($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid) ) ); $x = $pkt->c('x', NS_MUC); if (isset($options['no_history'])) { $x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0)); } return $x; } public function join_room($room_full_jid, $options = array()) { $pkt = $this->get_join_room_pkt($room_full_jid, $options); $this->jaxl->send($pkt); } public function get_leave_room_pkt($room_full_jid) { - return $this->jaxl->get_pres_pkt( - array('type' => 'unavailable', 'from' => $this->jaxl->full_jid->to_string(), 'to' => (($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid)) - ); + return $this->jaxl->get_pres_pkt(array( + 'type' => 'unavailable', + 'from' => $this->jaxl->full_jid->to_string(), + 'to' => ($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid + )); } public function leave_room($room_full_jid) { $pkt = $this->get_leave_room_pkt($room_full_jid); $this->jaxl->send($pkt); } // // api methods (moderator use case) // // // event callbacks // } diff --git a/xep/xep_0060.php b/xep/xep_0060.php index 23053b2..331be35 100644 --- a/xep/xep_0060.php +++ b/xep/xep_0060.php @@ -1,145 +1,149 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_PUBSUB', 'http://jabber.org/protocol/pubsub'); class XEP_0060 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods (entity use case) // // // api methods (subscriber use case) // public function get_subscribe_pkt($service, $node, $jid = null) { $child = new JAXLXml('pubsub', NS_PUBSUB); - $child->c('subscribe', null, array('node' => $node, 'jid' => ($jid ? $jid : $this->jaxl->full_jid->to_string()))); + $child->c( + 'subscribe', + null, + array('node' => $node, 'jid' => ($jid ? $jid : $this->jaxl->full_jid->to_string())) + ); return $this->get_iq_pkt($service, $child); } public function subscribe($service, $node, $jid = null) { $this->jaxl->send($this->get_subscribe_pkt($service, $node, $jid)); } public function unsubscribe() { } public function get_subscription_options() { } public function set_subscription_options() { } public function get_node_items() { } // // api methods (publisher use case) // public function get_publish_item_pkt($service, $node, $item) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('publish', null, array('node' => $node)); $child->cnode($item); return $this->get_iq_pkt($service, $child); } public function publish_item($service, $node, $item) { $this->jaxl->send($this->get_publish_item_pkt($service, $node, $item)); } public function delete_item() { } // // api methods (owner use case) // public function get_create_node_pkt($service, $node) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('create', null, array('node' => $node)); return $this->get_iq_pkt($service, $child); } public function create_node($service, $node) { $this->jaxl->send($this->get_create_node_pkt($service, $node)); } // // event callbacks // // // local methods // // this always add attrs protected function get_iq_pkt($service, $child, $type = 'set') { return $this->jaxl->get_iq_pkt( array('type' => $type, 'from' => $this->jaxl->full_jid->to_string(), 'to' => $service), $child ); } } diff --git a/xep/xep_0114.php b/xep/xep_0114.php index df7f90d..6e9896a 100644 --- a/xep/xep_0114.php +++ b/xep/xep_0114.php @@ -1,97 +1,102 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_JABBER_COMPONENT_ACCEPT', 'jabber:component:accept'); class XEP_0114 extends XMPPXep { // // abstract method // public function init() { return array( 'on_connect' => 'start_stream', 'on_stream_start' => 'start_handshake', 'on_handshake_stanza' => 'logged_in', 'on_error_stanza' => 'logged_out' ); } // // event callbacks // public function start_stream() { - $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" to="'.$this->jaxl->jid->to_string().'" xmlns="'.NS_JABBER_COMPONENT_ACCEPT.'">'; + $xml = sprintf( + '<stream:stream xmlns:stream="%s" to="%s" xmlns="%s">', + NS_XMPP, + $this->jaxl->jid->to_string(), + NS_JABBER_COMPONENT_ACCEPT + ); $this->jaxl->send_raw($xml); } public function start_handshake($stanza) { _debug("starting component handshake"); $id = $stanza->id; $hash = strtolower(sha1($id.$this->jaxl->pass)); $stanza = new JAXLXml('handshake', null, $hash); $this->jaxl->send($stanza); } public function logged_in($stanza) { _debug("component handshake complete"); $this->jaxl->handle_auth_success(); return array("logged_in", 1); } public function logged_out($stanza) { if ($stanza->name == "error" && $stanza->ns == NS_XMPP) { $reason = $stanza->childrens[0]->name; $this->jaxl->handle_auth_failure($reason); $this->jaxl->send_end_stream(); return array("logged_out", 0); } else { _debug("uncatched stanza received in logged_out"); } } } diff --git a/xep/xep_0249.php b/xep/xep_0249.php index 995be3a..2438300 100644 --- a/xep/xep_0249.php +++ b/xep/xep_0249.php @@ -1,92 +1,98 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DIRECT_MUC_INVITATION', 'jabber:x:conference'); class XEP_0249 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods // - public function get_invite_pkt($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) - { + public function get_invite_pkt( + $to_bare_jid, + $room_jid, + $password = null, + $reason = null, + $thread = null, + $continue = null + ) { $xattrs = array('jid' => $room_jid); if ($password) { $xattrs['password'] = $password; } if ($reason) { $xattrs['reason'] = $reason; } if ($thread) { $xattrs['thread'] = $thread; } if ($continue) { $xattrs['continue'] = $continue; } return $this->jaxl->get_msg_pkt( array('from' => $this->jaxl->full_jid->to_string(), 'to' => $to_bare_jid), null, null, null, new JAXLXml('x', NS_DIRECT_MUC_INVITATION, $xattrs) ); } public function invite($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) { $this->jaxl->send($this->get_invite_pkt($to_bare_jid, $room_jid, $password, $reason, $thread, $continue)); } // // event callbacks // } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index ba9e62b..d05a149 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,724 +1,740 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass = null, $resource = null, $force_tls = false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; } if (isset($jid->domain)) { $xml .= 'to="'.$jid->domain.'" '; } $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism)); switch ($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if (strlen($pass) == 0) { $stanza->t('='); } break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if (!isset($decoded['digest-uri'])) { $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; } $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) { $decoded['qop'] = 'auth'; } $data = array_merge($decoded, array('nc' => $nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) { if (isset($decoded[$key])) { $response[$key] = $decoded[$key]; } } return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if (!$msg->id) { $msg->id = $this->get_id(); } if ($payload) { $msg->cnode($payload); } return $msg; } public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if (!$pres->id) { $pres->id = $this->get_id(); } if ($payload) { $pres->cnode($payload); } return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if (!$iq->id) { $iq->id = $this->get_id(); } if ($payload) { $iq->cnode($payload); } return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach ($data as $key => $value) { $return[] = $key . '="' . $value . '"'; } return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach (array('realm', 'cnonce', 'digest-uri') as $key) { if (!isset($data[$key])) { $data[$key] = ''; } } $pack = md5($user.':'.$data['realm'].':'.$pass); if (isset($data['authzid'])) { $a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']); } else { $a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']); } $a2 = 'AUTHENTICATE:'.$data['digest-uri']; - return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); + return md5(sprintf( + '%s:%s:%s:%s:%s:%s', + md5($a1), + $data['nonce'], + $data['nc'], + $data['cnonce'], + $data['qop'], + md5($a2) + )); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch ($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch ($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch ($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch ($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch ($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); - $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; + if ($starttls) { + if ($this->force_tls) { + $required = true; + } else { + $required = $starttls->exists('required') ? true : false; + } + } else { + $required = false; + } if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; /*} elseif ($comp) { // compression not supported due to bug in php stream filters $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; */ } else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch ($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch ($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch ($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } elseif ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } elseif ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch ($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch ($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch ($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if ($stanza->name == 'message') { $this->handle_message($stanza); } elseif ($stanza->name == 'presence') { $this->handle_presence($stanza); } elseif ($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch ($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } }
jaxl/JAXL
cadcaaaf31ad000071b188d5b7d51c0ada50d7ff
Fix Squiz.ControlStructures.ControlSignature.SpaceAfterKeyword
diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index 304c536..8e5d181 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,217 +1,217 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; - switch($argc) { + switch ($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if (is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if (is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if (is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; foreach ($attrs as $k => $v) { if ($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } public function t($text, $append = false) { if (!$append) { $this->rover->text = $text; } else { if ($this->rover->text === null) { $this->rover->text = ''; } $this->rover->text .= $text; } return $this; } public function c($name, $ns = null, $attrs = array(), $text = null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { if ($this->rover->parent) { $this->rover = &$this->rover->parent; } return $this; } public function top() { $this->rover = &$this; return $this; } public function exists($name, $ns = null, $attrs = array()) { foreach ($this->childrens as $child) { if ($ns) { if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) { return $child; } } elseif ($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } public function update($name, $ns = null, $attrs = array(), $text = null) { foreach ($this->childrens as $k => $child) { if ($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } public function to_string($parent_ns = null) { $xml = ''; $xml .= '<'.$this->name; if ($this->ns && $this->ns != $parent_ns) { $xml .= ' xmlns="'.$this->ns.'"'; } foreach ($this->attrs as $k => $v) { if (!is_null($v) && $v !== false) { $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; } } $xml .= '>'; foreach ($this->childrens as $child) { $xml .= $child->to_string($this->ns); } if ($this->text) { $xml .= htmlspecialchars($this->text); } $xml .= '</'.$this->name.'>'; return $xml; } } diff --git a/http/http_request.php b/http/http_request.php index 5015270..5640dc0 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,512 +1,512 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers = array(), $body = null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if (sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation // public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { - switch($event) { + switch ($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { - switch($event) { + switch ($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { - switch($event) { + switch ($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { - switch($event) { + switch ($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { - switch($event) { + switch ($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; if ($this->body === null) { $this->body = $rcvd; } else { $this->body .= $rcvd; } if ($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach ($form_data as $data) { //_debug("passing $data to multipart fsm"); if (!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if (!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if (!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { - switch($event) { + switch ($event) { case 'empty_line': return 'headers_received'; break; default: if (substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if (method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } } elseif (@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { $k = trim($k); $v = ltrim($v); // is expect header? if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if (strtolower($k) == 'content-type') { $ctype = explode(';', $v); if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if (strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); - switch($event) { + switch ($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if ($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { if (sizeof($args) == 0) { $body = null; $headers = array(); } if (sizeof($args) == 1) { // http headers or body only received if (is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } } elseif (sizeof($args) == 2) { // body and http headers both received if (is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { foreach ($headers as $k => $v) { $this->_send_header($k, $v); } } protected function _send_body($body) { $this->_send($body); } protected function _send_response($code, $headers = array(), $body = null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set if ($body && !isset($headers['Content-Length'])) { $headers['Content-Length'] = strlen($body); } // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); if ($body) { $this->_send_body(HTTP_CRLF.$body); } } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if (sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach ($query as $q) { $q = explode("=", $q); if (sizeof($q) == 1) { $q[1] = ""; } $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } } diff --git a/jaxl.php b/jaxl.php index 4172c9f..311281f 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,886 +1,886 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger if (isset($this->cfg['log_path'])) { JAXLLogger::$path = $this->cfg['log_path']; } //else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; } if (isset($this->cfg['log_level'])) { JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; } else { JAXLLogger::$level = $this->log_level; } // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true; if ($strict) { $this->add_exception_handlers(); } $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if (!is_dir($this->priv_dir)) { mkdir($this->priv_dir); } if (!is_dir($this->tmp_dir)) { mkdir($this->tmp_dir); } if (!is_dir($this->pid_dir)) { mkdir($this->pid_dir); } if (!is_dir($this->log_dir)) { mkdir($this->log_dir); } if (!is_dir($this->sock_dir)) { mkdir($this->sock_dir); } // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if (!is_array($xeps)) { $xeps = array($xeps); } foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri = 1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show = 'chat', $priority = 10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type' => 'chat', 'to' => $to, 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid = null, $cb = null) { $attrs = array( 'type' => 'get', 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) { $this->add_cb('on_stanza_id_'.$pkt->id, $cb); } $this->send($pkt); } public function get_roster($cb = null) { $pkt = $this->get_iq_pkt( array( 'type' => 'get', 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) { $this->add_cb('on_stanza_id_'.$pkt->id, $cb); } $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribed') )); } public function get_socket_path() { if (isset($this->cfg['protocol'])) { $protocol = $this->cfg['protocol']; } else { $protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp"); } return $protocol."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts = array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) { $this->add_cb('on_connect', array($this, 'start_stream')); } // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) { $this->enable_debug_shell(); } if (@$opts['--with-unix-sock']) { $this->enable_unix_sock(); } // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } else { // if connection to the destination fails if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); - switch($sig) { + switch ($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { - switch($event) { + switch ($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { - switch($event) { + switch ($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { - switch($event) { + switch ($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if ($mechanisms) { foreach ($mechanisms->childrens as $mechanism) { $mechs[$mechanism->text] = true; } } // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if ($pref_auth_exists) { $mech = $pref_auth; } else { // if pref auth doesn't exists, choose one from available mechanisms foreach ($mechs as $mech => $any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if ($mech == 'X-FACEBOOK-PLATFORM') { if (@$this->cfg['fb_access_token']) { break; } } else { // else try first of the available methods break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if ($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } elseif ($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } elseif ($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if (!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach ($query->childrens as $child) { if ($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach ($child->childrens as $group) { if ($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if (!$emited) { $this->ev->emit('on_roster_update'); } } // if managing roster // catch contact vcard results if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if (@$this->roster[$stanza->from]) { $this->roster[$stanza->from]->vcard = $query; } } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if (!$emited) { $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if ($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if ($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } elseif ($type == 'unavailable') { if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) { unset($this->roster[$jid->bare]->resources[$jid->resource]); } } } // if managing subscription requests // we need to automate stuff here if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if ($this->manage_subscribe == "mutual") { $this->subscribe($stanza->from); } } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if ($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach ($query->childrens as $k => $child) { if ($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } elseif ($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } elseif ($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach ($query->childrens as $k => $child) { if ($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } /** * Used to define JAXL_CWD in tests. */ public static function dummy() { // Do nothing. } } diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php index 6dbed80..82f2b28 100644 --- a/xmpp/xmpp_stanza.php +++ b/xmpp/xmpp_stanza.php @@ -1,190 +1,190 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; /** * Generic xmpp stanza object which provide convinient access pattern over xml objects * Also to be able to convert an existing xml object into stanza object (to get access patterns going) * this class doesn't extend xml, but infact works on a reference of xml object * If not provided during constructor, new xml object is created and saved as reference * * @author abhinavsingh * */ class XMPPStanza { private $xml; public function __construct($name, $attrs = array(), $ns = NS_JABBER_CLIENT) { if ($name instanceof JAXLXml) { $this->xml = $name; } else { $this->xml = new JAXLXml($name, $ns, $attrs); } } public function __call($method, $args) { return call_user_func_array(array($this->xml, $method), $args); } public function __get($prop) { - switch($prop) { + switch ($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': return @$this->xml->attrs[$prop] ? $this->xml->attrs[$prop] : null; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val = @$this->xml->attrs[$attr] ? $this->xml->attrs[$attr] : null; if (!$val) { return null; } $val = new XMPPJid($val); return $val->$key; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val = $this->xml->exists($prop); if (!$val) { return null; } return $val->text; break; default: return null; break; } } public function __set($prop, $val) { - switch($prop) { + switch ($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop = $val; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': $this->xml->attrs[$prop] = $val; return true; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val1 = @$this->xml->attrs[$attr]; if (!$val1) { $val1 = ''; } $val1 = new XMPPJid($val1); $val1->$key = $val; $this->xml->attrs[$attr] = $val1->to_string(); return true; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val1 = $this->xml->exists($prop); if (!$val1) { $this->xml->c($prop)->t($val)->up(); } else { $this->xml->update($prop, $val1->ns, $val1->attrs, $val); } return true; break; default: return null; break; } } } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index 346af45..a18d574 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,724 +1,724 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass = null, $resource = null, $force_tls = false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; } if (isset($jid->domain)) { $xml .= 'to="'.$jid->domain.'" '; } $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism)); - switch($mechanism) { + switch ($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if (strlen($pass) == 0) { $stanza->t('='); } break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if (!isset($decoded['digest-uri'])) { $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; } $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) { $decoded['qop'] = 'auth'; } $data = array_merge($decoded, array('nc' => $nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) { if (isset($decoded[$key])) { $response[$key] = $decoded[$key]; } } return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if (!$msg->id) { $msg->id = $this->get_id(); } if ($payload) { $msg->cnode($payload); } return $msg; } public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if (!$pres->id) { $pres->id = $this->get_id(); } if ($payload) { $pres->cnode($payload); } return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if (!$iq->id) { $iq->id = $this->get_id(); } if ($payload) { $iq->cnode($payload); } return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach ($data as $key => $value) { $return[] = $key . '="' . $value . '"'; } return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach (array('realm', 'cnonce', 'digest-uri') as $key) { if (!isset($data[$key])) { $data[$key] = ''; } } $pack = md5($user.':'.$data['realm'].':'.$pass); if (isset($data['authzid'])) { $a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']); } else { $a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']); } $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { - switch($event) { + switch ($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { - switch($event) { + switch ($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { - switch($event) { + switch ($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { - switch($event) { + switch ($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { - switch($event) { + switch ($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; /*} elseif ($comp) { // compression not supported due to bug in php stream filters $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; */ } else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { - switch($event) { + switch ($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { - switch($event) { + switch ($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { - switch($event) { + switch ($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } elseif ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } elseif ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { - switch($event) { + switch ($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { - switch($event) { + switch ($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { - switch($event) { + switch ($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if ($stanza->name == 'message') { $this->handle_message($stanza); } elseif ($stanza->name == 'presence') { $this->handle_presence($stanza); } elseif ($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { - switch($event) { + switch ($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } }
jaxl/JAXL
0be4536dbc3dbd807c4b272e24e44f9bae5c2358
Fix PSR2.Methods.FunctionClosingBrace.SpacingBeforeClose
diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php index bd6a470..ea694d6 100644 --- a/core/jaxl_clock.php +++ b/core/jaxl_clock.php @@ -1,129 +1,128 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class JAXLClock { // current clock time in microseconds private $tick = 0; // current Unix timestamp with microseconds public $time = null; // scheduled jobs public $jobs = array(); public function __construct() { $this->time = microtime(true); } public function __destruct() { _info("shutting down clock server..."); } public function tick($by = null) { // update clock if ($by) { $this->tick += $by; $this->time += $by / pow(10, 6); } else { $time = microtime(true); $by = $time - $this->time; $this->tick += $by * pow(10, 6); $this->time = $time; } // run scheduled jobs foreach ($this->jobs as $ref => $job) { if ($this->tick >= $job['scheduled_on'] + $job['after']) { //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".$job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); call_user_func($job['cb'], $job['args']); if (!$job['is_periodic']) { unset($this->jobs[$ref]); } else { $job['scheduled_on'] = $this->tick; $job['runs']++; $this->jobs[$ref] = $job; } } } } // calculate execution time of callback public function tc($callback, $args = null) { - } // callback after $time microseconds public function call_fun_after($time, $callback, $args = null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => false, 'runs' => 0 ); return sizeof($this->jobs); } // callback periodically after $time microseconds public function call_fun_periodic($time, $callback, $args = null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => true, 'runs' => 0 ); return sizeof($this->jobs); } // cancel a previously scheduled callback public function cancel_fun_call($ref) { unset($this->jobs[$ref-1]); } } diff --git a/core/jaxl_event.php b/core/jaxl_event.php index b863584..4011471 100644 --- a/core/jaxl_event.php +++ b/core/jaxl_event.php @@ -1,131 +1,130 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * following kind of events are possible: * 1) hook i.e. if a callback for such an event is registered, calling function is responsible for the workflow from their on * 2) filter i.e. calling function will manipulate passed arguments and modified arguments will be passed to next chain of filter * * As a rule of thumb, only 1 hook can be registered for an event, while more than 1 filter is allowed for an event * hook and filter both cannot be applied on an event * * @author abhinavsingh * */ class JAXLEvent { protected $common = array(); public $reg = array(); public function __construct($common) { $this->common = $common; } public function __destruct() { - } // add callback on a event // returns a reference to be used while deleting callback // callback'd method must return TRUE to be persistent // if none returned or FALSE, callback will be removed automatically public function add($ev, $cb, $pri) { if (!isset($this->reg[$ev])) { $this->reg[$ev] = array(); } $ref = sizeof($this->reg[$ev]); $this->reg[$ev][] = array($pri, $cb); return $ev."-".$ref; } // emit event to notify registered callbacks // is a pqueue required here for performance enhancement // in case we have too many cbs on a specific event? public function emit($ev, $data = array()) { $data = array_merge($this->common, $data); $cbs = array(); if (!isset($this->reg[$ev])) { return $data; } foreach ($this->reg[$ev] as $cb) { if (!isset($cbs[$cb[0]])) { $cbs[$cb[0]] = array(); } $cbs[$cb[0]][] = $cb[1]; } foreach ($cbs as $pri => $cb) { foreach ($cb as $c) { $ret = call_user_func_array($c, $data); // this line is for fixing situation where callback function doesn't return an array type // in such cases next call of call_user_func_array will report error since $data is not an array type as expected // things will change in future, atleast put the callback inside a try/catch block // here we only check if there was a return, if yes we update $data with return value // this is bad design, need more thoughts, should work as of now if ($ret) { $data = $ret; } } } unset($cbs); return $data; } // remove previous registered callback public function del($ref) { $ref = explode("-", $ref); unset($this->reg[$ref[0]][$ref[1]]); } public function exists($ev) { $ret = isset($this->reg[$ev]); //_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists")); return $ret; } } diff --git a/core/jaxl_sock5.php b/core/jaxl_sock5.php index efaca10..5d1b6d1 100644 --- a/core/jaxl_sock5.php +++ b/core/jaxl_sock5.php @@ -1,133 +1,131 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ class JAXLSock5 { private $client = null; protected $transport = null; protected $ip = null; protected $port = null; public function __construct($transport = 'tcp') { $this->transport = $transport; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } public function __destruct() { - } public function connect($ip, $port = 1080) { $this->ip = $ip; $this->port = $port; $sock_path = $this->_sock_path(); if ($this->client->connect($sock_path)) { _debug("established connection to $sock_path"); return true; } else { _error("unable to connect $sock_path"); return false; } } // // Three phases of SOCK5 // // Negotiation pkt consists of 3 part: // 0x05 => Sock protocol version // 0x01 => Number of method identifier octet // // Following auth methods are defined: // 0x00 => No authentication required // 0x01 => GSSAPI // 0x02 => USERNAME/PASSWORD // 0x03 to 0x7F => IANA ASSIGNED // 0x80 to 0xFE => RESERVED FOR PRIVATE METHODS // 0xFF => NO ACCEPTABLE METHODS public function negotiate() { $pkt = pack("C3", 0x05, 0x01, 0x00); $this->client->send($pkt); // enter sub-negotiation state } public function relay_request() { // enter wait for reply state } public function send_data() { - } // // Socket client callback // public function on_response($raw) { _debug($raw); } // // Private // protected function _sock_path() { return $this->transport.'://'.$this->ip.':'.$this->port; } } diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index a6fd559..304c536 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,218 +1,217 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if (is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if (is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if (is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { - } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; foreach ($attrs as $k => $v) { if ($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } public function t($text, $append = false) { if (!$append) { $this->rover->text = $text; } else { if ($this->rover->text === null) { $this->rover->text = ''; } $this->rover->text .= $text; } return $this; } public function c($name, $ns = null, $attrs = array(), $text = null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { if ($this->rover->parent) { $this->rover = &$this->rover->parent; } return $this; } public function top() { $this->rover = &$this; return $this; } public function exists($name, $ns = null, $attrs = array()) { foreach ($this->childrens as $child) { if ($ns) { if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) { return $child; } } elseif ($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } public function update($name, $ns = null, $attrs = array(), $text = null) { foreach ($this->childrens as $k => $child) { if ($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } public function to_string($parent_ns = null) { $xml = ''; $xml .= '<'.$this->name; if ($this->ns && $this->ns != $parent_ns) { $xml .= ' xmlns="'.$this->ns.'"'; } foreach ($this->attrs as $k => $v) { if (!is_null($v) && $v !== false) { $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; } } $xml .= '>'; foreach ($this->childrens as $child) { $xml .= $child->to_string($this->ns); } if ($this->text) { $xml .= htmlspecialchars($this->text); } $xml .= '</'.$this->name.'>'; return $xml; } } diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index f525cf8..64b889c 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,149 +1,148 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 5) { echo "Usage: $argv[0] host jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[2], 'pass' => $argv[3], 'host' => $argv[1], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC '0203', // Delayed Delivery '0199' // XMPP Ping )); // // add necessary event callbacks here // $_room_full_jid = $argv[4]."/".$argv[5]; $room_full_jid = new XMPPJid($_room_full_jid); function on_auth_success_callback() { global $client, $room_full_jid; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // join muc room $client->xeps['0045']->join_room($room_full_jid); } $client->add_cb('on_auth_success', 'on_auth_success_callback'); function on_auth_failure_callback($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); } $client->add_cb('on_auth_failure', 'on_auth_failure_callback'); function on_groupchat_message_callback($stanza) { global $client; $from = new XMPPJid($stanza->from); $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); if ($from->resource) { echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } else { $subject = $stanza->exists('subject'); if ($subject) { echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } } } $client->add_cb('on_groupchat_message', 'on_chat_message_callback'); function on_presence_stanza_callback($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { if (($status = $x->exists('status', null, array('code' => '110'))) !== false) { $item = $x->exists('item'); _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); } else { _info("xmlns #user have no x child element"); } } else { _warning("=======> odd case 1"); } } elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) { // stanza from other users received if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; } else { _warning("=======> odd case 2"); } } else { _warning("=======> odd case 3"); } - } $client->add_cb('on_presence_stanza', 'on_presence_stanza_callback'); function on_disconnect_callback() { _info("got on_disconnect cb"); } $client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/register_user.php b/examples/register_user.php index 0ed15cd..14591d4 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,170 +1,169 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // $form = array(); function wait_for_register_response($event, $args) { global $client, $form; if ($event == 'stanza_cb') { $stanza = $args[0]; if ($stanza->name == 'iq') { $form['type'] = $stanza->attrs['type']; if ($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } elseif ($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } } } else { _notice("unhandled event $event rcvd"); } } function wait_for_register_form($event, $args) { global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if ($query) { $instructions = $query->exists('instructions'); if ($instructions) { echo $instructions->text.PHP_EOL; } foreach ($query->childrens as $k => $child) { if ($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); - } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // function on_stream_features_callback($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; } $client->add_cb('on_stream_features', 'on_stream_features_callback'); function on_disconnect_callback() { global $form; _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); } $client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(); // // if registration was successful // try to connect with newly registered account // if ($form['type'] == 'result') { _info("connecting newly registered user account"); $client = new JAXL(array( 'jid' => $form['username'].'@'.$argv[1], 'pass' => $form['password'], 'log_level' => JAXL_DEBUG )); function on_auth_success_callback() { global $client; $client->set_status('Available'); } $client->add_cb('on_auth_success', 'on_auth_success_callback'); $client->start(); } echo "done\n"; diff --git a/xep/xep_0060.php b/xep/xep_0060.php index 318f9c7..26d24ff 100644 --- a/xep/xep_0060.php +++ b/xep/xep_0060.php @@ -1,150 +1,145 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_PUBSUB', 'http://jabber.org/protocol/pubsub'); class XEP_0060 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods (entity use case) // // // api methods (subscriber use case) // public function get_subscribe_pkt($service, $node, $jid = null) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('subscribe', null, array('node' => $node, 'jid' => ($jid ? $jid : $this->jaxl->full_jid->to_string()))); return $this->get_iq_pkt($service, $child); } public function subscribe($service, $node, $jid = null) { $this->jaxl->send($this->get_subscribe_pkt($service, $node, $jid)); } public function unsubscribe() { - } public function get_subscription_options() { - } public function set_subscription_options() { - } public function get_node_items() { - } // // api methods (publisher use case) // public function get_publish_item_pkt($service, $node, $item) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('publish', null, array('node' => $node)); $child->cnode($item); return $this->get_iq_pkt($service, $child); } public function publish_item($service, $node, $item) { $this->jaxl->send($this->get_publish_item_pkt($service, $node, $item)); } public function delete_item() { - } // // api methods (owner use case) // public function get_create_node_pkt($service, $node) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('create', null, array('node' => $node)); return $this->get_iq_pkt($service, $child); } public function create_node($service, $node) { $this->jaxl->send($this->get_create_node_pkt($service, $node)); } // // event callbacks // // // local methods // // this always add attrs protected function get_iq_pkt($service, $child, $type = 'set') { return $this->jaxl->get_iq_pkt( array('type' => $type, 'from' => $this->jaxl->full_jid->to_string(), 'to' => $service), $child ); } } diff --git a/xmpp/xmpp_xep.php b/xmpp/xmpp_xep.php index 1b88461..f5d926e 100644 --- a/xmpp/xmpp_xep.php +++ b/xmpp/xmpp_xep.php @@ -1,66 +1,65 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh * */ abstract class XMPPXep { // init() method defines various callbacks // required by this xep extension abstract public function init(); //abstract public $description; //abstract public $dependencies; // reference to jaxl instance // which required me protected $jaxl = null; public function __construct($jaxl) { $this->jaxl = $jaxl; } public function __destruct() { - } }
jaxl/JAXL
41fd513844b6bc6757719b47c0f7d67d44c76a46
Show NULL on error
diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index 801291e..dc0c6e9 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,238 +1,243 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; public function __construct($stream_context = null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ public function connect($socket_path) { if (gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); if (sizeof($path_parts) == 3) { $this->port = $path_parts[2]; } _info("trying ".$socket_path); if ($this->stream_context) { $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); } else { $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); } } else { $this->fd = &$socket_path; } if ($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { - _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); + _error(sprintf( + "unable to connect %s with error no: %s, error str: %s", + is_null($socket_path) ? 'NULL' : $socket_path, + is_null($this->errno) ? 'NULL' : $this->errno, + is_null($this->errstr) ? 'NULL' : $this->errstr + )); $this->disconnect(); return false; } } public function disconnect() { JAXLLoop::unwatch($this->fd, array( 'read' => true, 'write' => true )); if (is_resource($this->fd)) { fclose($this->fd); } $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); return $ret; } public function send($data) { $this->obuffer .= $data; // add watch for write events if ($this->writing) { return; } JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if ($bytes === 0) { $meta = stream_get_meta_data($fd); if ($meta['eof'] === true) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); if ($bytes > 0) { _debug($raw); } // callback if ($this->recv_cb) { call_user_func($this->recv_cb, $raw); } } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if (strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } }
jaxl/JAXL
b30f6456624f3450ac145e8311cbdccafaed67b4
Check the resource before close it
diff --git a/core/jaxl_cli.php b/core/jaxl_cli.php index 75114c2..51e5517 100644 --- a/core/jaxl_cli.php +++ b/core/jaxl_cli.php @@ -1,105 +1,107 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLCli { public static $counter = 0; private $in = null; private $quit_cb = null; private $recv_cb = null; private $recv_chunk_size = 1024; public function __construct($recv_cb = null, $quit_cb = null) { $this->recv_cb = $recv_cb; $this->quit_cb = $quit_cb; // catch read event on stdin $this->in = fopen('php://stdin', 'r'); stream_set_blocking($this->in, false); JAXLLoop::watch($this->in, array( 'read' => array(&$this, 'on_read_ready') )); } public function __destruct() { - @fclose($this->in); + if (is_resource($this->in)) { + fclose($this->in); + } } public function stop() { JAXLLoop::unwatch($this->in, array( 'read' => true )); } public function on_read_ready($in) { $raw = @fread($in, $this->recv_chunk_size); if (ord($raw) == 10) { // enter key JAXLCli::prompt(false); return; } elseif (trim($raw) == 'quit') { $this->stop(); $this->in = null; if ($this->quit_cb) { call_user_func($this->quit_cb); } return; } if ($this->recv_cb) { call_user_func($this->recv_cb, $raw); } } public static function prompt($inc = true) { if ($inc) { ++self::$counter; } echo "jaxl ".self::$counter."> "; } } diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php index b5a99a7..df4d21b 100644 --- a/core/jaxl_pipe.php +++ b/core/jaxl_pipe.php @@ -1,120 +1,122 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * bidirectional communication pipes for processes * * This is how this will be (when complete): * $pipe = new JAXLPipe() will return an array of size 2 * $pipe[0] represents the read end of the pipe * $pipe[1] represents the write end of the pipe * * Proposed functionality might even change (currently consider this as experimental) * * @author abhinavsingh * */ class JAXLPipe { protected $perm = 0600; protected $recv_cb = null; protected $fd = null; protected $client = null; public $name = null; public function __construct($name, $read_cb = null) { $pipes_folder = JAXL_CWD.'/.jaxl/pipes'; if (!is_dir($pipes_folder)) { mkdir($pipes_folder); } $this->ev = new JAXLEvent(); $this->name = $name; $this->read_cb = $read_cb; $pipe_path = $this->get_pipe_file_path(); if (!file_exists($pipe_path)) { posix_mkfifo($pipe_path, $this->perm); $this->fd = fopen($pipe_path, 'r+'); if (!$this->fd) { _error("unable to open pipe"); } else { _debug("pipe opened using path $pipe_path"); _notice("Usage: $ echo 'Hello World!' > $pipe_path"); $this->client = new JAXLSocketClient(); $this->client->connect($this->fd); $this->client->set_callback(array(&$this, 'on_data')); } } else { _error("pipe with name $name already exists"); } } public function __destruct() { - @fclose($this->fd); + if (is_resource($this->fd)) { + fclose($this->fd); + } @unlink($this->get_pipe_file_path()); _debug("unlinking pipe file"); } public function get_pipe_file_path() { return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe'; } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function on_data($data) { // callback if ($this->recv_cb) { call_user_func($this->recv_cb, $data); } } } diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index abbb065..801291e 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,236 +1,238 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; public function __construct($stream_context = null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ public function connect($socket_path) { if (gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); if (sizeof($path_parts) == 3) { $this->port = $path_parts[2]; } _info("trying ".$socket_path); if ($this->stream_context) { $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); } else { $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); } } else { $this->fd = &$socket_path; } if ($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); $this->disconnect(); return false; } } public function disconnect() { JAXLLoop::unwatch($this->fd, array( 'read' => true, 'write' => true )); - @fclose($this->fd); + if (is_resource($this->fd)) { + fclose($this->fd); + } $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); return $ret; } public function send($data) { $this->obuffer .= $data; // add watch for write events if ($this->writing) { return; } JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if ($bytes === 0) { $meta = stream_get_meta_data($fd); if ($meta['eof'] === true) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); if ($bytes > 0) { _debug($raw); } // callback if ($this->recv_cb) { call_user_func($this->recv_cb, $raw); } } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if (strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } } diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index 03e64dd..580ef32 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,267 +1,273 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLSocketServer { public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; public function __construct($path, $accept_cb, $request_cb) { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; $ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog))); if (($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { if (@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); } else { _error("unable to set non block flag"); } } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } public function __destruct() { _info("shutting down socket server"); } public function read($client_id) { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } public function send($client_id, $data) { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } public function close($client_id) { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } public function on_server_accept_ready($server) { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); if (!$client) { _error("unable to accept new client conn"); return; } if (@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do if ($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); } else { // if no accept callback is registered // close the accepted connection - @fclose($client); + if (is_resource($client)) { + fclose($client); + } $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } } else { _error("unable to set non block flag"); } } public function on_client_read_ready($client) { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); if ($bytes === 0) { $meta = stream_get_meta_data($client); if ($meta['eof'] === true) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); - @fclose($client); + if (is_resource($client)) { + fclose($client); + } unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; if ($this->request_cb) { call_user_func($this->request_cb, $client_id, $total); } $this->clients[$client_id]['ibuffer'] = ''; } public function on_client_write_ready($client) { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); if ($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; } elseif ($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler if (strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { - @fclose($client); + if (is_resource($client)) { + fclose($client); + } $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } } catch (JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // protected function add_read_cb($client_id) { if ($this->clients[$client_id]['reading']) { return; } JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } protected function add_write_cb($client_id) { if ($this->clients[$client_id]['writing']) { return; } JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } protected function del_read_cb($client_id) { if (!$this->clients[$client_id]['reading']) { return; } JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } protected function del_write_cb($client_id) { if (!$this->clients[$client_id]['writing']) { return; } JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } }
jaxl/JAXL
a156e3749b0eb0ccdd3de366897c07381c72ecbf
Skip the test until XEP-0029 isn't implemented
diff --git a/tests/test_xmpp_jid.php b/tests/test_xmpp_jid.php index 211d201..c30c75f 100644 --- a/tests/test_xmpp_jid.php +++ b/tests/test_xmpp_jid.php @@ -1,100 +1,101 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ JAXL::dummy(); /** * * @author abhinavsingh * */ class XMPPJidTest extends PHPUnit_Framework_TestCase { /** * @dataProvider jidPositiveProvider */ public function test_xmpp_jid_construct($jidText) { $jid = new XMPPJid($jidText); $this->assertEquals($jidText, $jid->to_string()); } public function jidPositiveProvider() { return array( array('domain'), array('domain.tld'), array('1@domain'), array('[email protected]'), array('domain/res'), array('domain.tld/res'), array('1@domain/res'), array('[email protected]/res'), array('component.domain.tld'), array('[email protected]/res'), array('[email protected]/@res'), array('[email protected]//res') ); } /** * @dataProvider jidNegativeProvider * @expectedException InvalidArgumentException + * @requires function XEP_0029::validateJID */ public function testJidNegative($jidText) { $jid = new XMPPJid($jidText); } public function jidNegativeProvider() { return array( array('"@domain'), array('&@domain'), array("'@domain"), array('/@domain'), array(':@domain'), array('<@domain'), array('>@domain'), array('@@domain'), array("\x7F" . '@domain'), array("\xFF\xFE" . '@domain'), array("\xFF\xFF" . '@domain') ); } }
jaxl/JAXL
00262880cc8b89e2f2eeeee20613a5b863797094
Add some tags
diff --git a/jaxl.php b/jaxl.php index 6e99d78..eb1cee6 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,765 +1,785 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); - // event callback engine for xmpp stream lifecycle + + /** + * Event callback engine for XMPP stream lifecycle. + * @var JAXLEvent + */ protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) - - public function __construct($config) { + + /** + * @param array $config + */ + public function __construct(array $config) { $this->cfg = $config; // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } - - public function require_xep($xeps) { + + /** + * @param array $xeps + */ + public function require_xep(array $xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } - + + /** + * Add callback. + * + * @see JAXLEvent::add + * + * @param string $ev Event to subscribe. + * @param callable? $cb + * @param number $pri + * @return string + */ public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { $protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp"); if ($this->cfg['protocol']) $protocol = $this->cfg['protocol']; return $protocol."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) {
jaxl/JAXL
e953cc87971363981c838ba26dd28d746cb438e2
Logging customizations
diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index fa836d6..77905b4 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,199 +1,206 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; - + + /** @var JAXLXml[] */ public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if(is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if(is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if(is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; foreach($attrs as $k=>$v) { if($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } public function t($text, $append=FALSE) { if(!$append) { $this->rover->text = $text; } else { if($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; } return $this; } public function c($name, $ns=null, $attrs=array(), $text=null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { if($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } public function top() { $this->rover = &$this; return $this; } + /** + * @param string $name + * @param string $ns + * @param array $attrs + * @return JAXLXml|bool + */ public function exists($name, $ns=null, $attrs=array()) { foreach($this->childrens as $child) { if($ns) { if($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; } else if($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } public function update($name, $ns=null, $attrs=array(), $text=null) { foreach($this->childrens as $k=>$child) { if($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } public function to_string($parent_ns=null) { $xml = ''; $xml .= '<'.$this->name; if($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; foreach($this->attrs as $k=>$v) if(!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; foreach($this->childrens as $child) $xml .= $child->to_string($this->ns); if($this->text) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } } ?>
jaxl/JAXL
61cdb7481bd6e804e783541604dc8d7f3133bfc3
Setup CLI app. Fixes #66
diff --git a/jaxlctl b/jaxlctl index a1f1b95..1b1f67a 100755 --- a/jaxlctl +++ b/jaxlctl @@ -1,190 +1,193 @@ #!/usr/bin/env php <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ +error_reporting(E_ALL | E_STRICT); +date_default_timezone_set('UTC'); + $params = $argv; $exe = array_shift($params); $command = array_shift($params); require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // TODO: an abstract JAXLCtlCommand class // with seperate class per command // a mechanism to register new commands class JAXLCtl { protected $ipc = null; protected $buffer = ''; protected $buffer_cb = null; protected $cli = null; public $dots = "....... "; protected $symbols = array(); public function __construct($command, $params) { global $exe; if(method_exists($this, $command)) { $r = call_user_func_array(array(&$this, $command), $params); if(sizeof($r) == 2) { list($buffer_cb, $quit_cb) = $r; $this->buffer_cb = $buffer_cb; $this->cli = new JAXLCli(array(&$this, 'on_terminal_input'), $quit_cb); $this->run(); } else { _colorize("oops! internal command error", JAXL_ERROR); exit; } } else { _colorize("error: invalid command '$command' received", JAXL_ERROR); _colorize("type '$exe help' for list of available commands", JAXL_NOTICE); exit; } } public function run() { JAXLCli::prompt(); JAXLLoop::run(); } public function on_terminal_input($raw) { $raw = trim($raw); $last = substr($raw, -1, 1); if($last == ";") { // dispatch to buffer callback call_user_func($this->buffer_cb, $this->buffer.$raw); $this->buffer = ''; } else if($last == '\\') { $this->buffer .= substr($raw, 0, -1); echo $this->dots; } else { // buffer command $this->buffer .= $raw."; "; echo $this->dots; } } public static function print_help() { global $exe; _colorize("Usage: $exe command [options...]\n", JAXL_INFO); _colorize("Commands:", JAXL_NOTICE); _colorize(" help This help text", JAXL_DEBUG); _colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG); _colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG); echo "\n"; } protected function help() { JAXLCtl::print_help(); exit; } // // shell command // protected function shell() { return array(array(&$this, 'on_shell_input'), array(&$this, 'on_shell_quit')); } private function _eval($raw, $symbols) { extract($symbols); eval($raw); $g = get_defined_vars(); unset($g['raw']); unset($g['symbols']); return $g; } public function on_shell_input($raw) { $this->symbols = $this->_eval($raw, $this->symbols); JAXLCli::prompt(); } public function on_shell_quit() { exit; } // // debug command // protected function debug($sock_path) { $this->ipc = new JAXLSocketClient(); $this->ipc->set_callback(array(&$this, 'on_debug_response')); $this->ipc->connect('unix://'.$sock_path); return array(array(&$this, 'on_debug_input'), array(&$this, 'on_debug_quit')); } public function on_debug_response($raw) { $ret = unserialize($raw); print_r($ret); echo "\n"; JAXLCli::prompt(); } public function on_debug_input($raw) { $this->ipc->send($this->buffer.$raw); } public function on_debug_quit() { $this->ipc->disconnect(); exit; } } // we atleast need a command argument if($argc < 2) { JAXLCtl::print_help(); exit; } $ctl = new JAXLCtl($command, $params); echo "done\n"; ?>
jaxl/JAXL
433fae7113be6d7b7659becb776b5cb755f51f3a
Add notes for contributors
diff --git a/README.md b/README.md index 58de1de..4a8fbe9 100644 --- a/README.md +++ b/README.md @@ -1,40 +1,46 @@ Jaxl v3.0.1 ----------- Jaxl v3.x is a successor of v2.x (and is NOT backward compatible), carrying a lot of code from v2.x while throwing away the ugly parts. A lot of components have been re-written keeping in mind the feedback from the developer community over the last 4 years. Also Jaxl shares a few philosophies from my experience with erlang and python languages. Jaxl is an asynchronous, non-blocking I/O, event based PHP library for writing custom TCP/IP client and server implementations. From it's previous versions, library inherits a full blown stable support for [XMPP protocol stack](https://github.com/frost-nzcr4/JAXL/tree/v3.0.1/xmpp). In v3.0, support for [HTTP protocol stack](https://github.com/frost-nzcr4/JAXL/tree/v3.0.1/http) has also been added. At the heart of every protocol stack sits the [Core stack](https://github.com/frost-nzcr4/JAXL/tree/v3.0.1/core). It contains all the building blocks for everything that we aim to do with Jaxl library. Both XMPP and HTTP protocol stacks are written on top of the Core stack. Infact the source code of protocol implementations knows nothing about the standard (inbuilt) PHP socket and stream methods. -## Contribute to JAXL - -JAXL v3.0.1 adopt [PSR-2](http://www.php-fig.org/psr/psr-2/). -Check your PRs with [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer): - -```ShellSession -/path/to/phpcs -``` - [Examples](https://github.com/frost-nzcr4/JAXL/tree/v3.0.1/examples/) [Documentation](http://jaxl.readthedocs.org/) [Group and Mailing List](https://groups.google.com/forum/#!forum/jaxl) [Create a bug/issue](https://github.com/abhinavsingh/JAXL/issues/new) [Author](http://abhinavsingh.com/) + +## Contributing + +JAXL v3.0.1 adopt [PSR-2](http://www.php-fig.org/psr/psr-2/). +To make it easier to maintain the code contribute your changes after they have +passed [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer) +and [PHPUnit](https://github.com/sebastianbergmann/phpunit). If possible, add +a unit tests for your changes into the *tests* folder. + +To know current errors and failed tests, run: + +```ShellSession +./vendor/bin/phpcs +./vendor/bin/phpunit +```
jaxl/JAXL
8469582030c5281a48dfd8d03269afa3e1142537
Adding JAXLXml->x() for raw XML children This makes things like XEP-0071 possible
diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index fa836d6..d0ff4c0 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,199 +1,214 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. -* +* */ /** - * + * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml - * + * * @author abhinavsingh * */ class JAXLXml { - + public $name; public $ns = null; public $attrs = array(); + public $xml = null; public $text = null; - + public $childrens = array(); public $parent = null; public $rover = null; - + public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); - + $this->name = $argv[0]; - + switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if(is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if(is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if(is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } - + $this->rover = &$this; } - + public function __destruct() { - + } - + public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } - + public function match_attrs($attrs) { $matches = true; foreach($attrs as $k=>$v) { if($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } - + + public function x($xml, $append=FALSE) { + if(!$append) { + $this->rover->xml = $xml; + } + else { + if($this->rover->xml === null) + $this->rover->xml = ''; + $this->rover->xml .= $xml; + } + return $this; + } + public function t($text, $append=FALSE) { if(!$append) { $this->rover->text = $text; } else { - if($this->rover->text === null) + if($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; - } + } return $this; } - + public function c($name, $ns=null, $attrs=array(), $text=null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } - + public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } - + public function up() { if($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } - + public function top() { $this->rover = &$this; return $this; } public function exists($name, $ns=null, $attrs=array()) { foreach($this->childrens as $child) { if($ns) { if($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; } else if($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } - + public function update($name, $ns=null, $attrs=array(), $text=null) { foreach($this->childrens as $k=>$child) { if($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } - + public function to_string($parent_ns=null) { $xml = ''; - + $xml .= '<'.$this->name; if($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; foreach($this->attrs as $k=>$v) if(!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; - + foreach($this->childrens as $child) $xml .= $child->to_string($this->ns); - - if($this->text) $xml .= htmlspecialchars($this->text); + + if($this->xml !== null) $xml .= $this->xml; + + if($this->text !== null) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } - + } ?>
jaxl/JAXL
0c53be732064c8d99e80ec7b14828847f44d14ec
Убрал дефолтную установку тайм зон
diff --git a/jaxl.php b/jaxl.php index f529a07..6e99d78 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,644 +1,643 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; - - // setup logger - if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; - //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; - if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; + + // setup logger + if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; + //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; + if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; - + // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { $protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp"); if ($this->cfg['protocol']) $protocol = $this->cfg['protocol']; return $protocol."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods
jaxl/JAXL
21a632e3c0688422b5429ad41b39fc4e3fa85231
Allow log colorization to be disabled
diff --git a/core/jaxl_logger.php b/core/jaxl_logger.php index a0f039c..88843e5 100644 --- a/core/jaxl_logger.php +++ b/core/jaxl_logger.php @@ -1,92 +1,97 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // log level define('JAXL_ERROR', 1); define('JAXL_WARNING', 2); define('JAXL_NOTICE', 3); define('JAXL_INFO', 4); define('JAXL_DEBUG', 5); // generic global logging shortcuts for different level of verbosity function _error($msg) { JAXLLogger::log($msg, JAXL_ERROR); } function _warning($msg) { JAXLLogger::log($msg, JAXL_WARNING); } function _notice($msg) { JAXLLogger::log($msg, JAXL_NOTICE); } function _info($msg) { JAXLLogger::log($msg, JAXL_INFO); } function _debug($msg) { JAXLLogger::log($msg, JAXL_DEBUG); } // generic global terminal output colorize method // finally sends colorized message to terminal using error_log/1 // this method is mainly to escape $msg from file:line and time // prefix done by _debug, _error, ... methods function _colorize($msg, $verbosity) { error_log(JAXLLogger::colorize($msg, $verbosity)); } class JAXLLogger { + public static $colorize = true; public static $level = JAXL_DEBUG; public static $path = null; public static $max_log_size = 1000; protected static $colors = array( 1 => 31, // error: red 2 => 34, // warning: blue 3 => 33, // notice: yellow 4 => 32, // info: green 5 => 37 // debug: white ); public static function log($msg, $verbosity=1) { if($verbosity <= self::$level) { $bt = debug_backtrace(); array_shift($bt); $callee = array_shift($bt); $msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg; $size = strlen($msg); if($size > self::$max_log_size) $msg = substr($msg, 0, self::$max_log_size) . ' ...'; if(isset(self::$path)) error_log($msg . PHP_EOL, 3, self::$path); else error_log(self::colorize($msg, $verbosity)); } } public static function colorize($msg, $verbosity) { + if (self::$colorize) { + return $msg; + } + return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m"; } } ?> diff --git a/jaxl.php b/jaxl.php index f529a07..9a05989 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,644 +1,647 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; + public $log_colorize = true; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; - - // setup logger - if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; - //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; - if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; + + // setup logger + if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; + //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; + if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; - + if(isset($this->cfg['log_colorize'])) JAXLLogger::$colorize = $this->log_colorize = $this->cfg['log_colorize']; + else JAXLLogger::$colorize = $this->log_colorize; + // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { $protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp"); if ($this->cfg['protocol']) $protocol = $this->cfg['protocol']; return $protocol."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods
jaxl/JAXL
42fde6466830544c644e38d07c51156df681638c
Fix some PHP notices
diff --git a/jaxl.php b/jaxl.php index f529a07..9a8367e 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,812 +1,812 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { $protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp"); - if ($this->cfg['protocol']) + if (@$this->cfg['protocol']) $protocol = $this->cfg['protocol']; return $protocol."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { - $stanza = $args[0]; + $stanza = @$args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?>
jaxl/JAXL
61284621eba1d38a5430bfdd7906fd77579c83cf
Change the visibility of `JAXLLoop::select`
diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index a53a14b..1bc45a3 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,159 +1,159 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLLoop { public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; private function __construct() {} private function __clone() {} public static function watch($fd, $opts) { if(isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } if(isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function unwatch($fd, $opts) { if(isset($opts['read'])) { $fdid = (int) $fd; if(isset(self::$read_fds[$fdid])) { unset(self::$read_fds[$fdid]); unset(self::$read_cbs[$fdid]); --self::$active_read_fds; } } if(isset($opts['write'])) { $fdid = (int) $fd; if(isset(self::$write_fds[$fdid])) { unset(self::$write_fds[$fdid]); unset(self::$write_cbs[$fdid]); --self::$active_write_fds; } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function run() { if(!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); while((self::$active_read_fds + self::$active_write_fds) > 0) self::select(); _debug("no more active fd's to select"); self::$is_running = false; } } - private static function select() { + public static function select() { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); if($changed === false) { _error("error in the event loop, shutting down..."); /*foreach(self::$read_fds as $fd) { if(is_resource($fd)) print_r(stream_get_meta_data($fd)); }*/ exit; } else if($changed > 0) { // read callback foreach($read as $r) { $fdid = array_search($r, self::$read_fds); if(isset(self::$read_fds[$fdid])) call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); } // write callback foreach($write as $w) { $fdid = array_search($w, self::$write_fds); if(isset(self::$write_fds[$fdid])) call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); } self::$clock->tick(); } else if($changed === 0) { //_debug("nothing changed while selecting for read"); self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); } } } ?>
jaxl/JAXL
9d97c9036bfdd9a803e0fa92491dca4f4efee425
Change lib name
diff --git a/composer.json b/composer.json index 78c3829..1f2b736 100644 --- a/composer.json +++ b/composer.json @@ -1,24 +1,24 @@ { - "name": "abhinavsingh/jaxl", + "name": "ngsru/jaxl", "type": "library", "description": "Jaxl - Async, Non-Blocking, Event based Networking Library in PHP.", "keywords": ["xmpp", "jabber", "http", "asynchronous", "non blocking", "event loop", "php", "jaxl", "abhinavsingh"], "homepage": "http://jaxl.readthedocs.org/en/latest/index.html", "license": "MIT", "authors": [ { "name": "Abhinavsingh", "homepage": "https://abhinavsingh.com/" } ], "require": { "php": ">=5.2.4" }, "autoload": { "files": ["jaxl.php"] }, "bin": ["jaxlctl"] } \ No newline at end of file
jaxl/JAXL
4dd747df579b990b78b4ac3a9a201e0ea40b9741
Remove error reporting strict lvl
diff --git a/core/jaxl_exception.php b/core/jaxl_exception.php index 200ae46..45dd39f 100644 --- a/core/jaxl_exception.php +++ b/core/jaxl_exception.php @@ -1,94 +1,92 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -error_reporting(E_ALL | E_STRICT); - /** * * @author abhinavsingh */ class JAXLException extends Exception { public function __construct($message = null, $code = null, $file = null, $line = null) { _notice("got jaxl exception construct with $message, $code, $file, $line"); if($code === null) { parent::__construct($message); } else { parent::__construct($message, $code); } if($file !== null) { $this->file = $file; } if($line !== null) { $this->line = $line; } } public static function error_handler($errno, $error, $file, $line, $vars) { _debug("error handler called with $errno, $error, $file, $line"); if($errno === 0 || ($errno & error_reporting()) === 0) { return; } throw new JAXLException($error, $errno, $file, $line); } public static function exception_handler($e) { _debug("exception handler catched ".json_encode($e)); // TODO: Pretty print backtrace //print_r(debug_backtrace()); } public static function shutdown_handler() { try { _debug("got shutdown handler"); if(null !== ($error = error_get_last())) { throw new JAXLException($error['message'], $error['type'], $error['file'], $error['line']); } } catch(Exception $e) { _debug("shutdown handler catched with exception ".json_encode($e)); } } } ?>
jaxl/JAXL
7301a623d989ea2d689cde833d332d4bc555bde7
Working MUC password support.
diff --git a/xep/xep_0045.php b/xep/xep_0045.php index 777c682..7120a46 100644 --- a/xep/xep_0045.php +++ b/xep/xep_0045.php @@ -1,117 +1,117 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_MUC', 'http://jabber.org/protocol/muc'); class XEP_0045 extends XMPPXep { // // abstract method // public function init() { return array(); } public function send_groupchat($room_jid, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'groupchat', 'to'=>(($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid), 'from'=>$this->jaxl->full_jid->to_string() ), $body, $thread, $subject ); $this->jaxl->send($msg); } // // api methods (occupant use case) // // room_full_jid simply means room jid with nick name as resource public function get_join_room_pkt($room_full_jid, $options) { $pkt = $this->jaxl->get_pres_pkt( array( 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid) ) ); $x = $pkt->c('x', NS_MUC); if (isset($options['no_history'])) { - $x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0)); + $x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0))->up(); } if (isset($options['password'])) { - $x->c('password')->t($options['password']); + $x->c('password')->t($options['password'])->up(); } return $x; } public function join_room($room_full_jid, $options = array()) { $pkt = $this->get_join_room_pkt($room_full_jid, $options); $this->jaxl->send($pkt); } public function get_leave_room_pkt($room_full_jid) { return $this->jaxl->get_pres_pkt( array('type'=>'unavailable', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid)) ); } public function leave_room($room_full_jid) { $pkt = $this->get_leave_room_pkt($room_full_jid); $this->jaxl->send($pkt); } // // api methods (moderator use case) // // // event callbacks // } ?>
jaxl/JAXL
d12098991b3bdcbeb5db9a6ece43e063466e1fe3
Adding password support to MUC
diff --git a/xep/xep_0045.php b/xep/xep_0045.php index 90cd013..777c682 100644 --- a/xep/xep_0045.php +++ b/xep/xep_0045.php @@ -1,114 +1,117 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_MUC', 'http://jabber.org/protocol/muc'); class XEP_0045 extends XMPPXep { - + // // abstract method // - + public function init() { return array(); } - + public function send_groupchat($room_jid, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( - 'type'=>'groupchat', - 'to'=>(($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid), + 'type'=>'groupchat', + 'to'=>(($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid), 'from'=>$this->jaxl->full_jid->to_string() ), $body, $thread, $subject ); $this->jaxl->send($msg); } - + // // api methods (occupant use case) // - + // room_full_jid simply means room jid with nick name as resource public function get_join_room_pkt($room_full_jid, $options) { $pkt = $this->jaxl->get_pres_pkt( array( - 'from'=>$this->jaxl->full_jid->to_string(), + 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid) ) ); $x = $pkt->c('x', NS_MUC); if (isset($options['no_history'])) { $x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0)); } + if (isset($options['password'])) { + $x->c('password')->t($options['password']); + } return $x; } - + public function join_room($room_full_jid, $options = array()) { $pkt = $this->get_join_room_pkt($room_full_jid, $options); $this->jaxl->send($pkt); } - + public function get_leave_room_pkt($room_full_jid) { return $this->jaxl->get_pres_pkt( array('type'=>'unavailable', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid)) ); } - + public function leave_room($room_full_jid) { $pkt = $this->get_leave_room_pkt($room_full_jid); $this->jaxl->send($pkt); } - + // // api methods (moderator use case) // - - - + + + // // event callbacks // } ?>
jaxl/JAXL
e06315a61eb126c8688f33d94acb0321bfc0b1b6
Bumped version number to 3.0.1
diff --git a/README.md b/README.md index 5ad0c81..ebe7c28 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,31 @@ -Jaxl v3.x: +Jaxl v3.0.1 ----------- + Jaxl v3.x is a successor of v2.x (and is NOT backward compatible), carrying a lot of code from v2.x while throwing away the ugly parts. A lot of components have been re-written keeping in mind the feedback from the developer community over the last 4 years. Also Jaxl shares a few philosophies from my experience with erlang and python languages. Jaxl is an asynchronous, non-blocking I/O, event based PHP library for writing custom TCP/IP client and server implementations. From it's previous versions, library inherits a full blown stable support -for [XMPP protocol stack](https://github.com/abhinavsingh/JAXL/tree/v3.x/xmpp). -In v3.0, support for [HTTP protocol stack](https://github.com/abhinavsingh/JAXL/tree/v3.x/http) +for [XMPP protocol stack](https://github.com/frost-nzcr4/JAXL/tree/v3.0.1/xmpp). +In v3.0, support for [HTTP protocol stack](https://github.com/frost-nzcr4/JAXL/tree/v3.0.1/http) has also been added. -At the heart of every protocol stack sits the [Core stack](https://github.com/abhinavsingh/JAXL/tree/v3.x/core). +At the heart of every protocol stack sits the [Core stack](https://github.com/frost-nzcr4/JAXL/tree/v3.0.1/core). It contains all the building blocks for everything that we aim to do with Jaxl library. Both XMPP and HTTP protocol stacks are written on top of the Core stack. Infact the source code of protocol implementations knows nothing about the standard (inbuilt) PHP socket and stream methods. -[Examples](https://github.com/abhinavsingh/JAXL/tree/v3.x/examples/) +[Examples](https://github.com/frost-nzcr4/JAXL/tree/v3.0.1/examples/) [Documentation](http://jaxl.readthedocs.org/) [Group and Mailing List](https://groups.google.com/forum/#!forum/jaxl) [Create a bug/issue](https://github.com/abhinavsingh/JAXL/issues/new) [Author](http://abhinavsingh.com/) diff --git a/composer.json b/composer.json index 91dc426..40ade45 100644 --- a/composer.json +++ b/composer.json @@ -1,25 +1,37 @@ { "name": "abhinavsingh/jaxl", "type": "library", "description": "Jaxl - Async, Non-Blocking, Event based Networking Library in PHP.", "keywords": ["xmpp", "jabber", "http", "asynchronous", "non blocking", "event loop", "php", "jaxl", "abhinavsingh"], "homepage": "http://jaxl.readthedocs.org/en/latest/index.html", "license": "MIT", + "support": { + "forum": "https://groups.google.com/forum/#!forum/jaxl", + "issues": "https://github.com/abhinavsingh/JAXL/issues", + "source": "https://github.com/abhinavsingh/JAXL" + }, "authors": [ { - "name": "Abhinavsingh", + "name": "Abhinavsingh", "homepage": "https://abhinavsingh.com/" } ], "require": { - "php": ">=5.2.4" + "php": ">=5.2.4", + "ext-curl": "*", + "ext-hash": "*", + "ext-json": "*", + "ext-libxml": "*", + "ext-openssl": "*", + "ext-pcre": "*", + "ext-sockets": "*" }, "require-dev": { "squizlabs/php_codesniffer": "1.*", "sebastianbergmann/phpunit": "3.6.*" }, "autoload": { "files": ["jaxl.php"] }, "bin": ["jaxlctl"] } \ No newline at end of file
jaxl/JAXL
1ad3a19efa219e8e4494afd3d43ed22a23a96631
Add dev requirements to composer
diff --git a/.gitignore b/.gitignore index 6654fa5..bb19d8d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ -.buildpath -.project -.jaxl -.pydevproject -.settings/ -docs/_build +/.buildpath +/.project +/.jaxl +/.pydevproject +/.settings/ +/docs/_build +/vendor/ \ No newline at end of file diff --git a/composer.json b/composer.json index 3e22d24..91dc426 100644 --- a/composer.json +++ b/composer.json @@ -1,24 +1,25 @@ { "name": "abhinavsingh/jaxl", "type": "library", "description": "Jaxl - Async, Non-Blocking, Event based Networking Library in PHP.", "keywords": ["xmpp", "jabber", "http", "asynchronous", "non blocking", "event loop", "php", "jaxl", "abhinavsingh"], "homepage": "http://jaxl.readthedocs.org/en/latest/index.html", "license": "MIT", - "authors": [ { "name": "Abhinavsingh", "homepage": "https://abhinavsingh.com/" } ], - "require": { "php": ">=5.2.4" }, - + "require-dev": { + "squizlabs/php_codesniffer": "1.*", + "sebastianbergmann/phpunit": "3.6.*" + }, "autoload": { "files": ["jaxl.php"] }, "bin": ["jaxlctl"] } \ No newline at end of file
jaxl/JAXL
935c266f2f6c2c546a0d4964299187e6aebd98ea
Fix tests
diff --git a/tests/test_jaxl_event.php b/tests/test_jaxl_event.php index 9ccca64..708752b 100644 --- a/tests/test_jaxl_event.php +++ b/tests/test_jaxl_event.php @@ -1,73 +1,73 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLEventTest extends PHPUnit_Framework_TestCase { public function test_jaxl_event() { - $ev = new JAXLEvent(); + $ev = new JAXLEvent(array()); $ref1 = $ev->add('on_connect', 'some_func', 0); $ref2 = $ev->add('on_connect', 'some_func1', 0); $ref3 = $ev->add('on_connect', 'some_func2', 1); $ref4 = $ev->add('on_connect', 'some_func3', 4); $ref5 = $ev->add('on_disconnect', 'some_func', 1); $ref6 = $ev->add('on_disconnect', 'some_func1', 1); //$ev->emit('on_connect', null); $ev->del($ref2); $ev->del($ref1); $ev->del($ref6); $ev->del($ref5); $ev->del($ref4); $ev->del($ref3); //print_r($ev->reg); } } diff --git a/tests/test_jaxl_socket_client.php b/tests/test_jaxl_socket_client.php index 986f086..12ebaef 100644 --- a/tests/test_jaxl_socket_client.php +++ b/tests/test_jaxl_socket_client.php @@ -1,61 +1,61 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLSocketClientTest extends PHPUnit_Framework_TestCase { public function test_jaxl_socket_client() { - $sock = new JAXLSocketClient("127.0.0.1", 5222); - $sock->connect(); + $sock = new JAXLSocketClient(); + $sock->connect('tcp://127.0.0.1:5222'); $sock->send("<stream:stream>"); while ($sock->fd) { $sock->recv(); } } } diff --git a/tests/test_xmpp_msg.php b/tests/test_xmpp_msg.php index ae43422..fb8f3fa 100644 --- a/tests/test_xmpp_msg.php +++ b/tests/test_xmpp_msg.php @@ -1,69 +1,89 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPMsgTest extends PHPUnit_Framework_TestCase { - public function test_xmpp_msg() + public function test_xmpp_msg() { $msg = new XMPPMsg(array('to' => '[email protected]', 'from' => '[email protected]/~', 'type' => 'chat'), 'hi', 'thread1'); - echo $msg->to.PHP_EOL; - echo $msg->to_node.PHP_EOL; - echo $msg->from.PHP_EOL; - echo $msg->to_string().PHP_EOL; + $this->assertEquals( + array( + 'from' => '[email protected]/~', + 'to' => '[email protected]', + 'to_node' => '2', + 'to_string' => '<message xmlns="jabber:client" to="[email protected]" from="[email protected]/~" type="chat"><body>hi</body><thread>thread1</thread></message>', + ), + array( + 'from' => $msg->from, + 'to' => $msg->to, + 'to_node' => $msg->to_node, + 'to_string' => $msg->to_string(), + ) + ); $msg->to = '[email protected]/sp'; $msg->body = 'hello world'; $msg->subject = 'some subject'; - echo $msg->to.PHP_EOL; - echo $msg->to_node.PHP_EOL; - echo $msg->from.PHP_EOL; - echo $msg->to_string().PHP_EOL; + $this->assertEquals( + array( + 'from' => '[email protected]/~', + 'to' => '[email protected]/sp', + 'to_node' => '4', + 'to_string' => '<message xmlns="jabber:client" to="[email protected]/sp" from="[email protected]/~" type="chat"><body>hello world</body><thread>thread1</thread><subject>some subject</subject></message>', + ), + array( + 'from' => $msg->from, + 'to' => $msg->to, + 'to_node' => $msg->to_node, + 'to_string' => $msg->to_string(), + ) + ); } }
jaxl/JAXL
990e0caaa2c16219ba166ffdc827de138f5fd7ad
Add phpunit settings to run the whole testsuite
diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..ac6bdf3 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<phpunit + backupGlobals="false" + backupStaticAttributes="false" + colors="true" + convertErrorsToExceptions="true" + convertNoticesToExceptions="true" + convertWarningsToExceptions="true" + processIsolation="false" + stopOnFailure="false" +> + <testsuites> + <testsuite name="JAXL"> + <directory suffix=".php">tests/</directory> + <exclude>tests/test_jaxl_socket_client.php</exclude> + <exclude>tests/test_xmpp_stream.php</exclude> + </testsuite> + </testsuites> +</phpunit>
jaxl/JAXL
0014d1cde7fe224f5357f508c213b8b7255569fc
Fix undefined index notice.
diff --git a/jaxl.php b/jaxl.php index 9d38f7d..c169603 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,876 +1,878 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger if (isset($this->cfg['log_path'])) { JAXLLogger::$path = $this->cfg['log_path']; } //else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; } if (isset($this->cfg['log_level'])) { JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; } else { JAXLLogger::$level = $this->log_level; } // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true; if ($strict) { $this->add_exception_handlers(); } $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if (!is_dir($this->priv_dir)) { mkdir($this->priv_dir); } if (!is_dir($this->tmp_dir)) { mkdir($this->tmp_dir); } if (!is_dir($this->pid_dir)) { mkdir($this->pid_dir); } if (!is_dir($this->log_dir)) { mkdir($this->log_dir); } if (!is_dir($this->sock_dir)) { mkdir($this->sock_dir); } // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if (!is_array($xeps)) { $xeps = array($xeps); } foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri = 1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show = 'chat', $priority = 10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type' => 'chat', 'to' => $to, 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid = null, $cb = null) { $attrs = array( 'type' => 'get', 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) { $this->add_cb('on_stanza_id_'.$pkt->id, $cb); } $this->send($pkt); } public function get_roster($cb = null) { $pkt = $this->get_iq_pkt( array( 'type' => 'get', 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) { $this->add_cb('on_stanza_id_'.$pkt->id, $cb); } $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribed') )); } public function get_socket_path() { - $protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp"); - if ($this->cfg['protocol']) + if (isset($this->cfg['protocol'])) { $protocol = $this->cfg['protocol']; + } else { + $protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp"); + } return $protocol."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts = array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) { $this->add_cb('on_connect', array($this, 'start_stream')); } // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) { $this->enable_debug_shell(); } if (@$opts['--with-unix-sock']) { $this->enable_unix_sock(); } // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } else { // if connection to the destination fails if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if ($mechanisms) { foreach ($mechanisms->childrens as $mechanism) { $mechs[$mechanism->text] = true; } } // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if ($pref_auth_exists) { $mech = $pref_auth; } else { // if pref auth doesn't exists, choose one from available mechanisms foreach ($mechs as $mech => $any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if ($mech == 'X-FACEBOOK-PLATFORM') { if (@$this->cfg['fb_access_token']) { break; } } else { // else try first of the available methods break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if ($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } elseif ($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } elseif ($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if (!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach ($query->childrens as $child) { if ($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach ($child->childrens as $group) { if ($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if (!$emited) { $this->ev->emit('on_roster_update'); } } // if managing roster // catch contact vcard results if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if (@$this->roster[$stanza->from]) { $this->roster[$stanza->from]->vcard = $query; } } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if (!$emited) { $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if ($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if ($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } elseif ($type == 'unavailable') { if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) { unset($this->roster[$jid->bare]->resources[$jid->resource]); } } } // if managing subscription requests // we need to automate stuff here if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if ($this->manage_subscribe == "mutual") { $this->subscribe($stanza->from); } } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if ($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach ($query->childrens as $k => $child) { if ($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } elseif ($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } elseif ($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach ($query->childrens as $k => $child) { if ($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } }
jaxl/JAXL
68ebbae5c69c0df980b3e844556a9b7a46447267
Add check for protocol option. Refs abhinavsingh/JAXL#47
diff --git a/tests/tests.php b/tests/tests.php index 8d467a8..4c33446 100644 --- a/tests/tests.php +++ b/tests/tests.php @@ -1,51 +1,60 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLTest extends PHPUnit_Framework_TestCase { - + public function testProtocolOption() + { + $config = array( + 'host' => 'domain.tld', + 'port' => 5223, + 'protocol' => 'tcp' + ); + $jaxl = new JAXL($config); + $this->assertEquals('tcp://domain.tld:5223', $jaxl->get_socket_path()); + } }
jaxl/JAXL
7a7363663a60197fe04dedc64fa16234b3033b01
Add extra checks for negative node values according to XEP-0029
diff --git a/tests/test_xmpp_jid.php b/tests/test_xmpp_jid.php index 4712dfd..6e5e753 100644 --- a/tests/test_xmpp_jid.php +++ b/tests/test_xmpp_jid.php @@ -1,76 +1,102 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPJidTest extends PHPUnit_Framework_TestCase { /** * @dataProvider jidPositiveProvider */ public function test_xmpp_jid_construct($jidText) { $jid = new XMPPJid($jidText); $this->assertEquals($jidText, $jid->to_string()); } public function jidPositiveProvider() { return array( array('domain'), array('domain.tld'), array('1@domain'), array('[email protected]'), array('domain/res'), array('domain.tld/res'), array('1@domain/res'), array('[email protected]/res'), array('component.domain.tld'), array('[email protected]/res'), array('[email protected]/@res'), array('[email protected]//res') ); } + + /** + * @dataProvider jidNegativeProvider + * @expectedException InvalidArgumentException + */ + public function testJidNegative($jidText) + { + $jid = new XMPPJid($jidText); + } + + public function jidNegativeProvider() + { + return array( + array('"@domain'), + array('&@domain'), + array("'@domain"), + array('/@domain'), + array(':@domain'), + array('<@domain'), + array('>@domain'), + array('@@domain'), + array("\x7F" . '@domain'), + array("\xFF\xFE" . '@domain'), + array("\xFF\xFF" . '@domain') + ); + } }
jaxl/JAXL
25b31b4e996c33909bbee5a06f5cfad49978f87f
Add extra checks. Refs abhinavsingh/JAXL#39
diff --git a/tests/test_xmpp_jid.php b/tests/test_xmpp_jid.php index 8be52f0..4712dfd 100644 --- a/tests/test_xmpp_jid.php +++ b/tests/test_xmpp_jid.php @@ -1,68 +1,76 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPJidTest extends PHPUnit_Framework_TestCase { /** * @dataProvider jidPositiveProvider */ public function test_xmpp_jid_construct($jidText) { $jid = new XMPPJid($jidText); $this->assertEquals($jidText, $jid->to_string()); } public function jidPositiveProvider() { return array( - array('[email protected]/res'), + array('domain'), + array('domain.tld'), + array('1@domain'), + array('[email protected]'), + array('domain/res'), array('domain.tld/res'), + array('1@domain/res'), + array('[email protected]/res'), array('component.domain.tld'), - array('[email protected]') + array('[email protected]/res'), + array('[email protected]/@res'), + array('[email protected]//res') ); } }
jaxl/JAXL
96387731f0f30b0a1e3b6461529b5f866b0d465d
Fix PSR: Expected 1 space after comma in function call
diff --git a/xmpp/xmpp_nss.php b/xmpp/xmpp_nss.php index cbebab2..7a0cad0 100644 --- a/xmpp/xmpp_nss.php +++ b/xmpp/xmpp_nss.php @@ -1,60 +1,60 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // XML -define('NS_XML_pfx', "xml"); -define('NS_XML', 'http://www.w3.org/XML/1998/namespace'); +define('NS_XML_pfx', "xml"); +define('NS_XML', 'http://www.w3.org/XML/1998/namespace'); // XMPP Core (RFC 3920) -define('NS_XMPP_pfx', "stream"); -define('NS_XMPP', 'http://etherx.jabber.org/streams'); -define('NS_STREAM_ERRORS', 'urn:ietf:params:xml:ns:xmpp-streams'); -define('NS_TLS', 'urn:ietf:params:xml:ns:xmpp-tls'); -define('NS_SASL', 'urn:ietf:params:xml:ns:xmpp-sasl'); -define('NS_BIND', 'urn:ietf:params:xml:ns:xmpp-bind'); -define('NS_STANZA_ERRORS', 'urn:ietf:params:xml:ns:xmpp-stanzas'); +define('NS_XMPP_pfx', "stream"); +define('NS_XMPP', 'http://etherx.jabber.org/streams'); +define('NS_STREAM_ERRORS', 'urn:ietf:params:xml:ns:xmpp-streams'); +define('NS_TLS', 'urn:ietf:params:xml:ns:xmpp-tls'); +define('NS_SASL', 'urn:ietf:params:xml:ns:xmpp-sasl'); +define('NS_BIND', 'urn:ietf:params:xml:ns:xmpp-bind'); +define('NS_STANZA_ERRORS', 'urn:ietf:params:xml:ns:xmpp-stanzas'); // XMPP-IM (RFC 3921) -define('NS_JABBER_CLIENT', 'jabber:client'); -define('NS_JABBER_SERVER', 'jabber:server'); -define('NS_SESSION', 'urn:ietf:params:xml:ns:xmpp-session'); -define('NS_ROSTER', 'jabber:iq:roster'); +define('NS_JABBER_CLIENT', 'jabber:client'); +define('NS_JABBER_SERVER', 'jabber:server'); +define('NS_SESSION', 'urn:ietf:params:xml:ns:xmpp-session'); +define('NS_ROSTER', 'jabber:iq:roster'); // Stream Compression (XEP-0138) -define('NS_COMPRESSION_FEATURE', 'http://jabber.org/features/compress'); -define('NS_COMPRESSION_PROTOCOL', 'http://jabber.org/protocol/compress'); +define('NS_COMPRESSION_FEATURE', 'http://jabber.org/features/compress'); +define('NS_COMPRESSION_PROTOCOL', 'http://jabber.org/protocol/compress');
jaxl/JAXL
62c467f5fc77a51f030ed1692f18054991bf5608
Fix PSR: Visibility must be declared on method
diff --git a/tests/test_jaxl_event.php b/tests/test_jaxl_event.php index dd74261..9ccca64 100644 --- a/tests/test_jaxl_event.php +++ b/tests/test_jaxl_event.php @@ -1,73 +1,73 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLEventTest extends PHPUnit_Framework_TestCase { - function test_jaxl_event() + public function test_jaxl_event() { $ev = new JAXLEvent(); $ref1 = $ev->add('on_connect', 'some_func', 0); $ref2 = $ev->add('on_connect', 'some_func1', 0); $ref3 = $ev->add('on_connect', 'some_func2', 1); $ref4 = $ev->add('on_connect', 'some_func3', 4); $ref5 = $ev->add('on_disconnect', 'some_func', 1); $ref6 = $ev->add('on_disconnect', 'some_func1', 1); //$ev->emit('on_connect', null); $ev->del($ref2); $ev->del($ref1); $ev->del($ref6); $ev->del($ref5); $ev->del($ref4); $ev->del($ref3); //print_r($ev->reg); } } diff --git a/tests/test_jaxl_socket_client.php b/tests/test_jaxl_socket_client.php index d58d558..986f086 100644 --- a/tests/test_jaxl_socket_client.php +++ b/tests/test_jaxl_socket_client.php @@ -1,61 +1,61 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLSocketClientTest extends PHPUnit_Framework_TestCase { - function test_jaxl_socket_client() + public function test_jaxl_socket_client() { $sock = new JAXLSocketClient("127.0.0.1", 5222); $sock->connect(); $sock->send("<stream:stream>"); while ($sock->fd) { $sock->recv(); } } } diff --git a/tests/test_jaxl_xml_stream.php b/tests/test_jaxl_xml_stream.php index 0538af6..999c571 100644 --- a/tests/test_jaxl_xml_stream.php +++ b/tests/test_jaxl_xml_stream.php @@ -1,79 +1,79 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLXmlStreamTest extends PHPUnit_Framework_TestCase { - function xml_start_cb($node) + public function xml_start_cb($node) { $this->assertEquals('stream', $node->name); $this->assertEquals(NS_XMPP, $node->ns); } - function xml_end_cb($node) + public function xml_end_cb($node) { $this->assertEquals('stream', $node->name); } - function xml_stanza_cb($node) + public function xml_stanza_cb($node) { $this->assertEquals('features', $node->name); $this->assertEquals(1, sizeof($node->childrens)); } - function test_xml_stream_callbacks() + public function test_xml_stream_callbacks() { $xml = new JAXLXmlStream(); $xml->set_callback(array(&$this, "xml_start_cb"), array(&$this, "xml_end_cb"), array(&$this, "xml_stanza_cb")); $xml->parse('<stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">'); $xml->parse('<features>'); $xml->parse('<mechanisms>'); $xml->parse('</mechanisms>'); $xml->parse('</features>'); $xml->parse('</stream:stream>'); } } diff --git a/tests/test_xmpp_jid.php b/tests/test_xmpp_jid.php index 6d6fd94..01822ea 100644 --- a/tests/test_xmpp_jid.php +++ b/tests/test_xmpp_jid.php @@ -1,65 +1,65 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPJidTest extends PHPUnit_Framework_TestCase { - function test_xmpp_jid_construct() + public function test_xmpp_jid_construct() { $jid = new XMPPJid("[email protected]/res"); $this->assertEquals('[email protected]/res', $jid->to_string()); $jid = new XMPPJid("domain.tld/res"); $this->assertEquals('domain.tld/res', $jid->to_string()); $jid = new XMPPJid("component.domain.tld"); $this->assertEquals('component.domain.tld', $jid->to_string()); $jid = new XMPPJid("[email protected]"); $this->assertEquals('[email protected]', $jid->to_string()); } } diff --git a/tests/test_xmpp_msg.php b/tests/test_xmpp_msg.php index 93702fc..ae43422 100644 --- a/tests/test_xmpp_msg.php +++ b/tests/test_xmpp_msg.php @@ -1,69 +1,69 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPMsgTest extends PHPUnit_Framework_TestCase { - function test_xmpp_msg() + public function test_xmpp_msg() { $msg = new XMPPMsg(array('to' => '[email protected]', 'from' => '[email protected]/~', 'type' => 'chat'), 'hi', 'thread1'); echo $msg->to.PHP_EOL; echo $msg->to_node.PHP_EOL; echo $msg->from.PHP_EOL; echo $msg->to_string().PHP_EOL; $msg->to = '[email protected]/sp'; $msg->body = 'hello world'; $msg->subject = 'some subject'; echo $msg->to.PHP_EOL; echo $msg->to_node.PHP_EOL; echo $msg->from.PHP_EOL; echo $msg->to_string().PHP_EOL; } } diff --git a/tests/test_xmpp_stanza.php b/tests/test_xmpp_stanza.php index 3e0fa33..d349c01 100644 --- a/tests/test_xmpp_stanza.php +++ b/tests/test_xmpp_stanza.php @@ -1,78 +1,78 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPStanzaTest extends PHPUnit_Framework_TestCase { - function test_xmpp_stanza_nested() + public function test_xmpp_stanza_nested() { $stanza = new JAXLXml('message', array('to' => '[email protected]', 'from' => '[email protected]')); $stanza ->c('body')->attrs(array('xml:lang' => 'en'))->t('hello')->up() ->c('thread')->t('1234')->up() ->c('nested') ->c('nest')->t('nest1')->up() ->c('nest')->t('nest2')->up() ->c('nest')->t('nest3')->up()->up() ->c('c')->attrs(array('hash' => '84jsdmnskd')); $this->assertEquals( '<message to="[email protected]" from="[email protected]"><body xml:lang="en">hello</body><thread>1234</thread><nested><nest>nest1</nest><nest>nest2</nest><nest>nest3</nest></nested><c hash="84jsdmnskd"></c></message>', $stanza->to_string() ); } - function test_xmpp_stanza_from_jaxl_xml() + public function test_xmpp_stanza_from_jaxl_xml() { // xml to stanza test $xml = new JAXLXml('message', NS_JABBER_CLIENT, array('to' => '[email protected]', 'from' => '[email protected]/q')); $stanza = new XMPPStanza($xml); $stanza->c('body')->t('hello world'); echo $stanza->to."\n"; echo $stanza->to_string()."\n"; } } diff --git a/tests/test_xmpp_stream.php b/tests/test_xmpp_stream.php index 8e72f4c..17ad353 100644 --- a/tests/test_xmpp_stream.php +++ b/tests/test_xmpp_stream.php @@ -1,61 +1,61 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPStreamTest extends PHPUnit_Framework_TestCase { - function test_xmpp_stream() + public function test_xmpp_stream() { $xmpp = new XMPPStream("test@localhost", "password"); $xmpp->connect(); $xmpp->start_stream(); while ($xmpp->sock->fd) { $xmpp->sock->recv(); } } }
jaxl/JAXL
7c478d7d24d2abdeacb067944624f9ce94058953
Fix PSR: Expected "} catch ("
diff --git a/core/jaxl_exception.php b/core/jaxl_exception.php index bc1b26d..878bb44 100644 --- a/core/jaxl_exception.php +++ b/core/jaxl_exception.php @@ -1,96 +1,95 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ error_reporting(E_ALL | E_STRICT); /** * * @author abhinavsingh */ class JAXLException extends Exception { public function __construct($message = null, $code = null, $file = null, $line = null) { _notice("got jaxl exception construct with $message, $code, $file, $line"); if ($code === null) { parent::__construct($message); } else { parent::__construct($message, $code); } if ($file !== null) { $this->file = $file; } if ($line !== null) { $this->line = $line; } } public static function error_handler($errno, $error, $file, $line, $vars) { _debug("error handler called with $errno, $error, $file, $line"); if ($errno === 0 || ($errno & error_reporting()) === 0) { return; } throw new JAXLException($error, $errno, $file, $line); } public static function exception_handler($e) { _debug("exception handler catched ".json_encode($e)); // TODO: Pretty print backtrace //print_r(debug_backtrace()); } public static function shutdown_handler() { try { _debug("got shutdown handler"); if (null !== ($error = error_get_last())) { throw new JAXLException($error['message'], $error['type'], $error['file'], $error['line']); } - } - catch(Exception $e) { + } catch (Exception $e) { _debug("shutdown handler catched with exception ".json_encode($e)); } } } diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index e06e23f..03e64dd 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,268 +1,267 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLSocketServer { public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; public function __construct($path, $accept_cb, $request_cb) { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; $ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog))); if (($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { if (@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); } else { _error("unable to set non block flag"); } } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } public function __destruct() { _info("shutting down socket server"); } public function read($client_id) { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } public function send($client_id, $data) { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } public function close($client_id) { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } public function on_server_accept_ready($server) { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); if (!$client) { _error("unable to accept new client conn"); return; } if (@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do if ($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); } else { // if no accept callback is registered // close the accepted connection @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } } else { _error("unable to set non block flag"); } } public function on_client_read_ready($client) { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); if ($bytes === 0) { $meta = stream_get_meta_data($client); if ($meta['eof'] === true) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); @fclose($client); unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; if ($this->request_cb) { call_user_func($this->request_cb, $client_id, $total); } $this->clients[$client_id]['ibuffer'] = ''; } public function on_client_write_ready($client) { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); if ($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; } elseif ($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler if (strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } - } - catch(JAXLException $e) { + } catch (JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // protected function add_read_cb($client_id) { if ($this->clients[$client_id]['reading']) { return; } JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } protected function add_write_cb($client_id) { if ($this->clients[$client_id]['writing']) { return; } JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } protected function del_read_cb($client_id) { if (!$this->clients[$client_id]['reading']) { return; } JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } protected function del_write_cb($client_id) { if (!$this->clients[$client_id]['writing']) { return; } JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } }
jaxl/JAXL
a033dde98f0a539e4c8b97298f8bcc3a82e34980
Fix PSR: move comments into "else" block
diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index 36d1590..e06e23f 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,268 +1,268 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLSocketServer { public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; public function __construct($path, $accept_cb, $request_cb) { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; $ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog))); if (($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { if (@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); } else { _error("unable to set non block flag"); } } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } public function __destruct() { _info("shutting down socket server"); } public function read($client_id) { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } public function send($client_id, $data) { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } public function close($client_id) { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } public function on_server_accept_ready($server) { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); if (!$client) { _error("unable to accept new client conn"); return; } if (@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do if ($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); - } - // if no accept callback is registered - // close the accepted connection - else { + } else { + // if no accept callback is registered + // close the accepted connection + @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } } else { _error("unable to set non block flag"); } } public function on_client_read_ready($client) { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); if ($bytes === 0) { $meta = stream_get_meta_data($client); if ($meta['eof'] === true) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); @fclose($client); unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; if ($this->request_cb) { call_user_func($this->request_cb, $client_id, $total); } $this->clients[$client_id]['ibuffer'] = ''; } public function on_client_write_ready($client) { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); if ($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; } elseif ($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler if (strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } } catch(JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // protected function add_read_cb($client_id) { if ($this->clients[$client_id]['reading']) { return; } JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } protected function add_write_cb($client_id) { if ($this->clients[$client_id]['writing']) { return; } JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } protected function del_read_cb($client_id) { if (!$this->clients[$client_id]['reading']) { return; } JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } protected function del_write_cb($client_id) { if (!$this->clients[$client_id]['writing']) { return; } JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } } diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php index 8f541d2..8305651 100644 --- a/core/jaxl_xml_stream.php +++ b/core/jaxl_xml_stream.php @@ -1,199 +1,199 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Enter description here ... * @author abhinavsingh * */ class JAXLXmlStream { private $delimiter = '\\'; private $ns; private $parser; private $stanza; private $depth = -1; private $start_cb; private $stanza_cb; private $end_cb; public function __construct() { $this->init_parser(); } private function init_parser() { $this->depth = -1; $this->parser = xml_parser_create_ns("UTF-8", $this->delimiter); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); xml_set_character_data_handler($this->parser, array(&$this, "handle_character")); xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag")); } public function __destruct() { //_debug("cleaning up xml parser..."); @xml_parser_free($this->parser); } public function reset_parser() { $this->parse_final(null); @xml_parser_free($this->parser); $this->parser = null; $this->init_parser(); } public function set_callback($start_cb, $end_cb, $stanza_cb) { $this->start_cb = $start_cb; $this->end_cb = $end_cb; $this->stanza_cb = $stanza_cb; } public function parse($str) { xml_parse($this->parser, $str, false); } public function parse_final($str) { xml_parse($this->parser, $str, true); } protected function handle_start_tag($parser, $name, $attrs) { $name = $this->explode($name); //echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL; // replace ns with prefix foreach ($attrs as $key => $v) { $k = $this->explode($key); // no ns specified if ($k[0] == null) { $attrs[$k[1]] = $v; - } - // xml ns - elseif ($k[0] == NS_XML) { + } elseif ($k[0] == NS_XML) { + // xml ns + unset($attrs[$key]); $attrs['xml:'.$k[1]] = $v; } else { _error("==================> unhandled ns prefix on attribute"); // remove attribute else will cause error with bad stanza format // report to developer if above error message is ever encountered unset($attrs[$key]); } } if ($this->depth <= 0) { $this->depth = 0; $this->ns = $name[1]; if ($this->start_cb) { $stanza = new JAXLXml($name[1], $name[0], $attrs); call_user_func($this->start_cb, $stanza); } } else { if (!$this->stanza) { $stanza = new JAXLXml($name[1], $name[0], $attrs); $this->stanza = &$stanza; } else { $this->stanza->c($name[1], $name[0], $attrs); } } ++$this->depth; } protected function handle_end_tag($parser, $name) { $name = explode($this->delimiter, $name); $name = sizeof($name) == 1 ? array('', $name[0]) : $name; //echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL; if ($this->depth == 1) { if ($this->end_cb) { $stanza = new JAXLXml($name[1], $this->ns); call_user_func($this->end_cb, $stanza); } } elseif ($this->depth > 1) { if ($this->stanza) { $this->stanza->up(); } if ($this->depth == 2) { if ($this->stanza_cb) { call_user_func($this->stanza_cb, $this->stanza); $this->stanza = null; } } } --$this->depth; } protected function handle_character($parser, $data) { //echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL; if ($this->stanza) { $this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), true); } } private function implode($data) { return implode($this->delimiter, $data); } private function explode($data) { $data = explode($this->delimiter, $data); $data = sizeof($data) == 1 ? array(null, $data[0]) : $data; return $data; } } diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index cb93258..b749d7c 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,139 +1,139 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 5) { echo "Usage: $argv[0] host jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[2], 'pass' => $argv[3], 'host' => $argv[1], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC '0203', // Delayed Delivery '0199' // XMPP Ping )); // // add necessary event callbacks here // $_room_full_jid = $argv[4]."/".$argv[5]; $room_full_jid = new XMPPJid($_room_full_jid); $client->add_cb('on_auth_success', function () { global $client, $room_full_jid; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // join muc room $client->xeps['0045']->join_room($room_full_jid); }); $client->add_cb('on_auth_failure', function ($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_groupchat_message', function ($stanza) { global $client; $from = new XMPPJid($stanza->from); $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); if ($from->resource) { echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } else { $subject = $stanza->exists('subject'); if ($subject) { echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } } }); $client->add_cb('on_presence_stanza', function ($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { if (($status = $x->exists('status', null, array('code' => '110'))) !== false) { $item = $x->exists('item'); _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); } else { _info("xmlns #user have no x child element"); } } else { _warning("=======> odd case 1"); } - } - // stanza from other users received - elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) { + } elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) { + // stanza from other users received + if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; } else { _warning("=======> odd case 2"); } } else { _warning("=======> odd case 3"); } }); $client->add_cb('on_disconnect', function () { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/http/http_server.php b/http/http_server.php index f74b574..f694333 100644 --- a/http/http_server.php +++ b/http/http_server.php @@ -1,199 +1,199 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/http/http_dispatcher.php'; require_once JAXL_CWD.'/http/http_request.php'; // carriage return and line feed define('HTTP_CRLF', "\r\n"); // 1xx informational define('HTTP_100', "Continue"); define('HTTP_101', "Switching Protocols"); // 2xx success define('HTTP_200', "OK"); // 3xx redirection define('HTTP_301', 'Moved Permanently'); define('HTTP_304', 'Not Modified'); // 4xx client error define('HTTP_400', 'Bad Request'); define('HTTP_403', 'Forbidden'); define('HTTP_404', 'Not Found'); define('HTTP_405', 'Method Not Allowed'); define('HTTP_499', 'Client Closed Request'); // Nginx // 5xx server error define('HTTP_500', 'Internal Server Error'); define('HTTP_503', 'Service Unavailable'); class HTTPServer { private $server = null; public $cb = null; private $dispatcher = null; private $requests = array(); public function __construct($port = 9699, $address = "127.0.0.1") { $path = 'tcp://'.$address.':'.$port; $this->server = new JAXLSocketServer( $path, array(&$this, 'on_accept'), array(&$this, 'on_request') ); $this->dispatcher = new HTTPDispatcher(); } public function __destruct() { $this->server = null; } public function dispatch($rules) { foreach ($rules as $rule) { $this->dispatcher->add_rule($rule); } } public function start($cb = null) { $this->cb = $cb; JAXLLoop::run(); } public function on_accept($sock, $addr) { _debug("on_accept for client#$sock, addr:$addr"); // initialize new request obj $request = new HTTPRequest($sock, $addr); // setup sock cb $request->set_sock_cb( array(&$this->server, 'send'), array(&$this->server, 'read'), array(&$this->server, 'close') ); // cache request object $this->requests[$sock] = &$request; // reactive client for further read $this->server->read($sock); } public function on_request($sock, $raw) { _debug("on_request for client#$sock"); $request = $this->requests[$sock]; // 'wait_for_body' state is reached when ever // application calls recv_body() method // on received $request object if ($request->state() == 'wait_for_body') { $request->body($raw); } else { // break on crlf $lines = explode(HTTP_CRLF, $raw); // parse request line if ($request->state() == 'wait_for_request_line') { list($method, $resource, $version) = explode(" ", $lines[0]); $request->line($method, $resource, $version); unset($lines[0]); _info($request->ip." ".$request->method." ".$request->resource." ".$request->version); } // parse headers foreach ($lines as $line) { $line_parts = explode(":", $line); if (sizeof($line_parts) > 1) { if (strlen($line_parts[0]) > 0) { $k = $line_parts[0]; unset($line_parts[0]); $v = implode(":", $line_parts); $request->set_header($k, $v); } } elseif (strlen(trim($line_parts[0])) == 0) { $request->empty_line(); - } - // if exploded line array size is 1 - // and thr is something in $line_parts[0] - // must be request body - else { + } else { + // if exploded line array size is 1 + // and there is something in $line_parts[0] + // must be request body + $request->body($line); } } } // if request has reached 'headers_received' state? if ($request->state() == 'headers_received') { // dispatch to any matching rule found _debug("delegating to dispatcher for further routing"); $dispatched = $this->dispatcher->dispatch($request); // if no dispatch rule matched call generic callback if (!$dispatched && $this->cb) { _debug("no dispatch rule matched, sending to generic callback"); call_user_func($this->cb, $request); - } - // elseif not dispatched and not generic callbacked - // send 404 not_found - elseif (!$dispatched) { + } elseif (!$dispatched) { + // elseif not dispatched and not generic callbacked + // send 404 not_found + // TODO: send 404 if no callback is registered for this request _debug("dropping request since no matching dispatch rule or generic callback was specified"); $request->not_found('404 Not Found'); } - } - // if state is not 'headers_received' - // reactivate client socket for read event - else { + } else { + // if state is not 'headers_received' + // reactivate client socket for read event + $this->server->read($sock); } } } diff --git a/jaxl.php b/jaxl.php index 243111a..6ccabb0 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,873 +1,873 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger if (isset($this->cfg['log_path'])) { JAXLLogger::$path = $this->cfg['log_path']; } //else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; } if (isset($this->cfg['log_level'])) { JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; } else { JAXLLogger::$level = $this->log_level; } // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true; if ($strict) { $this->add_exception_handlers(); } $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if (!is_dir($this->priv_dir)) { mkdir($this->priv_dir); } if (!is_dir($this->tmp_dir)) { mkdir($this->tmp_dir); } if (!is_dir($this->pid_dir)) { mkdir($this->pid_dir); } if (!is_dir($this->log_dir)) { mkdir($this->log_dir); } if (!is_dir($this->sock_dir)) { mkdir($this->sock_dir); } // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if (!is_array($xeps)) { $xeps = array($xeps); } foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri = 1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show = 'chat', $priority = 10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type' => 'chat', 'to' => $to, 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid = null, $cb = null) { $attrs = array( 'type' => 'get', 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) { $this->add_cb('on_stanza_id_'.$pkt->id, $cb); } $this->send($pkt); } public function get_roster($cb = null) { $pkt = $this->get_iq_pkt( array( 'type' => 'get', 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) { $this->add_cb('on_stanza_id_'.$pkt->id, $cb); } $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts = array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) { $this->add_cb('on_connect', array($this, 'start_stream')); } // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) { $this->enable_debug_shell(); } if (@$opts['--with-unix-sock']) { $this->enable_unix_sock(); } // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); - } - // if connection to the destination fails - else { + } else { + // if connection to the destination fails + if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if ($mechanisms) { foreach ($mechanisms->childrens as $mechanism) { $mechs[$mechanism->text] = true; } } // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if ($pref_auth_exists) { $mech = $pref_auth; - } - // if pref auth doesn't exists, choose one from available mechanisms - else { + } else { + // if pref auth doesn't exists, choose one from available mechanisms + foreach ($mechs as $mech => $any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if ($mech == 'X-FACEBOOK-PLATFORM') { if (@$this->cfg['fb_access_token']) { break; } - } - // else try first of the available methods - else { + } else { + // else try first of the available methods + break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if ($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } elseif ($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } elseif ($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if (!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach ($query->childrens as $child) { if ($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach ($child->childrens as $group) { if ($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if (!$emited) { $this->ev->emit('on_roster_update'); } } // if managing roster // catch contact vcard results if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if (@$this->roster[$stanza->from]) { $this->roster[$stanza->from]->vcard = $query; } } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if (!$emited) { $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if ($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if ($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } elseif ($type == 'unavailable') { if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) { unset($this->roster[$jid->bare]->resources[$jid->resource]); } } } // if managing subscription requests // we need to automate stuff here if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if ($this->manage_subscribe == "mutual") { $this->subscribe($stanza->from); } } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if ($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach ($query->childrens as $k => $child) { if ($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } elseif ($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } elseif ($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach ($query->childrens as $k => $child) { if ($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index baeb5b0..346af45 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -7,718 +7,718 @@ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass = null, $resource = null, $force_tls = false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; } if (isset($jid->domain)) { $xml .= 'to="'.$jid->domain.'" '; } $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if (strlen($pass) == 0) { $stanza->t('='); } break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if (!isset($decoded['digest-uri'])) { $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; } $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) { $decoded['qop'] = 'auth'; } $data = array_merge($decoded, array('nc' => $nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) { if (isset($decoded[$key])) { $response[$key] = $decoded[$key]; } } return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if (!$msg->id) { $msg->id = $this->get_id(); } if ($payload) { $msg->cnode($payload); } return $msg; } public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if (!$pres->id) { $pres->id = $this->get_id(); } if ($payload) { $pres->cnode($payload); } return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if (!$iq->id) { $iq->id = $this->get_id(); } if ($payload) { $iq->cnode($payload); } return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach ($data as $key => $value) { $return[] = $key . '="' . $value . '"'; } return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach (array('realm', 'cnonce', 'digest-uri') as $key) { if (!isset($data[$key])) { $data[$key] = ''; } } $pack = md5($user.':'.$data['realm'].':'.$pass); if (isset($data['authzid'])) { $a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']); } else { $a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']); } $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; - } - /*// compression not supported due to bug in php stream filters - elseif ($comp) { + /*} elseif ($comp) { + // compression not supported due to bug in php stream filters + $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; - }*/ - else { + */ + } else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } elseif ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } elseif ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if ($stanza->name == 'message') { $this->handle_message($stanza); } elseif ($stanza->name == 'presence') { $this->handle_presence($stanza); } elseif ($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } }
jaxl/JAXL
4941ff946cdf186edc92c7dc540477b758ce2a59
Fix PSR: Multi-line functions and arguments
diff --git a/examples/http_rest_server.php b/examples/http_rest_server.php index caa5296..a48e947 100644 --- a/examples/http_rest_server.php +++ b/examples/http_rest_server.php @@ -1,121 +1,122 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // print usage notice and parse addr/port parameters if passed _colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE); $port = ($argc == 2 ? $argv[1] : 9699); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer($port); // callback method for dispatch rule (see below) function index($request) { $request->send_response( - 200, array('Content-Type' => 'text/html'), + 200, + array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } // callback method for dispatch rule (see below) function upload($request) { if ($request->method == 'GET') { - $request->ok(array( - 'Content-Type' => 'text/html'), + $request->ok( + array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' ); } elseif ($request->method == 'POST') { if ($request->body === null && $request->expect) { $request->recv_body(); } else { // got upload body, save it _info("file upload complete, got ".strlen($request->body)." bytes of data"); $upload_data = $request->multipart->form_data[0]['body']; $request->ok($upload_data, array('Content-Type' => $request->multipart->form_data[0]['headers']['Content-Type'])); } } } // add dispatch rules with callback method as first argument $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); // some REST CRUD style callback methods // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules function create_event($request) { _info("got event create request"); $request->close(); } function read_event($request, $pk) { _info("got event read request for $pk"); $request->close(); } function update_event($request, $pk) { _info("got event update request for $pk"); $request->close(); } function delete_event($request, $pk) { _info("got event delete request for $pk"); $request->close(); } $event_create = array('create_event', '^/event/create/$', array('PUT')); $event_read = array('read_event', '^/event/(?P<pk>\d+)/$', array('GET', 'HEAD')); $event_update = array('update_event', '^/event/(?P<pk>\d+)/$', array('POST')); $event_delete = array('delete_event', '^/event/(?P<pk>\d+)/$', array('DELETE')); // prepare rule set $rules = array($index, $upload, $event_create, $event_read, $event_update, $event_delete); $http->dispatch($rules); // start http server $http->start(); diff --git a/xep/xep_0249.php b/xep/xep_0249.php index 8eda5a3..9789d9c 100644 --- a/xep/xep_0249.php +++ b/xep/xep_0249.php @@ -1,90 +1,92 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DIRECT_MUC_INVITATION', 'jabber:x:conference'); class XEP_0249 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods // public function get_invite_pkt($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) { $xattrs = array('jid' => $room_jid); if ($password) { $xattrs['password'] = $password; } if ($reason) { $xattrs['reason'] = $reason; } if ($thread) { $xattrs['thread'] = $thread; } if ($continue) { $xattrs['continue'] = $continue; } return $this->jaxl->get_msg_pkt( array('from' => $this->jaxl->full_jid->to_string(), 'to' => $to_bare_jid), - null, null, null, + null, + null, + null, new JAXLXml('x', NS_DIRECT_MUC_INVITATION, $xattrs) ); } public function invite($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) { $this->jaxl->send($this->get_invite_pkt($to_bare_jid, $room_jid, $password, $reason, $thread, $continue)); } // // event callbacks // }
jaxl/JAXL
75c6874fe630b32bbf3645c20a8f8e7d15a6dc6b
Fix PSR: Line indented incorrectly
diff --git a/examples/register_user.php b/examples/register_user.php index 604bc49..179de31 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,166 +1,164 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // $form = array(); function wait_for_register_response($event, $args) { global $client, $form; if ($event == 'stanza_cb') { $stanza = $args[0]; if ($stanza->name == 'iq') { $form['type'] = $stanza->attrs['type']; if ($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } elseif ($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } } } else { _notice("unhandled event $event rcvd"); } } function wait_for_register_form($event, $args) { global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if ($query) { $instructions = $query->exists('instructions'); if ($instructions) { echo $instructions->text.PHP_EOL; } foreach ($query->childrens as $k => $child) { if ($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // $client->add_cb('on_stream_features', function ($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; }); $client->add_cb('on_disconnect', function () { global $form; _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); }); // // finally start configured xmpp stream // $client->start(); // // if registration was successful // try to connect with newly registered account // if ($form['type'] == 'result') { - -_info("connecting newly registered user account"); -$client = new JAXL(array( - 'jid' => $form['username'].'@'.$argv[1], - 'pass' => $form['password'], - 'log_level' => JAXL_DEBUG -)); - -$client->add_cb('on_auth_success', function () { - global $client; - $client->set_status('Available'); -}); - -$client->start(); - + _info("connecting newly registered user account"); + $client = new JAXL(array( + 'jid' => $form['username'].'@'.$argv[1], + 'pass' => $form['password'], + 'log_level' => JAXL_DEBUG + )); + + $client->add_cb('on_auth_success', function () { + global $client; + $client->set_status('Available'); + }); + + $client->start(); } echo "done\n";
jaxl/JAXL
4e7b8735a5c1d48a9665557696c53c8d94a900f7
Fix PSR: Expected 1 space after FUNCTION keyword
diff --git a/docs/users/xmpp_examples.rst b/docs/users/xmpp_examples.rst index bb2e78e..5ca0598 100644 --- a/docs/users/xmpp_examples.rst +++ b/docs/users/xmpp_examples.rst @@ -1,120 +1,120 @@ XMPP Examples ============= Echo Bot Client --------------- include ``jaxl.php`` and initialize a new ``JAXL`` instance: .. code-block:: ruby require 'jaxl.php'; $client = new JAXL(array( 'jid' => '[email protected]', 'pass' => 'password' )); We just initialized a new ``JAXL`` instance by passing our jabber client ``jid`` and ``pass``. View list of :ref:`available options <jaxl-instance>` that can be passed to ``JAXL`` constructor. Next we need to register callbacks on events of interest using ``JAXL::add_cb/2`` method as shown below: .. code-block:: ruby - $client->add_cb('on_auth_success', function() { + $client->add_cb('on_auth_success', function () { global $client; $client->set_status("available!"); // set your status $client->get_vcard(); // fetch your vcard $client->get_roster(); // fetch your roster list }); - $client->add_cb('on_chat_message', function($msg) { + $client->add_cb('on_chat_message', function ($msg) { global $client; // echo back $msg->to = $msg->from; $msg->from = $client->full_jid->to_string(); $client->send($msg); }); - $client->add_cb('on_disconnect', function() { + $client->add_cb('on_disconnect', function () { _debug("got on_disconnect cb"); }); We just registered callbacks on ``on_auth_success``, ``on_chat_message`` and ``on_disconnect`` events that will occur inside our configured ``JAXL`` instance lifecycle. We also passed a method that will be called (with parameters if any) when the event has been detected. See list of :ref:`available event callbacks <jaxl-instance>` that we can hook to inside ``JAXL`` instance lifecycle. Received ``$msg`` parameter with ``on_chat_message`` event callback above, will be an instance of ``XMPPMsg`` which extends ``XMPPStanza`` class, that allows us easy to use access patterns to common XMPP stanza attributes like ``to``, ``from``, ``type``, ``id`` to name a few. We were also able to access our xmpp client full jabber id by calling ``$client->full_jid``. This attribute of ``JAXL`` instance is available from ``on_auth_success`` event. ``full_jid`` attribute is an instance of ``XMPPJid``. To send our echo back ``$msg`` packet we called ``JAXL::send/1`` which accepts a single parameter which MUST be an instance of ``JAXLXml``. Since ``XMPPStanza`` is a wrapper upon ``JAXLXml`` we can very well pass our modified ``$msg`` object to the send method. Read more about various :ref:`XML Objects <xml-objects>` and how they make writing XMPP applications fun and easy. You can also :ref:`add custom access patterns <xml-objects>` upon received ``XMPPStanza`` objects. Since all access patterns are evaluated upon first access and cached for later usage, adding hundreds of custom access patterns that retrieves information from 100th child of received XML packet will not be an issue. We will finally start our xmpp client by calling: .. code-block:: ruby $client->start(); See list of :ref:`available options <jaxl-instance>` that can be passed to the ``JAXL::start/2`` method. These options are particularly useful for debugging and monitoring. Echo Bot BOSH Client -------------------- Everything goes same for a cli BOSH client. To run above echo bot client example as a bosh client simply pass additional parameters to ``JAXL`` constructor: .. code-block:: ruby require 'jaxl.php'; $client = new JAXL(array( 'jid' => '[email protected]', 'pass' => 'password', 'bosh_url' => 'http://localhost:5280/http-bind' )); You can even pass custom values for ``hold``, ``wait`` and other attributes. View list of :ref:`available options <jaxl-instance>` that can be passed to ``JAXL`` constructor. Echo Bot External Component --------------------------- Again almost everything goes same for an external component except a few custom ``JAXL`` constructor parameter as shown below: .. code-block:: ruby require_once 'jaxl.php'; $comp = new JAXL(array( // (required) component host and secret 'jid' => $argv[1], 'pass' => $argv[2], // (required) destination socket 'host' => $argv[3], 'port' => $argv[4] )); We will also need to include ``XEP0114`` which implements Jabber Component XMPP Extension. .. code-block:: ruby // (required) $comp->require_xep(array( '0114' // jabber component protocol )); ``JAXL::require_xep/1`` accepts an array of XEP numbers passed as strings. diff --git a/examples/echo_bosh_bot.php b/examples/echo_bosh_bot.php index cf0b58d..2eea065 100644 --- a/examples/echo_bosh_bot.php +++ b/examples/echo_bosh_bot.php @@ -1,106 +1,106 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // (required) 'bosh_url' => 'http://localhost:5280/http-bind', // (optional) srv lookup is done if not provided // for bosh client 'host' value is used for 'route' attribute //'host' => 'xmpp.domain.tld', // (optional) result from srv lookup used by default // for bosh client 'port' value is used for 'route' attribute //'port' => 5222, // (optional) //'resource' => 'resource', // (optional) defaults to PLAIN if supported, else other methods will be automatically tried 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN', 'log_level' => JAXL_INFO )); // // add necessary event callbacks here // -$client->add_cb('on_auth_success', function() { +$client->add_cb('on_auth_success', function () { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); $client->set_status("available!", "dnd", 10); }); -$client->add_cb('on_auth_failure', function($reason) { +$client->add_cb('on_auth_failure', function ($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); -$client->add_cb('on_chat_message', function($stanza) { +$client->add_cb('on_chat_message', function ($stanza) { global $client; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); -$client->add_cb('on_disconnect', function() { +$client->add_cb('on_disconnect', function () { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/echo_bot.php b/examples/echo_bot.php index 39ed641..65edcb9 100644 --- a/examples/echo_bot.php +++ b/examples/echo_bot.php @@ -1,147 +1,147 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // Run as: // php examples/echo_bot.php root@localhost password // php examples/echo_bot.php root@localhost password DIGEST-MD5 // php examples/echo_bot.php localhost "" ANONYMOUS if ($argc < 3) { echo "Usage: $argv[0] jid pass auth_type\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // (optional) srv lookup is done if not provided //'host' => 'xmpp.domain.tld', // (optional) result from srv lookup used by default //'port' => 5222, // (optional) defaults to false //'force_tls' => true, // (optional) //'resource' => 'resource', // (optional) defaults to PLAIN if supported, else other methods will be automatically tried 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN', 'log_level' => JAXL_INFO )); // // required XEP's // $client->require_xep(array( '0199' // XMPP Ping )); // // add necessary event callbacks here // -$client->add_cb('on_auth_success', function() { +$client->add_cb('on_auth_success', function () { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // fetch roster list $client->get_roster(); // fetch vcard $client->get_vcard(); // set status $client->set_status("available!", "dnd", 10); }); // by default JAXL instance catches incoming roster list results and updates // roster list is parsed/cached and an event 'on_roster_update' is emitted -$client->add_cb('on_roster_update', function() { +$client->add_cb('on_roster_update', function () { //global $client; //print_r($client->roster); }); -$client->add_cb('on_auth_failure', function($reason) { +$client->add_cb('on_auth_failure', function ($reason) { global $client; _info("got on_auth_failure cb with reason $reason"); $client->send_end_stream(); }); -$client->add_cb('on_chat_message', function($stanza) { +$client->add_cb('on_chat_message', function ($stanza) { global $client; // echo back incoming chat message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); -$client->add_cb('on_presence_stanza', function($stanza) { +$client->add_cb('on_presence_stanza', function ($stanza) { global $client; $type = ($stanza->type ? $stanza->type : "available"); $show = ($stanza->show ? $stanza->show : "???"); _info($stanza->from." is now ".$type." ($show)"); if ($type == "available") { // fetch vcard $client->get_vcard($stanza->from); } }); -$client->add_cb('on_disconnect', function() { +$client->add_cb('on_disconnect', function () { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(array( '--with-debug-shell' => true, '--with-unix-sock' => true )); echo "done\n"; diff --git a/examples/echo_component_bot.php b/examples/echo_component_bot.php index b7bf013..1d6bd21 100644 --- a/examples/echo_component_bot.php +++ b/examples/echo_component_bot.php @@ -1,98 +1,98 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc != 5) { echo "Usage: $argv[0] jid pass host port\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $comp = new JAXL(array( // (required) component host and secret 'jid' => $argv[1], 'pass' => $argv[2], // (required) 'host' => @$argv[3], 'port' => $argv[4], 'log_level' => JAXL_INFO )); // // XEP's required (required) // $comp->require_xep(array( '0114' // jabber component protocol )); // // add necessary event callbacks here // -$comp->add_cb('on_auth_success', function() { +$comp->add_cb('on_auth_success', function () { _info("got on_auth_success cb"); }); -$comp->add_cb('on_auth_failure', function($reason) { +$comp->add_cb('on_auth_failure', function ($reason) { global $comp; $comp->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); -$comp->add_cb('on_chat_message', function($stanza) { +$comp->add_cb('on_chat_message', function ($stanza) { global $comp; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $comp->jid->to_string(); $comp->send($stanza); }); -$comp->add_cb('on_disconnect', function() { +$comp->add_cb('on_disconnect', function () { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $comp->start(); echo "done\n"; diff --git a/examples/http_bind.php b/examples/http_bind.php index d75ade8..cd2a047 100644 --- a/examples/http_bind.php +++ b/examples/http_bind.php @@ -1,64 +1,64 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if (!isset($_GET['jid']) || !isset($_GET['pass'])) { echo "invalid input"; exit; } // // initialize JAXL object with initial config // require_once '../jaxl.php'; $client = new JAXL(array( 'jid' => $_GET['jid'], 'pass' => $_GET['pass'], 'bosh_url' => 'http://localhost:5280/http-bind', 'log_level' => JAXL_DEBUG )); -$client->add_cb('on_auth_success', function() { +$client->add_cb('on_auth_success', function () { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php index acaea62..e37ba6d 100644 --- a/examples/http_pre_bind.php +++ b/examples/http_pre_bind.php @@ -1,89 +1,89 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // http pre bind php script $body = file_get_contents("php://input"); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if (!@$attrs['to'] && !@$attrs['rid'] && !@$attrs['wait'] && !@$attrs['hold']) { echo "invalid input"; exit; } // // initialize JAXL object with initial config // require_once '../jaxl.php'; $to = (string)$attrs['to']; $rid = (int)$attrs['rid']; $wait = (int)$attrs['wait']; $hold = (int)$attrs['hold']; list($host, $port) = JAXLUtil::get_dns_srv($to); $client = new JAXL(array( 'domain' => $to, 'host' => $host, 'port' => $port, 'bosh_url' => 'http://localhost:5280/http-bind', 'bosh_rid' => $rid, 'bosh_wait' => $wait, 'bosh_hold' => $hold, 'auth_type' => 'ANONYMOUS', 'log_level' => JAXL_INFO )); -$client->add_cb('on_auth_success', function() { +$client->add_cb('on_auth_success', function () { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); echo '<body xmlns="'.NS_HTTP_BIND.'" sid="'.$client->xeps['0206']->sid.'" rid="'.$client->xeps['0206']->rid.'" jid="'.$client->full_jid->to_string().'"/>'; exit; }); -$client->add_cb('on_auth_failure', function($reason) { +$client->add_cb('on_auth_failure', function ($reason) { global $client; _info("got on_auth_failure cb with reason $reason"); $client->send_end_stream(); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index eda4d2d..cb93258 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,139 +1,139 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 5) { echo "Usage: $argv[0] host jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[2], 'pass' => $argv[3], 'host' => $argv[1], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC '0203', // Delayed Delivery '0199' // XMPP Ping )); // // add necessary event callbacks here // $_room_full_jid = $argv[4]."/".$argv[5]; $room_full_jid = new XMPPJid($_room_full_jid); -$client->add_cb('on_auth_success', function() { +$client->add_cb('on_auth_success', function () { global $client, $room_full_jid; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // join muc room $client->xeps['0045']->join_room($room_full_jid); }); -$client->add_cb('on_auth_failure', function($reason) { +$client->add_cb('on_auth_failure', function ($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); -$client->add_cb('on_groupchat_message', function($stanza) { +$client->add_cb('on_groupchat_message', function ($stanza) { global $client; $from = new XMPPJid($stanza->from); $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); if ($from->resource) { echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } else { $subject = $stanza->exists('subject'); if ($subject) { echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } } }); -$client->add_cb('on_presence_stanza', function($stanza) { +$client->add_cb('on_presence_stanza', function ($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { if (($status = $x->exists('status', null, array('code' => '110'))) !== false) { $item = $x->exists('item'); _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); } else { _info("xmlns #user have no x child element"); } } else { _warning("=======> odd case 1"); } } // stanza from other users received elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) { if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; } else { _warning("=======> odd case 2"); } } else { _warning("=======> odd case 3"); } }); -$client->add_cb('on_disconnect', function() { +$client->add_cb('on_disconnect', function () { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/pipes.php b/examples/pipes.php index 8fa44dc..4aa78d5 100644 --- a/examples/pipes.php +++ b/examples/pipes.php @@ -1,57 +1,57 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // include jaxl pipes require_once JAXL_CWD.'/core/jaxl_pipe.php'; // initialize $pipe_name = getmypid(); $pipe = new JAXLPipe($pipe_name); // add read event callback -$pipe->set_callback(function($data) { +$pipe->set_callback(function ($data) { global $pipe; _info("read ".trim($data)." from pipe"); }); JAXLLoop::run(); echo "done\n"; diff --git a/examples/publisher.php b/examples/publisher.php index bc94b36..7f29f16 100644 --- a/examples/publisher.php +++ b/examples/publisher.php @@ -1,97 +1,97 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // -$client->add_cb('on_auth_success', function() { +$client->add_cb('on_auth_success', function () { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // create node //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); // publish $item = new JAXLXml('item', null, array('id' => time())); $item->c('entry', 'http://www.w3.org/2005/Atom'); $item->c('title')->t('Soliloquy')->up(); $item->c('summary')->t('To be, or not to be: that is the question')->up(); $item->c('link', null, array('rel' => 'alternate', 'type' => 'text/html', 'href' => 'http://denmark.lit/2003/12/13/atom03'))->up(); $item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up(); $item->c('published')->t('2003-12-13T18:30:02Z')->up(); $item->c('updated')->t('2003-12-13T18:30:02Z')->up(); $client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item); }); -$client->add_cb('on_auth_failure', function($reason) { +$client->add_cb('on_auth_failure', function ($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); -$client->add_cb('on_disconnect', function() { +$client->add_cb('on_disconnect', function () { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/register_user.php b/examples/register_user.php index 1884da3..604bc49 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,166 +1,166 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // $form = array(); function wait_for_register_response($event, $args) { global $client, $form; if ($event == 'stanza_cb') { $stanza = $args[0]; if ($stanza->name == 'iq') { $form['type'] = $stanza->attrs['type']; if ($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } elseif ($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } } } else { _notice("unhandled event $event rcvd"); } } function wait_for_register_form($event, $args) { global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if ($query) { $instructions = $query->exists('instructions'); if ($instructions) { echo $instructions->text.PHP_EOL; } foreach ($query->childrens as $k => $child) { if ($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // -$client->add_cb('on_stream_features', function($stanza) { +$client->add_cb('on_stream_features', function ($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; }); -$client->add_cb('on_disconnect', function() { +$client->add_cb('on_disconnect', function () { global $form; _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); }); // // finally start configured xmpp stream // $client->start(); // // if registration was successful // try to connect with newly registered account // if ($form['type'] == 'result') { _info("connecting newly registered user account"); $client = new JAXL(array( 'jid' => $form['username'].'@'.$argv[1], 'pass' => $form['password'], 'log_level' => JAXL_DEBUG )); -$client->add_cb('on_auth_success', function() { +$client->add_cb('on_auth_success', function () { global $client; $client->set_status('Available'); }); $client->start(); } echo "done\n"; diff --git a/examples/subscriber.php b/examples/subscriber.php index 899278f..e6974f4 100644 --- a/examples/subscriber.php +++ b/examples/subscriber.php @@ -1,96 +1,96 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // -$client->add_cb('on_auth_success', function() { +$client->add_cb('on_auth_success', function () { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // create node //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); // subscribe $client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node'); }); -$client->add_cb('on_auth_failure', function($reason) { +$client->add_cb('on_auth_failure', function ($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); -$client->add_cb('on_headline_message', function($stanza) { +$client->add_cb('on_headline_message', function ($stanza) { global $client; if (($event = $stanza->exists('event', NS_PUBSUB.'#event'))) { _info("got pubsub event"); } else { _warning("unknown headline message rcvd"); } }); -$client->add_cb('on_disconnect', function() { +$client->add_cb('on_disconnect', function () { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/xfacebook_platform_client.php b/examples/xfacebook_platform_client.php index 00c5ce9..dbcf4de 100644 --- a/examples/xfacebook_platform_client.php +++ b/examples/xfacebook_platform_client.php @@ -1,98 +1,98 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc != 4) { echo "Usage: $argv[0] fb_user_id_or_username fb_app_key fb_access_token\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1].'@chat.facebook.com', 'fb_app_key' => $argv[2], 'fb_access_token' => $argv[3], // force tls (facebook require this now) 'force_tls' => true, // (required) force facebook oauth 'auth_type' => 'X-FACEBOOK-PLATFORM', // (optional) //'resource' => 'resource', 'log_level' => JAXL_INFO )); // // add necessary event callbacks here // -$client->add_cb('on_auth_success', function() { +$client->add_cb('on_auth_success', function () { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); $client->set_status("available!", "dnd", 10); }); -$client->add_cb('on_auth_failure', function($reason) { +$client->add_cb('on_auth_failure', function ($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); -$client->add_cb('on_chat_message', function($stanza) { +$client->add_cb('on_chat_message', function ($stanza) { global $client; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); -$client->add_cb('on_disconnect', function() { +$client->add_cb('on_disconnect', function () { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/xmpp_rest.php b/examples/xmpp_rest.php index 18cdcb4..0f0c579 100644 --- a/examples/xmpp_rest.php +++ b/examples/xmpp_rest.php @@ -1,75 +1,75 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // View explanation for this example here: // https://groups.google.com/d/msg/jaxl/QaGjZP4A2gY/n6SYutrBVxsJ if ($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // initialize xmpp client require_once 'jaxl.php'; $xmpp = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); // register callbacks on required xmpp events -$xmpp->add_cb('on_auth_success', function() { +$xmpp->add_cb('on_auth_success', function () { global $xmpp; _info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string()); }); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); // add generic callback // you can also dispatch REST style callback // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules -$http->cb = function($request) { +$http->cb = function ($request) { // For demo purposes we simply return xmpp client full jid global $xmpp; $request->ok($xmpp->full_jid->to_string()); }; // This will start main JAXLLoop, // hence we don't need to call $http->start() explicitly $xmpp->start(); diff --git a/examples/xoauth2_gtalk_client.php b/examples/xoauth2_gtalk_client.php index 81e90b5..ac040aa 100644 --- a/examples/xoauth2_gtalk_client.php +++ b/examples/xoauth2_gtalk_client.php @@ -1,97 +1,97 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc != 3) { echo "Usage: $argv[0] jid access_token\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // force tls 'force_tls' => true, // (required) perform X-OAUTH2 'auth_type' => 'X-OAUTH2', // (optional) //'resource' => 'resource', 'log_level' => JAXL_DEBUG )); // // add necessary event callbacks here // -$client->add_cb('on_auth_success', function() { +$client->add_cb('on_auth_success', function () { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); $client->set_status("available!", "dnd", 10); }); -$client->add_cb('on_auth_failure', function($reason) { +$client->add_cb('on_auth_failure', function ($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); -$client->add_cb('on_chat_message', function($stanza) { +$client->add_cb('on_chat_message', function ($stanza) { global $client; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); -$client->add_cb('on_disconnect', function() { +$client->add_cb('on_disconnect', function () { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n";
jaxl/JAXL
dbcfa2c5b9f7db95dbc0f842208de9fb4d983877
Fix PSR: No space found after comma in function call
diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php index 324ad78..bd6a470 100644 --- a/core/jaxl_clock.php +++ b/core/jaxl_clock.php @@ -1,129 +1,129 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class JAXLClock { // current clock time in microseconds private $tick = 0; // current Unix timestamp with microseconds public $time = null; // scheduled jobs public $jobs = array(); public function __construct() { $this->time = microtime(true); } public function __destruct() { _info("shutting down clock server..."); } public function tick($by = null) { // update clock if ($by) { $this->tick += $by; - $this->time += $by / pow(10,6); + $this->time += $by / pow(10, 6); } else { $time = microtime(true); $by = $time - $this->time; $this->tick += $by * pow(10, 6); $this->time = $time; } // run scheduled jobs foreach ($this->jobs as $ref => $job) { if ($this->tick >= $job['scheduled_on'] + $job['after']) { //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".$job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); call_user_func($job['cb'], $job['args']); if (!$job['is_periodic']) { unset($this->jobs[$ref]); } else { $job['scheduled_on'] = $this->tick; $job['runs']++; $this->jobs[$ref] = $job; } } } } // calculate execution time of callback public function tc($callback, $args = null) { } // callback after $time microseconds public function call_fun_after($time, $callback, $args = null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => false, 'runs' => 0 ); return sizeof($this->jobs); } // callback periodically after $time microseconds public function call_fun_periodic($time, $callback, $args = null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => true, 'runs' => 0 ); return sizeof($this->jobs); } // cancel a previously scheduled callback public function cancel_fun_call($ref) { unset($this->jobs[$ref-1]); } } diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index 3601cf5..67ce316 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,168 +1,168 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLLoop { public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; private function __construct() { } private function __clone() { } public static function watch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } if (isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function unwatch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; if (isset(self::$read_fds[$fdid])) { unset(self::$read_fds[$fdid]); unset(self::$read_cbs[$fdid]); --self::$active_read_fds; } } if (isset($opts['write'])) { $fdid = (int) $fd; if (isset(self::$write_fds[$fdid])) { unset(self::$write_fds[$fdid]); unset(self::$write_cbs[$fdid]); --self::$active_write_fds; } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function run() { if (!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); while ((self::$active_read_fds + self::$active_write_fds) > 0) { self::select(); } _debug("no more active fd's to select"); self::$is_running = false; } } private static function select() { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); if ($changed === false) { _error("error in the event loop, shutting down..."); /*foreach (self::$read_fds as $fd) { if (is_resource($fd)) { print_r(stream_get_meta_data($fd)); } }*/ exit; } elseif ($changed > 0) { // read callback foreach ($read as $r) { $fdid = array_search($r, self::$read_fds); if (isset(self::$read_fds[$fdid])) { call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); } } // write callback foreach ($write as $w) { $fdid = array_search($w, self::$write_fds); if (isset(self::$write_fds[$fdid])) { call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); } } self::$clock->tick(); } elseif ($changed === 0) { //_debug("nothing changed while selecting for read"); - self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); + self::$clock->tick((self::$secs * pow(10, 6)) + self::$usecs); } } } diff --git a/xep/xep_0199.php b/xep/xep_0199.php index 91bb445..da19ff9 100644 --- a/xep/xep_0199.php +++ b/xep/xep_0199.php @@ -1,63 +1,63 @@ <?php require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_XMPP_PING', 'urn:xmpp:ping'); class XEP_0199 extends XMPPXep { // // abstract method // public function init() { return array( 'on_auth_success' => 'on_auth_success', 'on_get_iq' => 'on_xmpp_ping' ); } // // api methods // public function get_ping_pkt() { $attrs = array( 'type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $this->jaxl->full_jid->domain ); return $this->jaxl->get_iq_pkt( $attrs, new JAXLXml('ping', NS_XMPP_PING) ); } public function ping() { $this->jaxl->send($this->get_ping_pkt()); } // // event callbacks // public function on_auth_success() { - JAXLLoop::$clock->call_fun_periodic(30 * pow(10,6), array(&$this, 'ping')); + JAXLLoop::$clock->call_fun_periodic(30 * pow(10, 6), array(&$this, 'ping')); } public function on_xmpp_ping($stanza) { if ($stanza->exists('ping', NS_XMPP_PING)) { $stanza->type = "result"; $stanza->to = $stanza->from; $stanza->from = $this->jaxl->full_jid->to_string(); $this->jaxl->send($stanza); } } } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index 39761a3..baeb5b0 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,724 +1,724 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass = null, $resource = null, $force_tls = false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; } if (isset($jid->domain)) { $xml .= 'to="'.$jid->domain.'" '; } $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if (strlen($pass) == 0) { $stanza->t('='); } break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if (!isset($decoded['digest-uri'])) { $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; } $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) { $decoded['qop'] = 'auth'; } $data = array_merge($decoded, array('nc' => $nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) { if (isset($decoded[$key])) { $response[$key] = $decoded[$key]; } } return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if (!$msg->id) { $msg->id = $this->get_id(); } if ($payload) { $msg->cnode($payload); } return $msg; } public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if (!$pres->id) { $pres->id = $this->get_id(); } if ($payload) { $pres->cnode($payload); } return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if (!$iq->id) { $iq->id = $this->get_id(); } if ($payload) { $iq->cnode($payload); } return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach ($data as $key => $value) { $return[] = $key . '="' . $value . '"'; } return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach (array('realm', 'cnonce', 'digest-uri') as $key) { if (!isset($data[$key])) { $data[$key] = ''; } } $pack = md5($user.':'.$data['realm'].':'.$pass); if (isset($data['authzid'])) { - $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); + $a1 = pack('H32', $pack).sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']); } else { - $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); + $a1 = pack('H32', $pack).sprintf(':%s:%s', $data['nonce'], $data['cnonce']); } $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters elseif ($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } elseif ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } elseif ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if ($stanza->name == 'message') { $this->handle_message($stanza); } elseif ($stanza->name == 'presence') { $this->handle_presence($stanza); } elseif ($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } }
jaxl/JAXL
60b1aa8a815c5e63d0de64e70df0bc4a9a2a25a6
Fix PSR: One line per statement
diff --git a/core/jaxl_logger.php b/core/jaxl_logger.php index 2883156..3a110f7 100644 --- a/core/jaxl_logger.php +++ b/core/jaxl_logger.php @@ -1,115 +1,117 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // log level define('JAXL_ERROR', 1); define('JAXL_WARNING', 2); define('JAXL_NOTICE', 3); define('JAXL_INFO', 4); define('JAXL_DEBUG', 5); // generic global logging shortcuts for different level of verbosity function _error($msg) { JAXLLogger::log($msg, JAXL_ERROR); } function _warning($msg) { JAXLLogger::log($msg, JAXL_WARNING); } function _notice($msg) { JAXLLogger::log($msg, JAXL_NOTICE); } function _info($msg) { JAXLLogger::log($msg, JAXL_INFO); } function _debug($msg) { JAXLLogger::log($msg, JAXL_DEBUG); } // generic global terminal output colorize method // finally sends colorized message to terminal using error_log/1 // this method is mainly to escape $msg from file:line and time // prefix done by _debug, _error, ... methods function _colorize($msg, $verbosity) { error_log(JAXLLogger::colorize($msg, $verbosity)); } class JAXLLogger { public static $level = JAXL_DEBUG; public static $path = null; public static $max_log_size = 1000; protected static $colors = array( 1 => 31, // error: red 2 => 34, // warning: blue 3 => 33, // notice: yellow 4 => 32, // info: green 5 => 37 // debug: white ); public static function log($msg, $verbosity = 1) { if ($verbosity <= self::$level) { - $bt = debug_backtrace(); array_shift($bt); $callee = array_shift($bt); + $bt = debug_backtrace(); + array_shift($bt); + $callee = array_shift($bt); $msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg; $size = strlen($msg); if ($size > self::$max_log_size) { $msg = substr($msg, 0, self::$max_log_size) . ' ...'; } if (isset(self::$path)) { error_log($msg . PHP_EOL, 3, self::$path); } else { error_log(self::colorize($msg, $verbosity)); } } } public static function colorize($msg, $verbosity) { return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m"; } } diff --git a/http/http_request.php b/http/http_request.php index f47eaa6..5015270 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,511 +1,512 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers = array(), $body = null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if (sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation // public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; if ($this->body === null) { $this->body = $rcvd; } else { $this->body .= $rcvd; } if ($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach ($form_data as $data) { //_debug("passing $data to multipart fsm"); if (!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if (!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if (!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { switch($event) { case 'empty_line': return 'headers_received'; break; default: if (substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if (method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } } elseif (@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { - $k = trim($k); $v = ltrim($v); + $k = trim($k); + $v = ltrim($v); // is expect header? if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if (strtolower($k) == 'content-type') { $ctype = explode(';', $v); if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if (strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if ($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { if (sizeof($args) == 0) { $body = null; $headers = array(); } if (sizeof($args) == 1) { // http headers or body only received if (is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } } elseif (sizeof($args) == 2) { // body and http headers both received if (is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { foreach ($headers as $k => $v) { $this->_send_header($k, $v); } } protected function _send_body($body) { $this->_send($body); } protected function _send_response($code, $headers = array(), $body = null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set if ($body && !isset($headers['Content-Length'])) { $headers['Content-Length'] = strlen($body); } // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); if ($body) { $this->_send_body(HTTP_CRLF.$body); } } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if (sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach ($query as $q) { $q = explode("=", $q); if (sizeof($q) == 1) { $q[1] = ""; } $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } }
jaxl/JAXL
fe57f81371c595ed70119e55abc280cbd4992ab0
Fix PSR: Inline control structures 2
diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index ce8ed1c..3601cf5 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,167 +1,168 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLLoop { public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; private function __construct() { } private function __clone() { } public static function watch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } if (isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function unwatch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; if (isset(self::$read_fds[$fdid])) { unset(self::$read_fds[$fdid]); unset(self::$read_cbs[$fdid]); --self::$active_read_fds; } } if (isset($opts['write'])) { $fdid = (int) $fd; if (isset(self::$write_fds[$fdid])) { unset(self::$write_fds[$fdid]); unset(self::$write_cbs[$fdid]); --self::$active_write_fds; } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function run() { if (!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); - while ((self::$active_read_fds + self::$active_write_fds) > 0) + while ((self::$active_read_fds + self::$active_write_fds) > 0) { self::select(); + } _debug("no more active fd's to select"); self::$is_running = false; } } private static function select() { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); if ($changed === false) { _error("error in the event loop, shutting down..."); /*foreach (self::$read_fds as $fd) { if (is_resource($fd)) { print_r(stream_get_meta_data($fd)); } }*/ exit; } elseif ($changed > 0) { // read callback foreach ($read as $r) { $fdid = array_search($r, self::$read_fds); if (isset(self::$read_fds[$fdid])) { call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); } } // write callback foreach ($write as $w) { $fdid = array_search($w, self::$write_fds); if (isset(self::$write_fds[$fdid])) { call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); } } self::$clock->tick(); } elseif ($changed === 0) { //_debug("nothing changed while selecting for read"); self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); } } } diff --git a/core/jaxl_util.php b/core/jaxl_util.php index e37e88f..9b5a52d 100644 --- a/core/jaxl_util.php +++ b/core/jaxl_util.php @@ -1,72 +1,74 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh * */ class JAXLUtil { public static function get_nonce($binary = true) { $nce = ''; mt_srand((double) microtime()*10000000); - for ($i = 0; $i<32; $i++) $nce .= chr(mt_rand(0, 255)); + for ($i = 0; $i<32; $i++) { + $nce .= chr(mt_rand(0, 255)); + } return $binary ? $nce : base64_encode($nce); } public static function get_dns_srv($domain) { $rec = dns_get_record("_xmpp-client._tcp.".$domain, DNS_SRV); if (is_array($rec)) { if (sizeof($rec) == 0) { return array($domain, 5222); } if (sizeof($rec) > 0) { return array($rec[0]['target'], $rec[0]['port']); } } } public static function pbkdf2($data, $secret, $iteration, $dkLen = 32, $algo = 'sha1') { return ''; } } diff --git a/http/http_request.php b/http/http_request.php index d08aebc..f47eaa6 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,510 +1,511 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers = array(), $body = null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if (sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation // public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; if ($this->body === null) { $this->body = $rcvd; } else { $this->body .= $rcvd; } if ($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach ($form_data as $data) { //_debug("passing $data to multipart fsm"); if (!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if (!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if (!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { switch($event) { case 'empty_line': return 'headers_received'; break; default: if (substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if (method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } } elseif (@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { $k = trim($k); $v = ltrim($v); // is expect header? if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if (strtolower($k) == 'content-type') { $ctype = explode(';', $v); if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if (strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if ($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { if (sizeof($args) == 0) { $body = null; $headers = array(); } if (sizeof($args) == 1) { // http headers or body only received if (is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } } elseif (sizeof($args) == 2) { // body and http headers both received if (is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { - foreach ($headers as $k => $v) + foreach ($headers as $k => $v) { $this->_send_header($k, $v); + } } protected function _send_body($body) { $this->_send($body); } protected function _send_response($code, $headers = array(), $body = null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set if ($body && !isset($headers['Content-Length'])) { $headers['Content-Length'] = strlen($body); } // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); if ($body) { $this->_send_body(HTTP_CRLF.$body); } } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if (sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach ($query as $q) { $q = explode("=", $q); if (sizeof($q) == 1) { $q[1] = ""; } $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } } diff --git a/xep/xep_0077.php b/xep/xep_0077.php index 5ca27da..d249411 100644 --- a/xep/xep_0077.php +++ b/xep/xep_0077.php @@ -1,85 +1,87 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_FEATURE_REGISTER', 'http://jabber.org/features/iq-register'); define('NS_INBAND_REGISTER', 'jabber:iq:register'); class XEP_0077 extends XMPPXep { // // abstract method // public function init() { return array( ); } // // api methods // public function get_form_pkt($domain) { return $this->jaxl->get_iq_pkt( array('to' => $domain, 'type' => 'get'), new JAXLXml('query', NS_INBAND_REGISTER) ); } public function get_form($domain) { $this->jaxl->send($this->get_form_pkt($domain)); } public function set_form($domain, $form) { $query = new JAXLXml('query', NS_INBAND_REGISTER); - foreach ($form as $k => $v) $query->c($k, null, array(), $v)->up(); + foreach ($form as $k => $v) { + $query->c($k, null, array(), $v)->up(); + } $pkt = $this->jaxl->get_iq_pkt( array('to' => $domain, 'type' => 'set'), $query ); $this->jaxl->send($pkt); } } diff --git a/xep/xep_0115.php b/xep/xep_0115.php index 13d8176..efe8e2a 100644 --- a/xep/xep_0115.php +++ b/xep/xep_0115.php @@ -1,73 +1,75 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_CAPS', 'http://jabber.org/protocol/caps'); class XEP_0115 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods // public function get_caps_pkt($cat, $type, $lang, $name, $node, $features) { asort($features); $S = $cat.'/'.$type.'/'.$lang.'/'.$name.'<'; - foreach ($features as $feature) $S .= $feature.'<'; + foreach ($features as $feature) { + $S .= $feature.'<'; + } $ver = base64_encode(sha1($S, true)); $stanza = new JAXLXml('c', NS_CAPS, array('hash' => 'sha1', 'node' => $node, 'ver' => $ver)); return $stanza; } // // event callbacks // } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index 4170ddb..39761a3 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,722 +1,724 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass = null, $resource = null, $force_tls = false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; } if (isset($jid->domain)) { $xml .= 'to="'.$jid->domain.'" '; } $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if (strlen($pass) == 0) { $stanza->t('='); } break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if (!isset($decoded['digest-uri'])) { $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; } $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) { $decoded['qop'] = 'auth'; } $data = array_merge($decoded, array('nc' => $nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) { if (isset($decoded[$key])) { $response[$key] = $decoded[$key]; } } return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if (!$msg->id) { $msg->id = $this->get_id(); } if ($payload) { $msg->cnode($payload); } return $msg; } public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if (!$pres->id) { $pres->id = $this->get_id(); } if ($payload) { $pres->cnode($payload); } return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if (!$iq->id) { $iq->id = $this->get_id(); } if ($payload) { $iq->cnode($payload); } return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); - foreach ($data as $key => $value) $return[] = $key . '="' . $value . '"'; + foreach ($data as $key => $value) { + $return[] = $key . '="' . $value . '"'; + } return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach (array('realm', 'cnonce', 'digest-uri') as $key) { if (!isset($data[$key])) { $data[$key] = ''; } } $pack = md5($user.':'.$data['realm'].':'.$pass); if (isset($data['authzid'])) { $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); } else { $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); } $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters elseif ($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } elseif ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } elseif ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if ($stanza->name == 'message') { $this->handle_message($stanza); } elseif ($stanza->name == 'presence') { $this->handle_presence($stanza); } elseif ($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } }
jaxl/JAXL
3528681a50aa9d64a27cdbf4bd00abd0d0108edd
Fix PSR: Inline control strictures
diff --git a/core/jaxl_cli.php b/core/jaxl_cli.php index 946466e..75114c2 100644 --- a/core/jaxl_cli.php +++ b/core/jaxl_cli.php @@ -1,99 +1,105 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLCli { public static $counter = 0; private $in = null; private $quit_cb = null; private $recv_cb = null; private $recv_chunk_size = 1024; public function __construct($recv_cb = null, $quit_cb = null) { $this->recv_cb = $recv_cb; $this->quit_cb = $quit_cb; // catch read event on stdin $this->in = fopen('php://stdin', 'r'); stream_set_blocking($this->in, false); JAXLLoop::watch($this->in, array( 'read' => array(&$this, 'on_read_ready') )); } public function __destruct() { @fclose($this->in); } public function stop() { JAXLLoop::unwatch($this->in, array( 'read' => true )); } public function on_read_ready($in) { $raw = @fread($in, $this->recv_chunk_size); if (ord($raw) == 10) { // enter key JAXLCli::prompt(false); return; } elseif (trim($raw) == 'quit') { $this->stop(); $this->in = null; - if ($this->quit_cb) call_user_func($this->quit_cb); + if ($this->quit_cb) { + call_user_func($this->quit_cb); + } return; } - if ($this->recv_cb) call_user_func($this->recv_cb, $raw); + if ($this->recv_cb) { + call_user_func($this->recv_cb, $raw); + } } public static function prompt($inc = true) { - if ($inc) ++self::$counter; + if ($inc) { + ++self::$counter; + } echo "jaxl ".self::$counter."> "; } } diff --git a/core/jaxl_event.php b/core/jaxl_event.php index d4356a4..b863584 100644 --- a/core/jaxl_event.php +++ b/core/jaxl_event.php @@ -1,125 +1,131 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * following kind of events are possible: * 1) hook i.e. if a callback for such an event is registered, calling function is responsible for the workflow from their on * 2) filter i.e. calling function will manipulate passed arguments and modified arguments will be passed to next chain of filter * * As a rule of thumb, only 1 hook can be registered for an event, while more than 1 filter is allowed for an event * hook and filter both cannot be applied on an event * * @author abhinavsingh * */ class JAXLEvent { protected $common = array(); public $reg = array(); public function __construct($common) { $this->common = $common; } public function __destruct() { } // add callback on a event // returns a reference to be used while deleting callback // callback'd method must return TRUE to be persistent // if none returned or FALSE, callback will be removed automatically public function add($ev, $cb, $pri) { - if (!isset($this->reg[$ev])) + if (!isset($this->reg[$ev])) { $this->reg[$ev] = array(); + } $ref = sizeof($this->reg[$ev]); $this->reg[$ev][] = array($pri, $cb); return $ev."-".$ref; } // emit event to notify registered callbacks // is a pqueue required here for performance enhancement // in case we have too many cbs on a specific event? public function emit($ev, $data = array()) { $data = array_merge($this->common, $data); $cbs = array(); - if (!isset($this->reg[$ev])) return $data; + if (!isset($this->reg[$ev])) { + return $data; + } foreach ($this->reg[$ev] as $cb) { - if (!isset($cbs[$cb[0]])) + if (!isset($cbs[$cb[0]])) { $cbs[$cb[0]] = array(); + } $cbs[$cb[0]][] = $cb[1]; } foreach ($cbs as $pri => $cb) { foreach ($cb as $c) { $ret = call_user_func_array($c, $data); // this line is for fixing situation where callback function doesn't return an array type // in such cases next call of call_user_func_array will report error since $data is not an array type as expected // things will change in future, atleast put the callback inside a try/catch block // here we only check if there was a return, if yes we update $data with return value // this is bad design, need more thoughts, should work as of now - if ($ret) $data = $ret; + if ($ret) { + $data = $ret; + } } } unset($cbs); return $data; } // remove previous registered callback public function del($ref) { $ref = explode("-", $ref); unset($this->reg[$ref[0]][$ref[1]]); } public function exists($ev) { $ret = isset($this->reg[$ev]); //_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists")); return $ret; } } diff --git a/core/jaxl_fsm.php b/core/jaxl_fsm.php index 8a42fc6..2aa9b25 100644 --- a/core/jaxl_fsm.php +++ b/core/jaxl_fsm.php @@ -1,83 +1,90 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ abstract class JAXLFsm { protected $state = null; // abstract method abstract public function handle_invalid_state($r); public function __construct($state) { $this->state = $state; } // returned value from state callbacks can be: // 1) array() <-- is_callable method // 2) array([0] => 'new_state', [1] => 'return value for current callback') <-- is_not_callable method // 3) array([0] => 'new_state') // 4) 'new_state' // // for case 1) new state will be an array // for other cases new state will be a string public function __call($event, $args) { if ($this->state) { // call state method _debug("calling state handler '".(is_array($this->state) ? $this->state[1] : $this->state)."' for incoming event '".$event."'"); $call = is_callable($this->state) ? $this->state : (method_exists($this, $this->state) ? array(&$this, $this->state): $this->state); $r = call_user_func($call, $event, $args); // 4 cases of possible return value - if (is_callable($r)) $this->state = $r; - elseif (is_array($r) && sizeof($r) == 2) list($this->state, $ret) = $r; - elseif (is_array($r) && sizeof($r) == 1) $this->state = $r[0]; - elseif (is_string($r)) $this->state = $r; - else $this->handle_invalid_state($r); + if (is_callable($r)) { + $this->state = $r; + } elseif (is_array($r) && sizeof($r) == 2) { + list($this->state, $ret) = $r; + } elseif (is_array($r) && sizeof($r) == 1) { + $this->state = $r[0]; + } elseif (is_string($r)) { + $this->state = $r; + } else { + $this->handle_invalid_state($r); + } _debug("current state '".(is_array($this->state) ? $this->state[1] : $this->state)."'"); // return case - if (!is_callable($r) && is_array($r) && sizeof($r) == 2) + if (!is_callable($r) && is_array($r) && sizeof($r) == 2) { return $ret; + } } else { _debug("invalid state found, nothing called for event ".$event.""); } } } diff --git a/core/jaxl_logger.php b/core/jaxl_logger.php index c165ea9..2883156 100644 --- a/core/jaxl_logger.php +++ b/core/jaxl_logger.php @@ -1,110 +1,115 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // log level define('JAXL_ERROR', 1); define('JAXL_WARNING', 2); define('JAXL_NOTICE', 3); define('JAXL_INFO', 4); define('JAXL_DEBUG', 5); // generic global logging shortcuts for different level of verbosity function _error($msg) { JAXLLogger::log($msg, JAXL_ERROR); } function _warning($msg) { JAXLLogger::log($msg, JAXL_WARNING); } function _notice($msg) { JAXLLogger::log($msg, JAXL_NOTICE); } function _info($msg) { JAXLLogger::log($msg, JAXL_INFO); } function _debug($msg) { JAXLLogger::log($msg, JAXL_DEBUG); } // generic global terminal output colorize method // finally sends colorized message to terminal using error_log/1 // this method is mainly to escape $msg from file:line and time // prefix done by _debug, _error, ... methods function _colorize($msg, $verbosity) { error_log(JAXLLogger::colorize($msg, $verbosity)); } class JAXLLogger { public static $level = JAXL_DEBUG; public static $path = null; public static $max_log_size = 1000; protected static $colors = array( 1 => 31, // error: red 2 => 34, // warning: blue 3 => 33, // notice: yellow 4 => 32, // info: green 5 => 37 // debug: white ); public static function log($msg, $verbosity = 1) { if ($verbosity <= self::$level) { $bt = debug_backtrace(); array_shift($bt); $callee = array_shift($bt); $msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg; $size = strlen($msg); - if ($size > self::$max_log_size) $msg = substr($msg, 0, self::$max_log_size) . ' ...'; + if ($size > self::$max_log_size) { + $msg = substr($msg, 0, self::$max_log_size) . ' ...'; + } - if (isset(self::$path)) error_log($msg . PHP_EOL, 3, self::$path); - else error_log(self::colorize($msg, $verbosity)); + if (isset(self::$path)) { + error_log($msg . PHP_EOL, 3, self::$path); + } else { + error_log(self::colorize($msg, $verbosity)); + } } } public static function colorize($msg, $verbosity) { return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m"; } } diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index 7a5f1c4..ce8ed1c 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,164 +1,167 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLLoop { public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; private function __construct() { } private function __clone() { } public static function watch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } if (isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function unwatch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; if (isset(self::$read_fds[$fdid])) { unset(self::$read_fds[$fdid]); unset(self::$read_cbs[$fdid]); --self::$active_read_fds; } } if (isset($opts['write'])) { $fdid = (int) $fd; if (isset(self::$write_fds[$fdid])) { unset(self::$write_fds[$fdid]); unset(self::$write_cbs[$fdid]); --self::$active_write_fds; } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function run() { if (!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); while ((self::$active_read_fds + self::$active_write_fds) > 0) self::select(); _debug("no more active fd's to select"); self::$is_running = false; } } private static function select() { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); if ($changed === false) { _error("error in the event loop, shutting down..."); /*foreach (self::$read_fds as $fd) { - if (is_resource($fd)) + if (is_resource($fd)) { print_r(stream_get_meta_data($fd)); + } }*/ exit; } elseif ($changed > 0) { // read callback foreach ($read as $r) { $fdid = array_search($r, self::$read_fds); - if (isset(self::$read_fds[$fdid])) + if (isset(self::$read_fds[$fdid])) { call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); + } } // write callback foreach ($write as $w) { $fdid = array_search($w, self::$write_fds); - if (isset(self::$write_fds[$fdid])) + if (isset(self::$write_fds[$fdid])) { call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); + } } self::$clock->tick(); } elseif ($changed === 0) { //_debug("nothing changed while selecting for read"); self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); } } } diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php index 5bf0ec3..b5a99a7 100644 --- a/core/jaxl_pipe.php +++ b/core/jaxl_pipe.php @@ -1,116 +1,120 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * bidirectional communication pipes for processes * * This is how this will be (when complete): * $pipe = new JAXLPipe() will return an array of size 2 * $pipe[0] represents the read end of the pipe * $pipe[1] represents the write end of the pipe * * Proposed functionality might even change (currently consider this as experimental) * * @author abhinavsingh * */ class JAXLPipe { protected $perm = 0600; protected $recv_cb = null; protected $fd = null; protected $client = null; public $name = null; public function __construct($name, $read_cb = null) { $pipes_folder = JAXL_CWD.'/.jaxl/pipes'; - if (!is_dir($pipes_folder)) mkdir($pipes_folder); + if (!is_dir($pipes_folder)) { + mkdir($pipes_folder); + } $this->ev = new JAXLEvent(); $this->name = $name; $this->read_cb = $read_cb; $pipe_path = $this->get_pipe_file_path(); if (!file_exists($pipe_path)) { posix_mkfifo($pipe_path, $this->perm); $this->fd = fopen($pipe_path, 'r+'); if (!$this->fd) { _error("unable to open pipe"); } else { _debug("pipe opened using path $pipe_path"); _notice("Usage: $ echo 'Hello World!' > $pipe_path"); $this->client = new JAXLSocketClient(); $this->client->connect($this->fd); $this->client->set_callback(array(&$this, 'on_data')); } } else { _error("pipe with name $name already exists"); } } public function __destruct() { @fclose($this->fd); @unlink($this->get_pipe_file_path()); _debug("unlinking pipe file"); } public function get_pipe_file_path() { return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe'; } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function on_data($data) { // callback - if ($this->recv_cb) call_user_func($this->recv_cb, $data); + if ($this->recv_cb) { + call_user_func($this->recv_cb, $data); + } } } diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index c0de786..abbb065 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,225 +1,236 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; public function __construct($stream_context = null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ public function connect($socket_path) { if (gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); - if (sizeof($path_parts) == 3) $this->port = $path_parts[2]; + if (sizeof($path_parts) == 3) { + $this->port = $path_parts[2]; + } _info("trying ".$socket_path); - if ($this->stream_context) $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); - else $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); + if ($this->stream_context) { + $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); + } else { + $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); + } } else { $this->fd = &$socket_path; } if ($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); $this->disconnect(); return false; } } public function disconnect() { JAXLLoop::unwatch($this->fd, array( 'read' => true, 'write' => true )); @fclose($this->fd); $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); return $ret; } public function send($data) { $this->obuffer .= $data; // add watch for write events - if ($this->writing) return; + if ($this->writing) { + return; + } JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if ($bytes === 0) { $meta = stream_get_meta_data($fd); if ($meta['eof'] === true) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); - if ($bytes > 0) _debug($raw); + if ($bytes > 0) { + _debug($raw); + } // callback - if ($this->recv_cb) call_user_func($this->recv_cb, $raw); + if ($this->recv_cb) { + call_user_func($this->recv_cb, $raw); + } } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if (strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } } diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index a28f986..36d1590 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,263 +1,268 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLSocketServer { public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; public function __construct($path, $accept_cb, $request_cb) { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; $ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog))); if (($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { if (@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); } else { _error("unable to set non block flag"); } } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } public function __destruct() { _info("shutting down socket server"); } public function read($client_id) { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } public function send($client_id, $data) { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } public function close($client_id) { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } public function on_server_accept_ready($server) { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); if (!$client) { _error("unable to accept new client conn"); return; } if (@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do if ($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); } // if no accept callback is registered // close the accepted connection else { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } } else { _error("unable to set non block flag"); } } public function on_client_read_ready($client) { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); if ($bytes === 0) { $meta = stream_get_meta_data($client); if ($meta['eof'] === true) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); @fclose($client); unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; - if ($this->request_cb) + if ($this->request_cb) { call_user_func($this->request_cb, $client_id, $total); + } $this->clients[$client_id]['ibuffer'] = ''; } public function on_client_write_ready($client) { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); if ($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; } elseif ($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler if (strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } } catch(JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // protected function add_read_cb($client_id) { - if ($this->clients[$client_id]['reading']) + if ($this->clients[$client_id]['reading']) { return; + } JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } protected function add_write_cb($client_id) { - if ($this->clients[$client_id]['writing']) + if ($this->clients[$client_id]['writing']) { return; + } JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } protected function del_read_cb($client_id) { - if (!$this->clients[$client_id]['reading']) + if (!$this->clients[$client_id]['reading']) { return; + } JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } protected function del_write_cb($client_id) { - if (!$this->clients[$client_id]['writing']) + if (!$this->clients[$client_id]['writing']) { return; + } JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } } diff --git a/core/jaxl_util.php b/core/jaxl_util.php index 1cddb7e..e37e88f 100644 --- a/core/jaxl_util.php +++ b/core/jaxl_util.php @@ -1,68 +1,72 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh * */ class JAXLUtil { public static function get_nonce($binary = true) { $nce = ''; mt_srand((double) microtime()*10000000); for ($i = 0; $i<32; $i++) $nce .= chr(mt_rand(0, 255)); return $binary ? $nce : base64_encode($nce); } public static function get_dns_srv($domain) { $rec = dns_get_record("_xmpp-client._tcp.".$domain, DNS_SRV); if (is_array($rec)) { - if (sizeof($rec) == 0) return array($domain, 5222); - if (sizeof($rec) > 0) return array($rec[0]['target'], $rec[0]['port']); + if (sizeof($rec) == 0) { + return array($domain, 5222); + } + if (sizeof($rec) > 0) { + return array($rec[0]['target'], $rec[0]['port']); + } } } public static function pbkdf2($data, $secret, $iteration, $dkLen = 32, $algo = 'sha1') { return ''; } } diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index e30d484..a6fd559 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,204 +1,218 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if (is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if (is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if (is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; foreach ($attrs as $k => $v) { if ($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } public function t($text, $append = false) { if (!$append) { $this->rover->text = $text; } else { - if ($this->rover->text === null) + if ($this->rover->text === null) { $this->rover->text = ''; + } $this->rover->text .= $text; } return $this; } public function c($name, $ns = null, $attrs = array(), $text = null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { - if ($this->rover->parent) $this->rover = &$this->rover->parent; + if ($this->rover->parent) { + $this->rover = &$this->rover->parent; + } return $this; } public function top() { $this->rover = &$this; return $this; } public function exists($name, $ns = null, $attrs = array()) { foreach ($this->childrens as $child) { if ($ns) { - if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) + if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) { return $child; + } } elseif ($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } public function update($name, $ns = null, $attrs = array(), $text = null) { foreach ($this->childrens as $k => $child) { if ($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } public function to_string($parent_ns = null) { $xml = ''; $xml .= '<'.$this->name; - if ($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; - foreach ($this->attrs as $k => $v) if (!is_null($v) && $v !== false) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; + if ($this->ns && $this->ns != $parent_ns) { + $xml .= ' xmlns="'.$this->ns.'"'; + } + foreach ($this->attrs as $k => $v) { + if (!is_null($v) && $v !== false) { + $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; + } + } $xml .= '>'; - foreach ($this->childrens as $child) $xml .= $child->to_string($this->ns); + foreach ($this->childrens as $child) { + $xml .= $child->to_string($this->ns); + } - if ($this->text) $xml .= htmlspecialchars($this->text); + if ($this->text) { + $xml .= htmlspecialchars($this->text); + } $xml .= '</'.$this->name.'>'; return $xml; } } diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php index e1e734b..8f541d2 100644 --- a/core/jaxl_xml_stream.php +++ b/core/jaxl_xml_stream.php @@ -1,197 +1,199 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Enter description here ... * @author abhinavsingh * */ class JAXLXmlStream { private $delimiter = '\\'; private $ns; private $parser; private $stanza; private $depth = -1; private $start_cb; private $stanza_cb; private $end_cb; public function __construct() { $this->init_parser(); } private function init_parser() { $this->depth = -1; $this->parser = xml_parser_create_ns("UTF-8", $this->delimiter); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); xml_set_character_data_handler($this->parser, array(&$this, "handle_character")); xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag")); } public function __destruct() { //_debug("cleaning up xml parser..."); @xml_parser_free($this->parser); } public function reset_parser() { $this->parse_final(null); @xml_parser_free($this->parser); $this->parser = null; $this->init_parser(); } public function set_callback($start_cb, $end_cb, $stanza_cb) { $this->start_cb = $start_cb; $this->end_cb = $end_cb; $this->stanza_cb = $stanza_cb; } public function parse($str) { xml_parse($this->parser, $str, false); } public function parse_final($str) { xml_parse($this->parser, $str, true); } protected function handle_start_tag($parser, $name, $attrs) { $name = $this->explode($name); //echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL; // replace ns with prefix foreach ($attrs as $key => $v) { $k = $this->explode($key); // no ns specified if ($k[0] == null) { $attrs[$k[1]] = $v; } // xml ns elseif ($k[0] == NS_XML) { unset($attrs[$key]); $attrs['xml:'.$k[1]] = $v; } else { _error("==================> unhandled ns prefix on attribute"); // remove attribute else will cause error with bad stanza format // report to developer if above error message is ever encountered unset($attrs[$key]); } } if ($this->depth <= 0) { $this->depth = 0; $this->ns = $name[1]; if ($this->start_cb) { $stanza = new JAXLXml($name[1], $name[0], $attrs); call_user_func($this->start_cb, $stanza); } } else { if (!$this->stanza) { $stanza = new JAXLXml($name[1], $name[0], $attrs); $this->stanza = &$stanza; } else { $this->stanza->c($name[1], $name[0], $attrs); } } ++$this->depth; } protected function handle_end_tag($parser, $name) { $name = explode($this->delimiter, $name); $name = sizeof($name) == 1 ? array('', $name[0]) : $name; //echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL; if ($this->depth == 1) { if ($this->end_cb) { $stanza = new JAXLXml($name[1], $this->ns); call_user_func($this->end_cb, $stanza); } } elseif ($this->depth > 1) { - if ($this->stanza) $this->stanza->up(); + if ($this->stanza) { + $this->stanza->up(); + } if ($this->depth == 2) { if ($this->stanza_cb) { call_user_func($this->stanza_cb, $this->stanza); $this->stanza = null; } } } --$this->depth; } protected function handle_character($parser, $data) { //echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL; if ($this->stanza) { $this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), true); } } private function implode($data) { return implode($this->delimiter, $data); } private function explode($data) { $data = explode($this->delimiter, $data); $data = sizeof($data) == 1 ? array(null, $data[0]) : $data; return $data; } } diff --git a/http/http_client.php b/http/http_client.php index a0db058..b9ebf3d 100644 --- a/http/http_client.php +++ b/http/http_client.php @@ -1,146 +1,150 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ class HTTPClient { private $url = null; private $parts = array(); private $headers = array(); private $data = null; public $method = null; private $client = null; public function __construct($url, $headers = array(), $data = null) { $this->url = $url; $this->headers = $headers; $this->data = $data; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } public function start($method = 'GET') { $this->method = $method; $this->parts = parse_url($this->url); $transport = $this->_transport(); $ip = $this->_ip(); $port = $this->_port(); $socket_path = $transport.'://'.$ip.':'.$port; if ($this->client->connect($socket_path)) { _debug("connection to $this->url established"); // send request data $this->send_request(); // start main loop JAXLLoop::run(); } else { _debug("unable to open $this->url"); } } public function on_response($raw) { _info("got http response"); } protected function send_request() { $this->client->send($this->_line()."\r\n"); $this->client->send($this->_ua()."\r\n"); $this->client->send($this->_host()."\r\n"); $this->client->send("\r\n"); } // // private methods on uri parts // private function _line() { return $this->method.' '.$this->_uri().' HTTP/1.1'; } private function _ua() { return 'User-Agent: jaxl_http_client/3.x'; } private function _host() { return 'Host: '.$this->parts['host'].':'.$this->_port(); } private function _transport() { return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl'); } private function _ip() { return gethostbyname($this->parts['host']); } private function _port() { return @$this->parts['port'] ? $this->parts['port'] : 80; } private function _uri() { $uri = $this->parts['path']; - if (@$this->parts['query']) $uri .= '?'.$this->parts['query']; - if (@$this->parts['fragment']) $uri .= '#'.$this->parts['fragment']; + if (@$this->parts['query']) { + $uri .= '?'.$this->parts['query']; + } + if (@$this->parts['fragment']) { + $uri .= '#'.$this->parts['fragment']; + } return $uri; } } diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php index 6f469cd..0dff465 100644 --- a/http/http_dispatcher.php +++ b/http/http_dispatcher.php @@ -1,124 +1,135 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // // (optionally) set an array of url dispatch rules // each dispatch rule is defined by an array of size 4 like: // array($callback, $pattern, $methods, $extra), where // $callback the method which will be called if this rule matches // $pattern regular expression to match request path // $methods list of allowed methods for this rule // pass boolean true to allow all http methods // if omitted or an empty array() is passed (which actually doesnt make sense) // by default 'GET' will be the method allowed on this rule // $extra reserved for future (you can totally omit this as of now) // class HTTPDispatchRule { // match callback public $cb = null; // regexp to match on request path public $pattern = null; // methods to match upon // add atleast 1 method for this rule to work public $methods = null; // other matching rules public $extra = array(); public function __construct($cb, $pattern, $methods = array('GET'), $extra = array()) { $this->cb = $cb; $this->pattern = $pattern; $this->methods = $methods; $this->extra = $extra; } public function match($path, $method) { if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) { if (in_array($method, $this->methods)) { return $matches; } } return false; } } class HTTPDispatcher { protected $rules = array(); public function __construct() { $this->rules = array(); } public function add_rule($rule) { $s = sizeof($rule); - if ($s > 4) { _debug("invalid rule"); return; } + if ($s > 4) { + _debug("invalid rule"); + return; + } // fill up defaults - if ($s == 3) { $rule[] = array(); - } elseif ($s == 2) { $rule[] = array('GET'); $rule[] = array(); - } else { _debug("invalid rule"); return; } + if ($s == 3) { + $rule[] = array(); + } elseif ($s == 2) { + $rule[] = array('GET'); + $rule[] = array(); + } else { + _debug("invalid rule"); + return; + } $this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]); } public function dispatch($request) { foreach ($this->rules as $rule) { //_debug("matching $request->path with pattern $rule->pattern"); if (($matches = $rule->match($request->path, $request->method)) !== false) { _debug("matching rule found, dispatching"); $params = array($request); // TODO: a bad way to restrict on 'pk', fix me for generalization - if (@isset($matches['pk'])) $params[] = $matches['pk']; + if (@isset($matches['pk'])) { + $params[] = $matches['pk']; + } call_user_func_array($rule->cb, $params); return true; } } return false; } } diff --git a/http/http_request.php b/http/http_request.php index bfc72c2..d08aebc 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,503 +1,510 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers = array(), $body = null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if (sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation // public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; - if ($this->body === null) $this->body = $rcvd; - else $this->body .= $rcvd; + if ($this->body === null) { + $this->body = $rcvd; + } else { + $this->body .= $rcvd; + } if ($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach ($form_data as $data) { //_debug("passing $data to multipart fsm"); if (!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if (!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if (!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { switch($event) { case 'empty_line': return 'headers_received'; break; default: if (substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if (method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } } elseif (@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { $k = trim($k); $v = ltrim($v); // is expect header? if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if (strtolower($k) == 'content-type') { $ctype = explode(';', $v); if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if (strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if ($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { if (sizeof($args) == 0) { $body = null; $headers = array(); } if (sizeof($args) == 1) { // http headers or body only received if (is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } } elseif (sizeof($args) == 2) { // body and http headers both received if (is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { foreach ($headers as $k => $v) $this->_send_header($k, $v); } protected function _send_body($body) { $this->_send($body); } protected function _send_response($code, $headers = array(), $body = null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set - if ($body && !isset($headers['Content-Length'])) + if ($body && !isset($headers['Content-Length'])) { $headers['Content-Length'] = strlen($body); + } // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); - if ($body) + if ($body) { $this->_send_body(HTTP_CRLF.$body); + } } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if (sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach ($query as $q) { $q = explode("=", $q); - if (sizeof($q) == 1) $q[1] = ""; + if (sizeof($q) == 1) { + $q[1] = ""; + } $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } } diff --git a/jaxl.php b/jaxl.php index c6ad713..243111a 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,837 +1,873 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger - if (isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; - //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; - if (isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; - else JAXLLogger::$level = $this->log_level; + if (isset($this->cfg['log_path'])) { + JAXLLogger::$path = $this->cfg['log_path']; + } + //else { JAXLLogger::$path = $this->log_dir."/jaxl.log"; } + if (isset($this->cfg['log_level'])) { + JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; + } else { + JAXLLogger::$level = $this->log_level; + } // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true; - if ($strict) $this->add_exception_handlers(); + if ($strict) { + $this->add_exception_handlers(); + } $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; - if (!is_dir($this->priv_dir)) mkdir($this->priv_dir); - if (!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); - if (!is_dir($this->pid_dir)) mkdir($this->pid_dir); - if (!is_dir($this->log_dir)) mkdir($this->log_dir); - if (!is_dir($this->sock_dir)) mkdir($this->sock_dir); + if (!is_dir($this->priv_dir)) { + mkdir($this->priv_dir); + } + if (!is_dir($this->tmp_dir)) { + mkdir($this->tmp_dir); + } + if (!is_dir($this->pid_dir)) { + mkdir($this->pid_dir); + } + if (!is_dir($this->log_dir)) { + mkdir($this->log_dir); + } + if (!is_dir($this->sock_dir)) { + mkdir($this->sock_dir); + } // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { - if (!is_array($xeps)) + if (!is_array($xeps)) { $xeps = array($xeps); + } foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri = 1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show = 'chat', $priority = 10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type' => 'chat', 'to' => $to, 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid = null, $cb = null) { $attrs = array( 'type' => 'get', 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); - if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); + if ($cb) { + $this->add_cb('on_stanza_id_'.$pkt->id, $cb); + } $this->send($pkt); } public function get_roster($cb = null) { $pkt = $this->get_iq_pkt( array( 'type' => 'get', 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); - if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); + if ($cb) { + $this->add_cb('on_stanza_id_'.$pkt->id, $cb); + } $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts = array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode - if (!$this->ev->exists('on_connect')) + if (!$this->ev->exists('on_connect')) { $this->add_cb('on_connect', array($this, 'start_stream')); + } // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts - if (@$opts['--with-debug-shell']) $this->enable_debug_shell(); - if (@$opts['--with-unix-sock']) $this->enable_unix_sock(); + if (@$opts['--with-debug-shell']) { + $this->enable_debug_shell(); + } + if (@$opts['--with-unix-sock']) { + $this->enable_unix_sock(); + } // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); - if ($mechanisms) foreach ($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; + if ($mechanisms) { + foreach ($mechanisms->childrens as $mechanism) { + $mechs[$mechanism->text] = true; + } + } // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if ($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach ($mechs as $mech => $any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if ($mech == 'X-FACEBOOK-PLATFORM') { if (@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if ($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } elseif ($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } elseif ($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if (!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach ($query->childrens as $child) { if ($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach ($child->childrens as $group) { if ($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above - if (!$emited) + if (!$emited) { $this->ev->emit('on_roster_update'); + } } // if managing roster // catch contact vcard results if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { - if (@$this->roster[$stanza->from]) + if (@$this->roster[$stanza->from]) { $this->roster[$stanza->from]->vcard = $query; + } } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on - if (!$emited) + if (!$emited) { $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); + } } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if ($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if ($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } elseif ($type == 'unavailable') { - if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) + if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) { unset($this->roster[$jid->bare]->resources[$jid->resource]); + } } } // if managing subscription requests // we need to automate stuff here if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); - if ($this->manage_subscribe == "mutual") + if ($this->manage_subscribe == "mutual") { $this->subscribe($stanza->from); + } } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if ($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach ($query->childrens as $k => $child) { if ($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } elseif ($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } elseif ($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach ($query->childrens as $k => $child) { if ($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } diff --git a/xep/xep_0030.php b/xep/xep_0030.php index c6d5cfd..57dedab 100644 --- a/xep/xep_0030.php +++ b/xep/xep_0030.php @@ -1,95 +1,99 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DISCO_INFO', 'http://jabber.org/protocol/disco#info'); define('NS_DISCO_ITEMS', 'http://jabber.org/protocol/disco#items'); class XEP_0030 extends XMPPXep { // // abstract method // public function init() { return array( ); } // // api methods // public function get_info_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid), new JAXLXml('query', NS_DISCO_INFO) ); } public function get_info($entity_jid, $callback = null) { $pkt = $this->get_info_pkt($entity_jid); - if ($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); + if ($callback) { + $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); + } $this->jaxl->send($pkt); } public function get_items_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid), new JAXLXml('query', NS_DISCO_ITEMS) ); } public function get_items($entity_jid, $callback = null) { $pkt = $this->get_items_pkt($entity_jid); - if ($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); + if ($callback) { + $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); + } $this->jaxl->send($pkt); } // // event callbacks // } diff --git a/xep/xep_0206.php b/xep/xep_0206.php index 62a85c2..53e160c 100644 --- a/xep/xep_0206.php +++ b/xep/xep_0206.php @@ -1,239 +1,257 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind'); define('NS_BOSH', 'urn:xmpp:xbosh'); class XEP_0206 extends XMPPXep { private $mch = null; public $chs = array(); private $recv_cb = null; public $rid = null; public $sid = null; private $hold = 1; private $wait = 30; private $restarted = false; public $headers = array( 'Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8' ); // // abstract method // public function init() { $this->mch = curl_multi_init(); return array( ); } // // event callbacks // public function send($body) { if (is_object($body)) { $body = $body->to_string(); } else { if (substr($body, 0, 15) == '<stream:stream ') { $this->restarted = true; $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'xmpp:restart' => 'true', 'xmlns:xmpp' => NS_BOSH )); $body = $body->to_string(); } elseif (substr($body, 0, 16) == '</stream:stream>') { $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'type' => 'terminate' )); $body = $body->to_string(); } else { $body = $this->wrap($body); } } _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body); $this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']); curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers); curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false); curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1); curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body); curl_multi_add_handle($this->mch, $this->chs[$this->rid]); } public function recv() { if ($this->restarted) { $this->restarted = false; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state - if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); + if ($this->recv_cb) { + call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); + } } _debug("recving for $this->rid"); do { $ret = curl_multi_exec($this->mch, $running); $changed = curl_multi_select($this->mch, 0.1); if ($changed == 0 && $running == 0) { $ch = @$this->chs[$this->rid]; if ($ch) { $data = curl_multi_getcontent($ch); curl_multi_remove_handle($this->mch, $ch); unset($this->chs[$this->rid]); _debug("recvd for $this->rid ".$data); list($body, $stanza) = $this->unwrap($data); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if (@$attrs['type'] == 'terminate') { // fool me again - if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); + if ($this->recv_cb) { + call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); + } } else { if (!$this->sid) { $this->sid = $attrs['sid']; } - if ($this->recv_cb) call_user_func($this->recv_cb, $stanza); + if ($this->recv_cb) { + call_user_func($this->recv_cb, $stanza); + } } } else { _error("no ch found"); exit; } } } while ($running); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function wrap($stanza) { return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>'; } public function unwrap($body) { // a dirty way but it works efficiently - if (substr($body, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); - else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); + if (substr($body, -2, 2) == "/>") { + preg_match_all('/<body (.*?)\/>/smi', $body, $m); + } else { + preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); + } - if (isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; - else $envelop = "<body/>"; + if (isset($m[1][0])) { + $envelop = "<body ".$m[1][0]."/>"; + } else { + $envelop = "<body/>"; + } - if (isset($m[2][0])) $payload = $m[2][0]; - else $payload = ''; + if (isset($m[2][0])) { + $payload = $m[2][0]; + } else { + $payload = ''; + } return array($envelop, $payload); } public function session_start() { $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000); $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold; $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state - if ($this->recv_cb) + if ($this->recv_cb) { call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); + } $attrs = array( 'content' => 'text/xml; charset=utf-8', 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'], 'secure' => 'true', 'xml:lang' => 'en', 'xmpp:version' => '1.0', 'xmlns:xmpp' => NS_BOSH, 'hold' => $this->hold, 'wait' => $this->wait, 'rid' => $this->rid, 'ver' => '1.10' ); - if (@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; + if (@$this->jaxl->cfg['jid']) { + $attrs['from'] = @$this->jaxl->cfg['jid']; + } $body = new JAXLXml('body', NS_HTTP_BIND, $attrs); $this->send($body); } public function ping() { $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid)); $this->send($body); } public function session_end() { $this->disconnect(); } public function disconnect() { _debug("disconnecting"); } } diff --git a/xep/xep_0249.php b/xep/xep_0249.php index 12dd79b..8eda5a3 100644 --- a/xep/xep_0249.php +++ b/xep/xep_0249.php @@ -1,82 +1,90 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DIRECT_MUC_INVITATION', 'jabber:x:conference'); class XEP_0249 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods // public function get_invite_pkt($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) { $xattrs = array('jid' => $room_jid); - if ($password) $xattrs['password'] = $password; - if ($reason) $xattrs['reason'] = $reason; - if ($thread) $xattrs['thread'] = $thread; - if ($continue) $xattrs['continue'] = $continue; + if ($password) { + $xattrs['password'] = $password; + } + if ($reason) { + $xattrs['reason'] = $reason; + } + if ($thread) { + $xattrs['thread'] = $thread; + } + if ($continue) { + $xattrs['continue'] = $continue; + } return $this->jaxl->get_msg_pkt( array('from' => $this->jaxl->full_jid->to_string(), 'to' => $to_bare_jid), null, null, null, new JAXLXml('x', NS_DIRECT_MUC_INVITATION, $xattrs) ); } public function invite($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) { $this->jaxl->send($this->get_invite_pkt($to_bare_jid, $room_jid, $password, $reason, $thread, $continue)); } // // event callbacks // } diff --git a/xmpp/xmpp_jid.php b/xmpp/xmpp_jid.php index b0d3d82..7492017 100644 --- a/xmpp/xmpp_jid.php +++ b/xmpp/xmpp_jid.php @@ -1,81 +1,86 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Xmpp Jid * * @author abhinavsingh * */ class XMPPJid { public $node = null; public $domain = null; public $resource = null; public $bare = null; public function __construct($str) { $tmp = explode("@", $str); if (sizeof($tmp) == 2) { $this->node = $tmp[0]; $tmp = explode("/", $tmp[1]); if (sizeof($tmp) == 2) { $this->domain = $tmp[0]; $this->resource = $tmp[1]; } else { $this->domain = $tmp[0]; } } elseif (sizeof($tmp) == 1) { $this->domain = $tmp[0]; } $this->bare = $this->node ? $this->node."@".$this->domain : $this->domain; } public function to_string() { $str = ""; - if ($this->node) $str .= $this->node.'@'.$this->domain; - elseif ($this->domain) $str .= $this->domain; - if ($this->resource) $str .= '/'.$this->resource; + if ($this->node) { + $str .= $this->node.'@'.$this->domain; + } elseif ($this->domain) { + $str .= $this->domain; + } + if ($this->resource) { + $str .= '/'.$this->resource; + } return $str; } } diff --git a/xmpp/xmpp_msg.php b/xmpp/xmpp_msg.php index 838d332..868460c 100644 --- a/xmpp/xmpp_msg.php +++ b/xmpp/xmpp_msg.php @@ -1,52 +1,58 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; class XMPPMsg extends XMPPStanza { public function __construct($attrs, $body = null, $thread = null, $subject = null) { parent::__construct('message', $attrs); - if ($body) $this->c('body')->t($body)->up(); - if ($thread) $this->c('thread')->t($thread)->up(); - if ($subject) $this->c('subject')->t($subject)->up(); + if ($body) { + $this->c('body')->t($body)->up(); + } + if ($thread) { + $this->c('thread')->t($thread)->up(); + } + if ($subject) { + $this->c('subject')->t($subject)->up(); + } } } diff --git a/xmpp/xmpp_pres.php b/xmpp/xmpp_pres.php index a054686..e5b90d7 100644 --- a/xmpp/xmpp_pres.php +++ b/xmpp/xmpp_pres.php @@ -1,52 +1,58 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; class XMPPPres extends XMPPStanza { public function __construct($attrs, $status = null, $show = null, $priority = null) { parent::__construct('presence', $attrs); - if ($status) $this->c('status')->t($status)->up(); - if ($show) $this->c('show')->t($show)->up(); - if ($priority) $this->c('priority')->t($priority)->up(); + if ($status) { + $this->c('status')->t($status)->up(); + } + if ($show) { + $this->c('show')->t($show)->up(); + } + if ($priority) { + $this->c('priority')->t($priority)->up(); + } } } diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php index f8be8da..6dbed80 100644 --- a/xmpp/xmpp_stanza.php +++ b/xmpp/xmpp_stanza.php @@ -1,178 +1,190 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; /** * Generic xmpp stanza object which provide convinient access pattern over xml objects * Also to be able to convert an existing xml object into stanza object (to get access patterns going) * this class doesn't extend xml, but infact works on a reference of xml object * If not provided during constructor, new xml object is created and saved as reference * * @author abhinavsingh * */ class XMPPStanza { private $xml; public function __construct($name, $attrs = array(), $ns = NS_JABBER_CLIENT) { - if ($name instanceof JAXLXml) $this->xml = $name; - else $this->xml = new JAXLXml($name, $ns, $attrs); + if ($name instanceof JAXLXml) { + $this->xml = $name; + } else { + $this->xml = new JAXLXml($name, $ns, $attrs); + } } public function __call($method, $args) { return call_user_func_array(array($this->xml, $method), $args); } public function __get($prop) { switch($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': return @$this->xml->attrs[$prop] ? $this->xml->attrs[$prop] : null; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val = @$this->xml->attrs[$attr] ? $this->xml->attrs[$attr] : null; - if (!$val) return null; + if (!$val) { + return null; + } $val = new XMPPJid($val); return $val->$key; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val = $this->xml->exists($prop); - if (!$val) return null; + if (!$val) { + return null; + } return $val->text; break; default: return null; break; } } public function __set($prop, $val) { switch($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop = $val; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': $this->xml->attrs[$prop] = $val; return true; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val1 = @$this->xml->attrs[$attr]; - if (!$val1) $val1 = ''; + if (!$val1) { + $val1 = ''; + } $val1 = new XMPPJid($val1); $val1->$key = $val; $this->xml->attrs[$attr] = $val1->to_string(); return true; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val1 = $this->xml->exists($prop); - if (!$val1) $this->xml->c($prop)->t($val)->up(); - else $this->xml->update($prop, $val1->ns, $val1->attrs, $val); + if (!$val1) { + $this->xml->c($prop)->t($val)->up(); + } else { + $this->xml->update($prop, $val1->ns, $val1->attrs, $val); + } return true; break; default: return null; break; } } } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index efab4cf..4170ddb 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,700 +1,722 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass = null, $resource = null, $force_tls = false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; - //if (isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; - if (isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; + //if (isset($jid->bare)) { $xml .= 'from="'.$jid->bare.'" '; } + if (isset($jid->domain)) { + $xml .= 'to="'.$jid->domain.'" '; + } $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. - if (strlen($pass) == 0) + if (strlen($pass) == 0) { $stanza->t('='); + } break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; - if (!isset($decoded['digest-uri'])) + if (!isset($decoded['digest-uri'])) { $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; + } $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); - if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) + if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) { $decoded['qop'] = 'auth'; + } $data = array_merge($decoded, array('nc' => $nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); - foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) - if (isset($decoded[$key])) + foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) { + if (isset($decoded[$key])) { $response[$key] = $decoded[$key]; + } + } return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); - if (!$msg->id) $msg->id = $this->get_id(); - if ($payload) $msg->cnode($payload); + if (!$msg->id) { + $msg->id = $this->get_id(); + } + if ($payload) { + $msg->cnode($payload); + } return $msg; } public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null) { $pres = new XMPPPres($attrs, $status, $show, $priority); - if (!$pres->id) $pres->id = $this->get_id(); - if ($payload) $pres->cnode($payload); + if (!$pres->id) { + $pres->id = $this->get_id(); + } + if ($payload) { + $pres->cnode($payload); + } return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); - if (!$iq->id) $iq->id = $this->get_id(); - if ($payload) $iq->cnode($payload); + if (!$iq->id) { + $iq->id = $this->get_id(); + } + if ($payload) { + $iq->cnode($payload); + } return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach ($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { - foreach (array('realm', 'cnonce', 'digest-uri') as $key) - if (!isset($data[$key])) + foreach (array('realm', 'cnonce', 'digest-uri') as $key) { + if (!isset($data[$key])) { $data[$key] = ''; + } + } $pack = md5($user.':'.$data['realm'].':'.$pass); - if (isset($data['authzid'])) + if (isset($data['authzid'])) { $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); - else + } else { $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); + } $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters elseif ($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } elseif ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } elseif ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if ($stanza->name == 'message') { $this->handle_message($stanza); } elseif ($stanza->name == 'presence') { $this->handle_presence($stanza); } elseif ($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } }
jaxl/JAXL
b2062cf99c3054655cc1a4acaf4424e9c4603156
Fix PSR: ELSE IF is discouraged; use ELSEIF instead
diff --git a/core/jaxl_cli.php b/core/jaxl_cli.php index 3621b64..946466e 100644 --- a/core/jaxl_cli.php +++ b/core/jaxl_cli.php @@ -1,99 +1,99 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLCli { public static $counter = 0; private $in = null; private $quit_cb = null; private $recv_cb = null; private $recv_chunk_size = 1024; public function __construct($recv_cb = null, $quit_cb = null) { $this->recv_cb = $recv_cb; $this->quit_cb = $quit_cb; // catch read event on stdin $this->in = fopen('php://stdin', 'r'); stream_set_blocking($this->in, false); JAXLLoop::watch($this->in, array( 'read' => array(&$this, 'on_read_ready') )); } public function __destruct() { @fclose($this->in); } public function stop() { JAXLLoop::unwatch($this->in, array( 'read' => true )); } public function on_read_ready($in) { $raw = @fread($in, $this->recv_chunk_size); if (ord($raw) == 10) { // enter key JAXLCli::prompt(false); return; - } else if (trim($raw) == 'quit') { + } elseif (trim($raw) == 'quit') { $this->stop(); $this->in = null; if ($this->quit_cb) call_user_func($this->quit_cb); return; } if ($this->recv_cb) call_user_func($this->recv_cb, $raw); } public static function prompt($inc = true) { if ($inc) ++self::$counter; echo "jaxl ".self::$counter."> "; } } diff --git a/core/jaxl_fsm.php b/core/jaxl_fsm.php index d5a6d1e..8a42fc6 100644 --- a/core/jaxl_fsm.php +++ b/core/jaxl_fsm.php @@ -1,83 +1,83 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ abstract class JAXLFsm { protected $state = null; // abstract method abstract public function handle_invalid_state($r); public function __construct($state) { $this->state = $state; } // returned value from state callbacks can be: // 1) array() <-- is_callable method // 2) array([0] => 'new_state', [1] => 'return value for current callback') <-- is_not_callable method // 3) array([0] => 'new_state') // 4) 'new_state' // // for case 1) new state will be an array // for other cases new state will be a string public function __call($event, $args) { if ($this->state) { // call state method _debug("calling state handler '".(is_array($this->state) ? $this->state[1] : $this->state)."' for incoming event '".$event."'"); $call = is_callable($this->state) ? $this->state : (method_exists($this, $this->state) ? array(&$this, $this->state): $this->state); $r = call_user_func($call, $event, $args); // 4 cases of possible return value if (is_callable($r)) $this->state = $r; - else if (is_array($r) && sizeof($r) == 2) list($this->state, $ret) = $r; - else if (is_array($r) && sizeof($r) == 1) $this->state = $r[0]; - else if (is_string($r)) $this->state = $r; + elseif (is_array($r) && sizeof($r) == 2) list($this->state, $ret) = $r; + elseif (is_array($r) && sizeof($r) == 1) $this->state = $r[0]; + elseif (is_string($r)) $this->state = $r; else $this->handle_invalid_state($r); _debug("current state '".(is_array($this->state) ? $this->state[1] : $this->state)."'"); // return case if (!is_callable($r) && is_array($r) && sizeof($r) == 2) return $ret; } else { _debug("invalid state found, nothing called for event ".$event.""); } } } diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index 553e0cd..7a5f1c4 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,164 +1,164 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLLoop { public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; private function __construct() { } private function __clone() { } public static function watch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } if (isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function unwatch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; if (isset(self::$read_fds[$fdid])) { unset(self::$read_fds[$fdid]); unset(self::$read_cbs[$fdid]); --self::$active_read_fds; } } if (isset($opts['write'])) { $fdid = (int) $fd; if (isset(self::$write_fds[$fdid])) { unset(self::$write_fds[$fdid]); unset(self::$write_cbs[$fdid]); --self::$active_write_fds; } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function run() { if (!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); while ((self::$active_read_fds + self::$active_write_fds) > 0) self::select(); _debug("no more active fd's to select"); self::$is_running = false; } } private static function select() { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); if ($changed === false) { _error("error in the event loop, shutting down..."); /*foreach (self::$read_fds as $fd) { if (is_resource($fd)) print_r(stream_get_meta_data($fd)); }*/ exit; - } else if ($changed > 0) { + } elseif ($changed > 0) { // read callback foreach ($read as $r) { $fdid = array_search($r, self::$read_fds); if (isset(self::$read_fds[$fdid])) call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); } // write callback foreach ($write as $w) { $fdid = array_search($w, self::$write_fds); if (isset(self::$write_fds[$fdid])) call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); } self::$clock->tick(); - } else if ($changed === 0) { + } elseif ($changed === 0) { //_debug("nothing changed while selecting for read"); self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); } } } diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index 36063b5..a28f986 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,263 +1,263 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLSocketServer { public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; public function __construct($path, $accept_cb, $request_cb) { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; $ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog))); if (($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { if (@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); } else { _error("unable to set non block flag"); } } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } public function __destruct() { _info("shutting down socket server"); } public function read($client_id) { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } public function send($client_id, $data) { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } public function close($client_id) { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } public function on_server_accept_ready($server) { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); if (!$client) { _error("unable to accept new client conn"); return; } if (@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do if ($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); } // if no accept callback is registered // close the accepted connection else { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } } else { _error("unable to set non block flag"); } } public function on_client_read_ready($client) { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); if ($bytes === 0) { $meta = stream_get_meta_data($client); if ($meta['eof'] === true) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); @fclose($client); unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; if ($this->request_cb) call_user_func($this->request_cb, $client_id, $total); $this->clients[$client_id]['ibuffer'] = ''; } public function on_client_write_ready($client) { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); if ($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; - } else if ($written == strlen($total) || $written == $this->send_chunk_size) { + } elseif ($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler if (strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } } catch(JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // protected function add_read_cb($client_id) { if ($this->clients[$client_id]['reading']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } protected function add_write_cb($client_id) { if ($this->clients[$client_id]['writing']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } protected function del_read_cb($client_id) { if (!$this->clients[$client_id]['reading']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } protected function del_write_cb($client_id) { if (!$this->clients[$client_id]['writing']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } } diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index f11059f..e30d484 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,204 +1,204 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if (is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if (is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if (is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; foreach ($attrs as $k => $v) { if ($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } public function t($text, $append = false) { if (!$append) { $this->rover->text = $text; } else { if ($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; } return $this; } public function c($name, $ns = null, $attrs = array(), $text = null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { if ($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } public function top() { $this->rover = &$this; return $this; } public function exists($name, $ns = null, $attrs = array()) { foreach ($this->childrens as $child) { if ($ns) { if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; - } else if ($child->name == $name && $child->match_attrs($attrs)) { + } elseif ($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } public function update($name, $ns = null, $attrs = array(), $text = null) { foreach ($this->childrens as $k => $child) { if ($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } public function to_string($parent_ns = null) { $xml = ''; $xml .= '<'.$this->name; if ($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; foreach ($this->attrs as $k => $v) if (!is_null($v) && $v !== false) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; foreach ($this->childrens as $child) $xml .= $child->to_string($this->ns); if ($this->text) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } } diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php index d24fd03..e1e734b 100644 --- a/core/jaxl_xml_stream.php +++ b/core/jaxl_xml_stream.php @@ -1,197 +1,197 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Enter description here ... * @author abhinavsingh * */ class JAXLXmlStream { private $delimiter = '\\'; private $ns; private $parser; private $stanza; private $depth = -1; private $start_cb; private $stanza_cb; private $end_cb; public function __construct() { $this->init_parser(); } private function init_parser() { $this->depth = -1; $this->parser = xml_parser_create_ns("UTF-8", $this->delimiter); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); xml_set_character_data_handler($this->parser, array(&$this, "handle_character")); xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag")); } public function __destruct() { //_debug("cleaning up xml parser..."); @xml_parser_free($this->parser); } public function reset_parser() { $this->parse_final(null); @xml_parser_free($this->parser); $this->parser = null; $this->init_parser(); } public function set_callback($start_cb, $end_cb, $stanza_cb) { $this->start_cb = $start_cb; $this->end_cb = $end_cb; $this->stanza_cb = $stanza_cb; } public function parse($str) { xml_parse($this->parser, $str, false); } public function parse_final($str) { xml_parse($this->parser, $str, true); } protected function handle_start_tag($parser, $name, $attrs) { $name = $this->explode($name); //echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL; // replace ns with prefix foreach ($attrs as $key => $v) { $k = $this->explode($key); // no ns specified if ($k[0] == null) { $attrs[$k[1]] = $v; } // xml ns - else if ($k[0] == NS_XML) { + elseif ($k[0] == NS_XML) { unset($attrs[$key]); $attrs['xml:'.$k[1]] = $v; } else { _error("==================> unhandled ns prefix on attribute"); // remove attribute else will cause error with bad stanza format // report to developer if above error message is ever encountered unset($attrs[$key]); } } if ($this->depth <= 0) { $this->depth = 0; $this->ns = $name[1]; if ($this->start_cb) { $stanza = new JAXLXml($name[1], $name[0], $attrs); call_user_func($this->start_cb, $stanza); } } else { if (!$this->stanza) { $stanza = new JAXLXml($name[1], $name[0], $attrs); $this->stanza = &$stanza; } else { $this->stanza->c($name[1], $name[0], $attrs); } } ++$this->depth; } protected function handle_end_tag($parser, $name) { $name = explode($this->delimiter, $name); $name = sizeof($name) == 1 ? array('', $name[0]) : $name; //echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL; if ($this->depth == 1) { if ($this->end_cb) { $stanza = new JAXLXml($name[1], $this->ns); call_user_func($this->end_cb, $stanza); } - } else if ($this->depth > 1) { + } elseif ($this->depth > 1) { if ($this->stanza) $this->stanza->up(); if ($this->depth == 2) { if ($this->stanza_cb) { call_user_func($this->stanza_cb, $this->stanza); $this->stanza = null; } } } --$this->depth; } protected function handle_character($parser, $data) { //echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL; if ($this->stanza) { $this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), true); } } private function implode($data) { return implode($this->delimiter, $data); } private function explode($data) { $data = explode($this->delimiter, $data); $data = sizeof($data) == 1 ? array(null, $data[0]) : $data; return $data; } } diff --git a/docs/users/http_examples.rst b/docs/users/http_examples.rst index af515bb..6357e42 100644 --- a/docs/users/http_examples.rst +++ b/docs/users/http_examples.rst @@ -1,102 +1,102 @@ HTTP Examples ============= Writing HTTP Server ------------------- Intialize an ``HTTPServer`` instance .. code-block:: ruby require_once 'jaxl.php'; require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this. Define a callback method that will accept all incoming ``HTTPRequest`` objects .. code-block:: ruby function on_request($request) { if ($request->method == 'GET') { $body = json_encode($request); $request->ok($body, array('Content-Type' => 'application:json')); } else { $request->not_found(); } } ``on_request`` callback method will receive a ``HTTPRequest`` object instance. For this example, we will simply echo back json encoded ``$request`` object for every http GET request. Start http server: .. code-block:: ruby $http->start('on_request'); We pass ``on_request`` method as first parameter to ``HTTPServer::start/1``. If nothing is passed, requests will fail with a default 404 not found error message Writing REST API Server ----------------------- Intialize an ``HTTPServer`` instance .. code-block:: ruby require_once 'jaxl.php'; require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this. Define our REST resources callback methods: .. code-block:: ruby function index($request) { $request->send_response( 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } function upload($request) { if ($request->method == 'GET') { $request->send_response( 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action=""><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' ); - } else if ($request->method == 'POST') { + } elseif ($request->method == 'POST') { if ($request->body === null && $request->expect) { $request->recv_body(); } else { // got upload body, save it _debug("file upload complete, got ".strlen($request->body)." bytes of data"); $request->close(); } } } Next we need to register dispatch rules for our callbacks above: .. code-block:: ruby $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); $rules = array($index, $upload); $http->dispatch($rules); Start REST api server: .. code-block:: ruby $http->start(); Make an HTTP request -------------------- diff --git a/examples/http_rest_server.php b/examples/http_rest_server.php index de1aa63..caa5296 100644 --- a/examples/http_rest_server.php +++ b/examples/http_rest_server.php @@ -1,121 +1,121 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // print usage notice and parse addr/port parameters if passed _colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE); $port = ($argc == 2 ? $argv[1] : 9699); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer($port); // callback method for dispatch rule (see below) function index($request) { $request->send_response( 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } // callback method for dispatch rule (see below) function upload($request) { if ($request->method == 'GET') { $request->ok(array( 'Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' ); - } else if ($request->method == 'POST') { + } elseif ($request->method == 'POST') { if ($request->body === null && $request->expect) { $request->recv_body(); } else { // got upload body, save it _info("file upload complete, got ".strlen($request->body)." bytes of data"); $upload_data = $request->multipart->form_data[0]['body']; $request->ok($upload_data, array('Content-Type' => $request->multipart->form_data[0]['headers']['Content-Type'])); } } } // add dispatch rules with callback method as first argument $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); // some REST CRUD style callback methods // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules function create_event($request) { _info("got event create request"); $request->close(); } function read_event($request, $pk) { _info("got event read request for $pk"); $request->close(); } function update_event($request, $pk) { _info("got event update request for $pk"); $request->close(); } function delete_event($request, $pk) { _info("got event delete request for $pk"); $request->close(); } $event_create = array('create_event', '^/event/create/$', array('PUT')); $event_read = array('read_event', '^/event/(?P<pk>\d+)/$', array('GET', 'HEAD')); $event_update = array('update_event', '^/event/(?P<pk>\d+)/$', array('POST')); $event_delete = array('delete_event', '^/event/(?P<pk>\d+)/$', array('DELETE')); // prepare rule set $rules = array($index, $upload, $event_create, $event_read, $event_update, $event_delete); $http->dispatch($rules); // start http server $http->start(); diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index 2cebe70..eda4d2d 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,139 +1,139 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 5) { echo "Usage: $argv[0] host jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[2], 'pass' => $argv[3], 'host' => $argv[1], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC '0203', // Delayed Delivery '0199' // XMPP Ping )); // // add necessary event callbacks here // $_room_full_jid = $argv[4]."/".$argv[5]; $room_full_jid = new XMPPJid($_room_full_jid); $client->add_cb('on_auth_success', function() { global $client, $room_full_jid; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // join muc room $client->xeps['0045']->join_room($room_full_jid); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_groupchat_message', function($stanza) { global $client; $from = new XMPPJid($stanza->from); $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); if ($from->resource) { echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } else { $subject = $stanza->exists('subject'); if ($subject) { echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } } }); $client->add_cb('on_presence_stanza', function($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { if (($status = $x->exists('status', null, array('code' => '110'))) !== false) { $item = $x->exists('item'); _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); } else { _info("xmlns #user have no x child element"); } } else { _warning("=======> odd case 1"); } } // stanza from other users received - else if (strtolower($from->bare) == strtolower($room_full_jid->bare)) { + elseif (strtolower($from->bare) == strtolower($room_full_jid->bare)) { if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; } else { _warning("=======> odd case 2"); } } else { _warning("=======> odd case 3"); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/register_user.php b/examples/register_user.php index a035f63..1884da3 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,166 +1,166 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // $form = array(); function wait_for_register_response($event, $args) { global $client, $form; if ($event == 'stanza_cb') { $stanza = $args[0]; if ($stanza->name == 'iq') { $form['type'] = $stanza->attrs['type']; if ($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; - } else if ($stanza->attrs['type'] == 'error') { + } elseif ($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } } } else { _notice("unhandled event $event rcvd"); } } function wait_for_register_form($event, $args) { global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if ($query) { $instructions = $query->exists('instructions'); if ($instructions) { echo $instructions->text.PHP_EOL; } foreach ($query->childrens as $k => $child) { if ($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // $client->add_cb('on_stream_features', function($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; }); $client->add_cb('on_disconnect', function() { global $form; _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); }); // // finally start configured xmpp stream // $client->start(); // // if registration was successful // try to connect with newly registered account // if ($form['type'] == 'result') { _info("connecting newly registered user account"); $client = new JAXL(array( 'jid' => $form['username'].'@'.$argv[1], 'pass' => $form['password'], 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', function() { global $client; $client->set_status('Available'); }); $client->start(); } echo "done\n"; diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php index 8a4f88f..6f469cd 100644 --- a/http/http_dispatcher.php +++ b/http/http_dispatcher.php @@ -1,124 +1,124 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // // (optionally) set an array of url dispatch rules // each dispatch rule is defined by an array of size 4 like: // array($callback, $pattern, $methods, $extra), where // $callback the method which will be called if this rule matches // $pattern regular expression to match request path // $methods list of allowed methods for this rule // pass boolean true to allow all http methods // if omitted or an empty array() is passed (which actually doesnt make sense) // by default 'GET' will be the method allowed on this rule // $extra reserved for future (you can totally omit this as of now) // class HTTPDispatchRule { // match callback public $cb = null; // regexp to match on request path public $pattern = null; // methods to match upon // add atleast 1 method for this rule to work public $methods = null; // other matching rules public $extra = array(); public function __construct($cb, $pattern, $methods = array('GET'), $extra = array()) { $this->cb = $cb; $this->pattern = $pattern; $this->methods = $methods; $this->extra = $extra; } public function match($path, $method) { if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) { if (in_array($method, $this->methods)) { return $matches; } } return false; } } class HTTPDispatcher { protected $rules = array(); public function __construct() { $this->rules = array(); } public function add_rule($rule) { $s = sizeof($rule); if ($s > 4) { _debug("invalid rule"); return; } // fill up defaults if ($s == 3) { $rule[] = array(); - } else if ($s == 2) { $rule[] = array('GET'); $rule[] = array(); + } elseif ($s == 2) { $rule[] = array('GET'); $rule[] = array(); } else { _debug("invalid rule"); return; } $this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]); } public function dispatch($request) { foreach ($this->rules as $rule) { //_debug("matching $request->path with pattern $rule->pattern"); if (($matches = $rule->match($request->path, $request->method)) !== false) { _debug("matching rule found, dispatching"); $params = array($request); // TODO: a bad way to restrict on 'pk', fix me for generalization if (@isset($matches['pk'])) $params[] = $matches['pk']; call_user_func_array($rule->cb, $params); return true; } } return false; } } diff --git a/http/http_multipart.php b/http/http_multipart.php index 6f3daf4..c76638f 100644 --- a/http/http_multipart.php +++ b/http/http_multipart.php @@ -1,171 +1,171 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; class HTTPMultiPart extends JAXLFsm { public $boundary = null; public $form_data = array(); public $index = -1; public function handle_invalid_state($r) { _error("got invalid event $r"); } public function __construct($boundary) { $this->boundary = $boundary; parent::__construct('wait_for_boundary_start'); } public function state() { return $this->state; } public function wait_for_boundary_start($event, $data) { if ($event == 'process') { if ($data[0] == '--'.$this->boundary) { $this->index += 1; $this->form_data[$this->index] = array( 'meta' => array(), 'headers' => array(), 'body' => '' ); return array('wait_for_content_disposition', true); } else { _warning("invalid boundary start $data[0] while expecting $this->boundary"); return array('wait_for_boundary_start', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_boundary_start', false); } } public function wait_for_content_disposition($event, $data) { if ($event == 'process') { $disposition = explode(":", $data[0]); if (strtolower(trim($disposition[0])) == 'content-disposition') { $this->form_data[$this->index]['headers'][$disposition[0]] = trim($disposition[1]); $meta = explode(";", $disposition[1]); if (trim(array_shift($meta)) == 'form-data') { foreach ($meta as $k) { list($k, $v) = explode("=", $k); $this->form_data[$this->index]['meta'][$k] = $v; } return array('wait_for_content_type', true); } else { _warning("first part of meta is not form-data"); return array('wait_for_content_disposition', false); } } else { _warning("not a valid content-disposition line"); return array('wait_for_content_disposition', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_disposition', false); } } public function wait_for_content_type($event, $data) { if ($event == 'process') { $type = explode(":", $data[0]); if (strtolower(trim($type[0])) == 'content-type') { $this->form_data[$this->index]['headers'][$type[0]] = trim($type[1]); $this->form_data[$this->index]['meta']['type'] = $type[1]; return array('wait_for_content_body', true); } else { _debug("not a valid content-type line"); return array('wait_for_content_type', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_type', false); } } public function wait_for_content_body($event, $data) { if ($event == 'process') { if ($data[0] == '--'.$this->boundary) { _debug("start of new multipart/form-data detected"); return array('wait_for_content_disposition', true); - } else if ($data[0] == '--'.$this->boundary.'--') { + } elseif ($data[0] == '--'.$this->boundary.'--') { _debug("end of multipart form data detected"); return array('wait_for_empty_line', true); } else { $this->form_data[$this->index]['body'] .= $data[0]; return array('wait_for_content_body', true); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_body', false); } } public function wait_for_empty_line($event, $data) { if ($event == 'process') { if ($data[0] == '') { return array('done', true); } else { _warning("invalid empty line $data[0] received"); return array('wait_for_empty_line', false); } } else { _warning("got $event in done state with data $data[0]"); return array('wait_for_empty_line', false); } } public function done($event, $data) { _warning("got unhandled event $event with data $data[0]"); return array('done', false); } } diff --git a/http/http_request.php b/http/http_request.php index d3b0808..bfc72c2 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,503 +1,503 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers = array(), $body = null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if (sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation // public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; if ($this->body === null) $this->body = $rcvd; else $this->body .= $rcvd; if ($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach ($form_data as $data) { //_debug("passing $data to multipart fsm"); if (!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if (!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if (!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { switch($event) { case 'empty_line': return 'headers_received'; break; default: if (substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if (method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } - } else if (@isset($this->shortcuts[$event])) { + } elseif (@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { $k = trim($k); $v = ltrim($v); // is expect header? if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if (strtolower($k) == 'content-type') { $ctype = explode(';', $v); if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if (strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if ($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { if (sizeof($args) == 0) { $body = null; $headers = array(); } if (sizeof($args) == 1) { // http headers or body only received if (is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } - } else if (sizeof($args) == 2) { + } elseif (sizeof($args) == 2) { // body and http headers both received if (is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { foreach ($headers as $k => $v) $this->_send_header($k, $v); } protected function _send_body($body) { $this->_send($body); } protected function _send_response($code, $headers = array(), $body = null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set if ($body && !isset($headers['Content-Length'])) $headers['Content-Length'] = strlen($body); // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); if ($body) $this->_send_body(HTTP_CRLF.$body); } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if (sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach ($query as $q) { $q = explode("=", $q); if (sizeof($q) == 1) $q[1] = ""; $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } } diff --git a/http/http_server.php b/http/http_server.php index 7e5f731..f74b574 100644 --- a/http/http_server.php +++ b/http/http_server.php @@ -1,199 +1,199 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/http/http_dispatcher.php'; require_once JAXL_CWD.'/http/http_request.php'; // carriage return and line feed define('HTTP_CRLF', "\r\n"); // 1xx informational define('HTTP_100', "Continue"); define('HTTP_101', "Switching Protocols"); // 2xx success define('HTTP_200', "OK"); // 3xx redirection define('HTTP_301', 'Moved Permanently'); define('HTTP_304', 'Not Modified'); // 4xx client error define('HTTP_400', 'Bad Request'); define('HTTP_403', 'Forbidden'); define('HTTP_404', 'Not Found'); define('HTTP_405', 'Method Not Allowed'); define('HTTP_499', 'Client Closed Request'); // Nginx // 5xx server error define('HTTP_500', 'Internal Server Error'); define('HTTP_503', 'Service Unavailable'); class HTTPServer { private $server = null; public $cb = null; private $dispatcher = null; private $requests = array(); public function __construct($port = 9699, $address = "127.0.0.1") { $path = 'tcp://'.$address.':'.$port; $this->server = new JAXLSocketServer( $path, array(&$this, 'on_accept'), array(&$this, 'on_request') ); $this->dispatcher = new HTTPDispatcher(); } public function __destruct() { $this->server = null; } public function dispatch($rules) { foreach ($rules as $rule) { $this->dispatcher->add_rule($rule); } } public function start($cb = null) { $this->cb = $cb; JAXLLoop::run(); } public function on_accept($sock, $addr) { _debug("on_accept for client#$sock, addr:$addr"); // initialize new request obj $request = new HTTPRequest($sock, $addr); // setup sock cb $request->set_sock_cb( array(&$this->server, 'send'), array(&$this->server, 'read'), array(&$this->server, 'close') ); // cache request object $this->requests[$sock] = &$request; // reactive client for further read $this->server->read($sock); } public function on_request($sock, $raw) { _debug("on_request for client#$sock"); $request = $this->requests[$sock]; // 'wait_for_body' state is reached when ever // application calls recv_body() method // on received $request object if ($request->state() == 'wait_for_body') { $request->body($raw); } else { // break on crlf $lines = explode(HTTP_CRLF, $raw); // parse request line if ($request->state() == 'wait_for_request_line') { list($method, $resource, $version) = explode(" ", $lines[0]); $request->line($method, $resource, $version); unset($lines[0]); _info($request->ip." ".$request->method." ".$request->resource." ".$request->version); } // parse headers foreach ($lines as $line) { $line_parts = explode(":", $line); if (sizeof($line_parts) > 1) { if (strlen($line_parts[0]) > 0) { $k = $line_parts[0]; unset($line_parts[0]); $v = implode(":", $line_parts); $request->set_header($k, $v); } - } else if (strlen(trim($line_parts[0])) == 0) { + } elseif (strlen(trim($line_parts[0])) == 0) { $request->empty_line(); } // if exploded line array size is 1 // and thr is something in $line_parts[0] // must be request body else { $request->body($line); } } } // if request has reached 'headers_received' state? if ($request->state() == 'headers_received') { // dispatch to any matching rule found _debug("delegating to dispatcher for further routing"); $dispatched = $this->dispatcher->dispatch($request); // if no dispatch rule matched call generic callback if (!$dispatched && $this->cb) { _debug("no dispatch rule matched, sending to generic callback"); call_user_func($this->cb, $request); } - // else if not dispatched and not generic callbacked + // elseif not dispatched and not generic callbacked // send 404 not_found - else if (!$dispatched) { + elseif (!$dispatched) { // TODO: send 404 if no callback is registered for this request _debug("dropping request since no matching dispatch rule or generic callback was specified"); $request->not_found('404 Not Found'); } } // if state is not 'headers_received' // reactivate client socket for read event else { $this->server->read($sock); } } } diff --git a/jaxl.php b/jaxl.php index ff1a00c..c6ad713 100644 --- a/jaxl.php +++ b/jaxl.php @@ -169,669 +169,669 @@ class JAXL extends XMPPStream _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if (!is_array($xeps)) $xeps = array($xeps); foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri = 1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show = 'chat', $priority = 10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type' => 'chat', 'to' => $to, 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid = null, $cb = null) { $attrs = array( 'type' => 'get', 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb = null) { $pkt = $this->get_iq_pkt( array( 'type' => 'get', 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts = array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) $this->enable_debug_shell(); if (@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if ($mechanisms) foreach ($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if ($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach ($mechs as $mech => $any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if ($mech == 'X-FACEBOOK-PLATFORM') { if (@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if ($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; - } else if ($pref_auth == 'CRAM-MD5') { + } elseif ($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; - } else if ($pref_auth == 'SCRAM-SHA-1') { + } elseif ($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if (!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach ($query->childrens as $child) { if ($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach ($child->childrens as $group) { if ($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if (!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if (@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if (!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if ($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if ($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; - } else if ($type == 'unavailable') { + } elseif ($type == 'unavailable') { if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if ($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if ($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach ($query->childrens as $k => $child) { if ($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; - } else if ($child->name == 'x') { + } elseif ($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; - } else if ($child->name == 'feature') { + } elseif ($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach ($query->childrens as $k => $child) { if ($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } diff --git a/jaxlctl b/jaxlctl index 36fd3cc..ceb4398 100755 --- a/jaxlctl +++ b/jaxlctl @@ -1,197 +1,197 @@ #!/usr/bin/env php <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ $params = $argv; $exe = array_shift($params); $command = array_shift($params); require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // TODO: an abstract JAXLCtlCommand class // with seperate class per command // a mechanism to register new commands class JAXLCtl { protected $ipc = null; protected $buffer = ''; protected $buffer_cb = null; protected $cli = null; public $dots = "....... "; protected $symbols = array(); public function __construct($command, $params) { global $exe; if (method_exists($this, $command)) { $r = call_user_func_array(array(&$this, $command), $params); if (sizeof($r) == 2) { list($buffer_cb, $quit_cb) = $r; $this->buffer_cb = $buffer_cb; $this->cli = new JAXLCli(array(&$this, 'on_terminal_input'), $quit_cb); $this->run(); } else { _colorize("oops! internal command error", JAXL_ERROR); exit; } } else { _colorize("error: invalid command '$command' received", JAXL_ERROR); _colorize("type '$exe help' for list of available commands", JAXL_NOTICE); exit; } } public function run() { JAXLCli::prompt(); JAXLLoop::run(); } public function on_terminal_input($raw) { $raw = trim($raw); $last = substr($raw, -1, 1); if ($last == ";") { // dispatch to buffer callback call_user_func($this->buffer_cb, $this->buffer.$raw); $this->buffer = ''; - } else if ($last == '\\') { + } elseif ($last == '\\') { $this->buffer .= substr($raw, 0, -1); echo $this->dots; } else { // buffer command $this->buffer .= $raw."; "; echo $this->dots; } } public static function print_help() { global $exe; _colorize("Usage: $exe command [options...]\n", JAXL_INFO); _colorize("Commands:", JAXL_NOTICE); _colorize(" help This help text", JAXL_DEBUG); _colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG); _colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG); echo "\n"; } protected function help() { JAXLCtl::print_help(); exit; } // // shell command // protected function shell() { return array(array(&$this, 'on_shell_input'), array(&$this, 'on_shell_quit')); } private function _eval($raw, $symbols) { extract($symbols); eval($raw); $g = get_defined_vars(); unset($g['raw']); unset($g['symbols']); return $g; } public function on_shell_input($raw) { $this->symbols = $this->_eval($raw, $this->symbols); JAXLCli::prompt(); } public function on_shell_quit() { exit; } // // debug command // protected function debug($sock_path) { $this->ipc = new JAXLSocketClient(); $this->ipc->set_callback(array(&$this, 'on_debug_response')); $this->ipc->connect('unix://'.$sock_path); return array(array(&$this, 'on_debug_input'), array(&$this, 'on_debug_quit')); } public function on_debug_response($raw) { $ret = unserialize($raw); print_r($ret); echo "\n"; JAXLCli::prompt(); } public function on_debug_input($raw) { $this->ipc->send($this->buffer.$raw); } public function on_debug_quit() { $this->ipc->disconnect(); exit; } } // we atleast need a command argument if ($argc < 2) { JAXLCtl::print_help(); exit; } $ctl = new JAXLCtl($command, $params); echo "done\n"; diff --git a/xep/xep_0206.php b/xep/xep_0206.php index 61e73fc..62a85c2 100644 --- a/xep/xep_0206.php +++ b/xep/xep_0206.php @@ -1,239 +1,239 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind'); define('NS_BOSH', 'urn:xmpp:xbosh'); class XEP_0206 extends XMPPXep { private $mch = null; public $chs = array(); private $recv_cb = null; public $rid = null; public $sid = null; private $hold = 1; private $wait = 30; private $restarted = false; public $headers = array( 'Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8' ); // // abstract method // public function init() { $this->mch = curl_multi_init(); return array( ); } // // event callbacks // public function send($body) { if (is_object($body)) { $body = $body->to_string(); } else { if (substr($body, 0, 15) == '<stream:stream ') { $this->restarted = true; $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'xmpp:restart' => 'true', 'xmlns:xmpp' => NS_BOSH )); $body = $body->to_string(); - } else if (substr($body, 0, 16) == '</stream:stream>') { + } elseif (substr($body, 0, 16) == '</stream:stream>') { $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'type' => 'terminate' )); $body = $body->to_string(); } else { $body = $this->wrap($body); } } _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body); $this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']); curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers); curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false); curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1); curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body); curl_multi_add_handle($this->mch, $this->chs[$this->rid]); } public function recv() { if ($this->restarted) { $this->restarted = false; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); } _debug("recving for $this->rid"); do { $ret = curl_multi_exec($this->mch, $running); $changed = curl_multi_select($this->mch, 0.1); if ($changed == 0 && $running == 0) { $ch = @$this->chs[$this->rid]; if ($ch) { $data = curl_multi_getcontent($ch); curl_multi_remove_handle($this->mch, $ch); unset($this->chs[$this->rid]); _debug("recvd for $this->rid ".$data); list($body, $stanza) = $this->unwrap($data); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if (@$attrs['type'] == 'terminate') { // fool me again if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); } else { if (!$this->sid) { $this->sid = $attrs['sid']; } if ($this->recv_cb) call_user_func($this->recv_cb, $stanza); } } else { _error("no ch found"); exit; } } } while ($running); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function wrap($stanza) { return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>'; } public function unwrap($body) { // a dirty way but it works efficiently if (substr($body, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); if (isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; else $envelop = "<body/>"; if (isset($m[2][0])) $payload = $m[2][0]; else $payload = ''; return array($envelop, $payload); } public function session_start() { $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000); $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold; $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); $attrs = array( 'content' => 'text/xml; charset=utf-8', 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'], 'secure' => 'true', 'xml:lang' => 'en', 'xmpp:version' => '1.0', 'xmlns:xmpp' => NS_BOSH, 'hold' => $this->hold, 'wait' => $this->wait, 'rid' => $this->rid, 'ver' => '1.10' ); if (@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; $body = new JAXLXml('body', NS_HTTP_BIND, $attrs); $this->send($body); } public function ping() { $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid)); $this->send($body); } public function session_end() { $this->disconnect(); } public function disconnect() { _debug("disconnecting"); } } diff --git a/xmpp/xmpp_jid.php b/xmpp/xmpp_jid.php index 5b1b89d..b0d3d82 100644 --- a/xmpp/xmpp_jid.php +++ b/xmpp/xmpp_jid.php @@ -1,81 +1,81 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Xmpp Jid * * @author abhinavsingh * */ class XMPPJid { public $node = null; public $domain = null; public $resource = null; public $bare = null; public function __construct($str) { $tmp = explode("@", $str); if (sizeof($tmp) == 2) { $this->node = $tmp[0]; $tmp = explode("/", $tmp[1]); if (sizeof($tmp) == 2) { $this->domain = $tmp[0]; $this->resource = $tmp[1]; } else { $this->domain = $tmp[0]; } - } else if (sizeof($tmp) == 1) { + } elseif (sizeof($tmp) == 1) { $this->domain = $tmp[0]; } $this->bare = $this->node ? $this->node."@".$this->domain : $this->domain; } public function to_string() { $str = ""; if ($this->node) $str .= $this->node.'@'.$this->domain; - else if ($this->domain) $str .= $this->domain; + elseif ($this->domain) $str .= $this->domain; if ($this->resource) $str .= '/'.$this->resource; return $str; } } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index d2a2ec3..efab4cf 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,700 +1,700 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass = null, $resource = null, $force_tls = false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if (isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; if (isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if (strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if (!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc' => $nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if (isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if (!$msg->id) $msg->id = $this->get_id(); if ($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if (!$pres->id) $pres->id = $this->get_id(); if ($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if (!$iq->id) $iq->id = $this->get_id(); if ($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); - } else if (strpos(strrev(trim($pair)), '"') === 0 && $key) { + } elseif (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach ($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach (array('realm', 'cnonce', 'digest-uri') as $key) if (!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if (isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters - else if ($comp) { + elseif ($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; - } else if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { + } elseif ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; - } else if ($stanza->name == 'success' && $stanza->ns == NS_SASL) { + } elseif ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if ($stanza->name == 'message') { $this->handle_message($stanza); - } else if ($stanza->name == 'presence') { + } elseif ($stanza->name == 'presence') { $this->handle_presence($stanza); - } else if ($stanza->name == 'iq') { + } elseif ($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } }
jaxl/JAXL
6a8caf05d7ace4fda277c63594c159e08b1bdbe2
Fix PSR: TRUE, FALSE and NULL must be lowercase
diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index 6a45cba..c0de786 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,225 +1,225 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; public function __construct($stream_context = null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ public function connect($socket_path) { if (gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); if (sizeof($path_parts) == 3) $this->port = $path_parts[2]; _info("trying ".$socket_path); if ($this->stream_context) $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); else $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); } else { $this->fd = &$socket_path; } if ($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); $this->disconnect(); return false; } } public function disconnect() { JAXLLoop::unwatch($this->fd, array( 'read' => true, 'write' => true )); @fclose($this->fd); $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); return $ret; } public function send($data) { $this->obuffer .= $data; // add watch for write events if ($this->writing) return; JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if ($bytes === 0) { $meta = stream_get_meta_data($fd); - if ($meta['eof'] === TRUE) { + if ($meta['eof'] === true) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); if ($bytes > 0) _debug($raw); // callback if ($this->recv_cb) call_user_func($this->recv_cb, $raw); } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if (strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } } diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index f1a4263..36063b5 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,263 +1,263 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLSocketServer { public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; public function __construct($path, $accept_cb, $request_cb) { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; $ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog))); if (($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { if (@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); } else { _error("unable to set non block flag"); } } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } public function __destruct() { _info("shutting down socket server"); } public function read($client_id) { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } public function send($client_id, $data) { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } public function close($client_id) { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } public function on_server_accept_ready($server) { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); if (!$client) { _error("unable to accept new client conn"); return; } if (@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do if ($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); } // if no accept callback is registered // close the accepted connection else { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } } else { _error("unable to set non block flag"); } } public function on_client_read_ready($client) { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); if ($bytes === 0) { $meta = stream_get_meta_data($client); - if ($meta['eof'] === TRUE) { + if ($meta['eof'] === true) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); @fclose($client); unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; if ($this->request_cb) call_user_func($this->request_cb, $client_id, $total); $this->clients[$client_id]['ibuffer'] = ''; } public function on_client_write_ready($client) { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); if ($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; } else if ($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler if (strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } } catch(JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // protected function add_read_cb($client_id) { if ($this->clients[$client_id]['reading']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } protected function add_write_cb($client_id) { if ($this->clients[$client_id]['writing']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } protected function del_read_cb($client_id) { if (!$this->clients[$client_id]['reading']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } protected function del_write_cb($client_id) { if (!$this->clients[$client_id]['writing']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } } diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index 6c8f186..f11059f 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,204 +1,204 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if (is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if (is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if (is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; foreach ($attrs as $k => $v) { if ($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } - public function t($text, $append = FALSE) + public function t($text, $append = false) { if (!$append) { $this->rover->text = $text; } else { if ($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; } return $this; } public function c($name, $ns = null, $attrs = array(), $text = null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { if ($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } public function top() { $this->rover = &$this; return $this; } public function exists($name, $ns = null, $attrs = array()) { foreach ($this->childrens as $child) { if ($ns) { if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; } else if ($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } public function update($name, $ns = null, $attrs = array(), $text = null) { foreach ($this->childrens as $k => $child) { if ($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } public function to_string($parent_ns = null) { $xml = ''; $xml .= '<'.$this->name; if ($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; - foreach ($this->attrs as $k => $v) if (!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; + foreach ($this->attrs as $k => $v) if (!is_null($v) && $v !== false) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; foreach ($this->childrens as $child) $xml .= $child->to_string($this->ns); if ($this->text) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } } diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php index 1d7c1b7..d24fd03 100644 --- a/core/jaxl_xml_stream.php +++ b/core/jaxl_xml_stream.php @@ -1,197 +1,197 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Enter description here ... * @author abhinavsingh * */ class JAXLXmlStream { private $delimiter = '\\'; private $ns; private $parser; private $stanza; private $depth = -1; private $start_cb; private $stanza_cb; private $end_cb; public function __construct() { $this->init_parser(); } private function init_parser() { $this->depth = -1; $this->parser = xml_parser_create_ns("UTF-8", $this->delimiter); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); xml_set_character_data_handler($this->parser, array(&$this, "handle_character")); xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag")); } public function __destruct() { //_debug("cleaning up xml parser..."); @xml_parser_free($this->parser); } public function reset_parser() { $this->parse_final(null); @xml_parser_free($this->parser); $this->parser = null; $this->init_parser(); } public function set_callback($start_cb, $end_cb, $stanza_cb) { $this->start_cb = $start_cb; $this->end_cb = $end_cb; $this->stanza_cb = $stanza_cb; } public function parse($str) { xml_parse($this->parser, $str, false); } public function parse_final($str) { xml_parse($this->parser, $str, true); } protected function handle_start_tag($parser, $name, $attrs) { $name = $this->explode($name); //echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL; // replace ns with prefix foreach ($attrs as $key => $v) { $k = $this->explode($key); // no ns specified if ($k[0] == null) { $attrs[$k[1]] = $v; } // xml ns else if ($k[0] == NS_XML) { unset($attrs[$key]); $attrs['xml:'.$k[1]] = $v; } else { _error("==================> unhandled ns prefix on attribute"); // remove attribute else will cause error with bad stanza format // report to developer if above error message is ever encountered unset($attrs[$key]); } } if ($this->depth <= 0) { $this->depth = 0; $this->ns = $name[1]; if ($this->start_cb) { $stanza = new JAXLXml($name[1], $name[0], $attrs); call_user_func($this->start_cb, $stanza); } } else { if (!$this->stanza) { $stanza = new JAXLXml($name[1], $name[0], $attrs); $this->stanza = &$stanza; } else { $this->stanza->c($name[1], $name[0], $attrs); } } ++$this->depth; } protected function handle_end_tag($parser, $name) { $name = explode($this->delimiter, $name); $name = sizeof($name) == 1 ? array('', $name[0]) : $name; //echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL; if ($this->depth == 1) { if ($this->end_cb) { $stanza = new JAXLXml($name[1], $this->ns); call_user_func($this->end_cb, $stanza); } } else if ($this->depth > 1) { if ($this->stanza) $this->stanza->up(); if ($this->depth == 2) { if ($this->stanza_cb) { call_user_func($this->stanza_cb, $this->stanza); $this->stanza = null; } } } --$this->depth; } protected function handle_character($parser, $data) { //echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL; if ($this->stanza) { - $this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), TRUE); + $this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), true); } } private function implode($data) { return implode($this->delimiter, $data); } private function explode($data) { $data = explode($this->delimiter, $data); $data = sizeof($data) == 1 ? array(null, $data[0]) : $data; return $data; } } diff --git a/docs/users/xml_objects.rst b/docs/users/xml_objects.rst index a11a049..9323f10 100644 --- a/docs/users/xml_objects.rst +++ b/docs/users/xml_objects.rst @@ -1,121 +1,121 @@ .. _xml-objects: Xml Objects =========== Jaxl library works with custom XML implementation which is similar to inbuild PHP XML functions but is lightweight and easy to work with. JAXLXml ------- ``JAXLXml`` is the base XML object. Open up :ref:`Jaxl interactive shell <jaxl-instance>` and try some xml object creation/manipulation: >>> ./jaxlctl shell jaxl 1> jaxl 1> $xml = new JAXLXml( ....... 'dummy', ....... 'dummy:packet', ....... array('attr1' => '[email protected]', 'attr2' => ''), ....... 'Hello World!' ....... ); jaxl 2> echo $xml->to_string(); <dummy xmlns="dummy:packet" attr1="[email protected]" attr2="">Hello World!</dummy> jaxl 3> ``JAXLXml`` constructor instance accepts following parameters: * ``JAXLXml($name, $ns, $attrs, $text)`` * ``JAXLXml($name, $ns, $attrs)`` * ``JAXLXml($name, $ns, $text)`` * ``JAXLXml($name, $attrs, $text)`` * ``JAXLXml($name, $attrs)`` * ``JAXLXml($name, $ns)`` * ``JAXLXml($name)`` ``JAXLXml`` draws inspiration from StropheJS XML Builder class. Below are available methods for modifying and manipulating an ``JAXLXml`` object: - * ``t($text, $append = FALSE)`` + * ``t($text, $append = false)`` update text of current rover * ``c($name, $ns = null, $attrs = array(), $text = null)`` append a child node at current rover * ``cnode($node)`` append a JAXLXml child node at current rover * ``up()`` move rover to one step up the xml tree * ``top()`` move rover back to top element in the xml tree * ``exists($name, $ns = null, $attrs = array())`` checks if a child with $name exists, return child ``JAXLXml`` if found otherwise false. This function returns at first matching child. * ``update($name, $ns = null, $attrs = array(), $text = null)`` update specified child element * ``attrs($attrs)`` merge new attrs with attributes of current rover * ``match_attrs($attrs)`` pass a kv pair of ``$attrs``, return bool if all passed keys matches their respective values in the xml packet * ``to_string()`` get string representation of the object ``JAXLXml`` maintains a rover which points to the current level down the XML tree where manipulation is performed. XMPPStanza ---------- In the world of XMPP where everything incoming and outgoing payload is an ``JAXLXml`` instance code can become nasty, developers can get lost in dirty XML manipulations spreaded all over the application code base and what not. XML structures are not only unreadable for humans but even for machine. While an instance of ``JAXLXml`` provide direct access to XML ``name``, ``ns`` and ``text``, it can become painful and time consuming when trying to retrieve or modify a particular ``attrs`` or ``childrens``. I was fed up of doing ``getAttributeByName``, ``setAttributeByName``, ``getChild`` etc everytime i had to access common XMPP Stanza attributes. ``XMPPStanza`` is a wrapper on top of ``JAXLXml`` objects. Preserving all the functionalities of base ``JAXLXml`` instance it also provide direct access to most common XMPP Stanza attributes like ``to``, ``from``, ``id``, ``type`` etc. It also provides a framework for adding custom access patterns. ``XMPPMsg``, ``XMPPPres`` and ``XMPPIq`` extends ``XMPPStanza`` and also add a few custom access patterns like ``body``, ``thread``, ``subject``, ``status``, ``show`` etc. Here is a list of default access patterns: #. ``name`` #. ``ns`` #. ``text`` #. ``attrs`` #. ``childrens`` #. ``to`` #. ``from`` #. ``id`` #. ``type`` #. ``to_node`` #. ``to_domain`` #. ``to_resource`` #. ``from_node`` #. ``from_domain`` #. ``from_resource`` #. ``status`` #. ``show`` #. ``priority`` #. ``body`` #. ``thread`` #. ``subject`` diff --git a/examples/echo_unix_sock_server.php b/examples/echo_unix_sock_server.php index 69e5908..9763e50 100644 --- a/examples/echo_unix_sock_server.php +++ b/examples/echo_unix_sock_server.php @@ -1,60 +1,60 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 2) { echo "Usage: $argv[0] /path/to/server.sock\n"; exit; } require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; $server = null; function on_request($client, $raw) { global $server; $server->send($client, $raw); _info("got client callback ".$raw); } @unlink($argv[1]); -$server = new JAXLSocketServer('unix://'.$argv[1], NULL, 'on_request'); +$server = new JAXLSocketServer('unix://'.$argv[1], null, 'on_request'); JAXLLoop::run(); echo "done\n"; diff --git a/examples/multi_client.php b/examples/multi_client.php index 8bc4057..bb73015 100644 --- a/examples/multi_client.php +++ b/examples/multi_client.php @@ -1,132 +1,132 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // enable multi client support // this will force 1st parameter of callbacks // as connected client instance define('JAXL_MULTI_CLIENT', true); // input multiple account credentials $accounts = array(); -$add_new = TRUE; +$add_new = true; while ($add_new) { $jid = readline('Enter Jabber Id: '); $pass = readline('Enter Password: '); $accounts[] = array($jid, $pass); $next = readline('Add another account (y/n): '); - $add_new = $next == 'y' ? TRUE : FALSE; + $add_new = $next == 'y' ? true : false; } // setup jaxl require_once 'jaxl.php'; // // common callbacks // function on_auth_success($client) { _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // fetch roster list $client->get_roster(); // fetch vcard $client->get_vcard(); // set status $client->set_status("available!", "dnd", 10); } function on_auth_failure($client, $reason) { _info("got on_auth_failure cb with reason $reason"); $client->send_end_stream(); } function on_chat_message($client, $stanza) { // echo back incoming chat message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); } function on_presence_stanza($client, $stanza) { global $client; $type = ($stanza->type ? $stanza->type : "available"); $show = ($stanza->show ? $stanza->show : "???"); _info($stanza->from." is now ".$type." ($show)"); if ($type == "available") { // fetch vcard $client->get_vcard($stanza->from); } } function on_disconnect($client) { _info("got on_disconnect cb"); } // // bootstrap all account instances // foreach ($accounts as $account) { $client = new JAXL(array( 'jid' => $account[0], 'pass' => $account[1], 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', 'on_auth_success'); $client->add_cb('on_auth_failure', 'on_auth_failure'); $client->add_cb('on_chat_message', 'on_chat_message'); $client->add_cb('on_presence_stanza', 'on_presence_stanza'); $client->add_cb('on_disconnect', 'on_disconnect'); $client->connect($client->get_socket_path()); $client->start_stream(); } // start core loop JAXLLoop::run(); echo "done\n"; diff --git a/jaxl.php b/jaxl.php index bdfa365..ff1a00c 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,648 +1,648 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger if (isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if (isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // env - $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; + $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : true; if ($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if (!is_dir($this->priv_dir)) mkdir($this->priv_dir); if (!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if (!is_dir($this->pid_dir)) mkdir($this->pid_dir); if (!is_dir($this->log_dir)) mkdir($this->log_dir); if (!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if (!is_array($xeps)) $xeps = array($xeps); foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri = 1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show = 'chat', $priority = 10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type' => 'chat', 'to' => $to, 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid = null, $cb = null) { $attrs = array( 'type' => 'get', 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb = null) { $pkt = $this->get_iq_pkt( array( 'type' => 'get', 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts = array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) $this->enable_debug_shell(); if (@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array();
jaxl/JAXL
762e7c803ad9b6af95a0fd8eeeae9c6b567108a9
Fix PSR: Opening brace after the definition
diff --git a/core/jaxl_cli.php b/core/jaxl_cli.php index 3f539fb..3621b64 100644 --- a/core/jaxl_cli.php +++ b/core/jaxl_cli.php @@ -1,98 +1,99 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; -class JAXLCli { +class JAXLCli +{ public static $counter = 0; private $in = null; private $quit_cb = null; private $recv_cb = null; private $recv_chunk_size = 1024; public function __construct($recv_cb = null, $quit_cb = null) { $this->recv_cb = $recv_cb; $this->quit_cb = $quit_cb; // catch read event on stdin $this->in = fopen('php://stdin', 'r'); stream_set_blocking($this->in, false); JAXLLoop::watch($this->in, array( 'read' => array(&$this, 'on_read_ready') )); } public function __destruct() { @fclose($this->in); } public function stop() { JAXLLoop::unwatch($this->in, array( 'read' => true )); } public function on_read_ready($in) { $raw = @fread($in, $this->recv_chunk_size); if (ord($raw) == 10) { // enter key JAXLCli::prompt(false); return; } else if (trim($raw) == 'quit') { $this->stop(); $this->in = null; if ($this->quit_cb) call_user_func($this->quit_cb); return; } if ($this->recv_cb) call_user_func($this->recv_cb, $raw); } public static function prompt($inc = true) { if ($inc) ++self::$counter; echo "jaxl ".self::$counter."> "; } } diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php index d74af6c..324ad78 100644 --- a/core/jaxl_clock.php +++ b/core/jaxl_clock.php @@ -1,128 +1,129 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -class JAXLClock { +class JAXLClock +{ // current clock time in microseconds private $tick = 0; // current Unix timestamp with microseconds public $time = null; // scheduled jobs public $jobs = array(); public function __construct() { $this->time = microtime(true); } public function __destruct() { _info("shutting down clock server..."); } public function tick($by = null) { // update clock if ($by) { $this->tick += $by; $this->time += $by / pow(10,6); } else { $time = microtime(true); $by = $time - $this->time; $this->tick += $by * pow(10, 6); $this->time = $time; } // run scheduled jobs foreach ($this->jobs as $ref => $job) { if ($this->tick >= $job['scheduled_on'] + $job['after']) { //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".$job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); call_user_func($job['cb'], $job['args']); if (!$job['is_periodic']) { unset($this->jobs[$ref]); } else { $job['scheduled_on'] = $this->tick; $job['runs']++; $this->jobs[$ref] = $job; } } } } // calculate execution time of callback public function tc($callback, $args = null) { } // callback after $time microseconds public function call_fun_after($time, $callback, $args = null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => false, 'runs' => 0 ); return sizeof($this->jobs); } // callback periodically after $time microseconds public function call_fun_periodic($time, $callback, $args = null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => true, 'runs' => 0 ); return sizeof($this->jobs); } // cancel a previously scheduled callback public function cancel_fun_call($ref) { unset($this->jobs[$ref-1]); } } diff --git a/core/jaxl_event.php b/core/jaxl_event.php index 56c6898..d4356a4 100644 --- a/core/jaxl_event.php +++ b/core/jaxl_event.php @@ -1,124 +1,125 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * following kind of events are possible: * 1) hook i.e. if a callback for such an event is registered, calling function is responsible for the workflow from their on * 2) filter i.e. calling function will manipulate passed arguments and modified arguments will be passed to next chain of filter * * As a rule of thumb, only 1 hook can be registered for an event, while more than 1 filter is allowed for an event * hook and filter both cannot be applied on an event * * @author abhinavsingh * */ -class JAXLEvent { +class JAXLEvent +{ protected $common = array(); public $reg = array(); public function __construct($common) { $this->common = $common; } public function __destruct() { } // add callback on a event // returns a reference to be used while deleting callback // callback'd method must return TRUE to be persistent // if none returned or FALSE, callback will be removed automatically public function add($ev, $cb, $pri) { if (!isset($this->reg[$ev])) $this->reg[$ev] = array(); $ref = sizeof($this->reg[$ev]); $this->reg[$ev][] = array($pri, $cb); return $ev."-".$ref; } // emit event to notify registered callbacks // is a pqueue required here for performance enhancement // in case we have too many cbs on a specific event? public function emit($ev, $data = array()) { $data = array_merge($this->common, $data); $cbs = array(); if (!isset($this->reg[$ev])) return $data; foreach ($this->reg[$ev] as $cb) { if (!isset($cbs[$cb[0]])) $cbs[$cb[0]] = array(); $cbs[$cb[0]][] = $cb[1]; } foreach ($cbs as $pri => $cb) { foreach ($cb as $c) { $ret = call_user_func_array($c, $data); // this line is for fixing situation where callback function doesn't return an array type // in such cases next call of call_user_func_array will report error since $data is not an array type as expected // things will change in future, atleast put the callback inside a try/catch block // here we only check if there was a return, if yes we update $data with return value // this is bad design, need more thoughts, should work as of now if ($ret) $data = $ret; } } unset($cbs); return $data; } // remove previous registered callback public function del($ref) { $ref = explode("-", $ref); unset($this->reg[$ref[0]][$ref[1]]); } public function exists($ev) { $ret = isset($this->reg[$ev]); //_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists")); return $ret; } } diff --git a/core/jaxl_exception.php b/core/jaxl_exception.php index 276ad40..bc1b26d 100644 --- a/core/jaxl_exception.php +++ b/core/jaxl_exception.php @@ -1,95 +1,96 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ error_reporting(E_ALL | E_STRICT); /** * * @author abhinavsingh */ -class JAXLException extends Exception { +class JAXLException extends Exception +{ public function __construct($message = null, $code = null, $file = null, $line = null) { _notice("got jaxl exception construct with $message, $code, $file, $line"); if ($code === null) { parent::__construct($message); } else { parent::__construct($message, $code); } if ($file !== null) { $this->file = $file; } if ($line !== null) { $this->line = $line; } } public static function error_handler($errno, $error, $file, $line, $vars) { _debug("error handler called with $errno, $error, $file, $line"); if ($errno === 0 || ($errno & error_reporting()) === 0) { return; } throw new JAXLException($error, $errno, $file, $line); } public static function exception_handler($e) { _debug("exception handler catched ".json_encode($e)); // TODO: Pretty print backtrace //print_r(debug_backtrace()); } public static function shutdown_handler() { try { _debug("got shutdown handler"); if (null !== ($error = error_get_last())) { throw new JAXLException($error['message'], $error['type'], $error['file'], $error['line']); } } catch(Exception $e) { _debug("shutdown handler catched with exception ".json_encode($e)); } } } diff --git a/core/jaxl_fsm.php b/core/jaxl_fsm.php index abf6bc7..d5a6d1e 100644 --- a/core/jaxl_fsm.php +++ b/core/jaxl_fsm.php @@ -1,82 +1,83 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -abstract class JAXLFsm { +abstract class JAXLFsm +{ protected $state = null; // abstract method abstract public function handle_invalid_state($r); public function __construct($state) { $this->state = $state; } // returned value from state callbacks can be: // 1) array() <-- is_callable method // 2) array([0] => 'new_state', [1] => 'return value for current callback') <-- is_not_callable method // 3) array([0] => 'new_state') // 4) 'new_state' // // for case 1) new state will be an array // for other cases new state will be a string public function __call($event, $args) { if ($this->state) { // call state method _debug("calling state handler '".(is_array($this->state) ? $this->state[1] : $this->state)."' for incoming event '".$event."'"); $call = is_callable($this->state) ? $this->state : (method_exists($this, $this->state) ? array(&$this, $this->state): $this->state); $r = call_user_func($call, $event, $args); // 4 cases of possible return value if (is_callable($r)) $this->state = $r; else if (is_array($r) && sizeof($r) == 2) list($this->state, $ret) = $r; else if (is_array($r) && sizeof($r) == 1) $this->state = $r[0]; else if (is_string($r)) $this->state = $r; else $this->handle_invalid_state($r); _debug("current state '".(is_array($this->state) ? $this->state[1] : $this->state)."'"); // return case if (!is_callable($r) && is_array($r) && sizeof($r) == 2) return $ret; } else { _debug("invalid state found, nothing called for event ".$event.""); } } } diff --git a/core/jaxl_logger.php b/core/jaxl_logger.php index c2d1d08..c165ea9 100644 --- a/core/jaxl_logger.php +++ b/core/jaxl_logger.php @@ -1,109 +1,110 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // log level define('JAXL_ERROR', 1); define('JAXL_WARNING', 2); define('JAXL_NOTICE', 3); define('JAXL_INFO', 4); define('JAXL_DEBUG', 5); // generic global logging shortcuts for different level of verbosity function _error($msg) { JAXLLogger::log($msg, JAXL_ERROR); } function _warning($msg) { JAXLLogger::log($msg, JAXL_WARNING); } function _notice($msg) { JAXLLogger::log($msg, JAXL_NOTICE); } function _info($msg) { JAXLLogger::log($msg, JAXL_INFO); } function _debug($msg) { JAXLLogger::log($msg, JAXL_DEBUG); } // generic global terminal output colorize method // finally sends colorized message to terminal using error_log/1 // this method is mainly to escape $msg from file:line and time // prefix done by _debug, _error, ... methods function _colorize($msg, $verbosity) { error_log(JAXLLogger::colorize($msg, $verbosity)); } -class JAXLLogger { +class JAXLLogger +{ public static $level = JAXL_DEBUG; public static $path = null; public static $max_log_size = 1000; protected static $colors = array( 1 => 31, // error: red 2 => 34, // warning: blue 3 => 33, // notice: yellow 4 => 32, // info: green 5 => 37 // debug: white ); public static function log($msg, $verbosity = 1) { if ($verbosity <= self::$level) { $bt = debug_backtrace(); array_shift($bt); $callee = array_shift($bt); $msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg; $size = strlen($msg); if ($size > self::$max_log_size) $msg = substr($msg, 0, self::$max_log_size) . ' ...'; if (isset(self::$path)) error_log($msg . PHP_EOL, 3, self::$path); else error_log(self::colorize($msg, $verbosity)); } } public static function colorize($msg, $verbosity) { return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m"; } } diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index 316155a..553e0cd 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,163 +1,164 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ -class JAXLLoop { +class JAXLLoop +{ public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; private function __construct() { } private function __clone() { } public static function watch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } if (isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function unwatch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; if (isset(self::$read_fds[$fdid])) { unset(self::$read_fds[$fdid]); unset(self::$read_cbs[$fdid]); --self::$active_read_fds; } } if (isset($opts['write'])) { $fdid = (int) $fd; if (isset(self::$write_fds[$fdid])) { unset(self::$write_fds[$fdid]); unset(self::$write_cbs[$fdid]); --self::$active_write_fds; } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function run() { if (!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); while ((self::$active_read_fds + self::$active_write_fds) > 0) self::select(); _debug("no more active fd's to select"); self::$is_running = false; } } private static function select() { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); if ($changed === false) { _error("error in the event loop, shutting down..."); /*foreach (self::$read_fds as $fd) { if (is_resource($fd)) print_r(stream_get_meta_data($fd)); }*/ exit; } else if ($changed > 0) { // read callback foreach ($read as $r) { $fdid = array_search($r, self::$read_fds); if (isset(self::$read_fds[$fdid])) call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); } // write callback foreach ($write as $w) { $fdid = array_search($w, self::$write_fds); if (isset(self::$write_fds[$fdid])) call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); } self::$clock->tick(); } else if ($changed === 0) { //_debug("nothing changed while selecting for read"); self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); } } } diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php index e10f937..5bf0ec3 100644 --- a/core/jaxl_pipe.php +++ b/core/jaxl_pipe.php @@ -1,115 +1,116 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * bidirectional communication pipes for processes * * This is how this will be (when complete): * $pipe = new JAXLPipe() will return an array of size 2 * $pipe[0] represents the read end of the pipe * $pipe[1] represents the write end of the pipe * * Proposed functionality might even change (currently consider this as experimental) * * @author abhinavsingh * */ -class JAXLPipe { +class JAXLPipe +{ protected $perm = 0600; protected $recv_cb = null; protected $fd = null; protected $client = null; public $name = null; public function __construct($name, $read_cb = null) { $pipes_folder = JAXL_CWD.'/.jaxl/pipes'; if (!is_dir($pipes_folder)) mkdir($pipes_folder); $this->ev = new JAXLEvent(); $this->name = $name; $this->read_cb = $read_cb; $pipe_path = $this->get_pipe_file_path(); if (!file_exists($pipe_path)) { posix_mkfifo($pipe_path, $this->perm); $this->fd = fopen($pipe_path, 'r+'); if (!$this->fd) { _error("unable to open pipe"); } else { _debug("pipe opened using path $pipe_path"); _notice("Usage: $ echo 'Hello World!' > $pipe_path"); $this->client = new JAXLSocketClient(); $this->client->connect($this->fd); $this->client->set_callback(array(&$this, 'on_data')); } } else { _error("pipe with name $name already exists"); } } public function __destruct() { @fclose($this->fd); @unlink($this->get_pipe_file_path()); _debug("unlinking pipe file"); } public function get_pipe_file_path() { return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe'; } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function on_data($data) { // callback if ($this->recv_cb) call_user_func($this->recv_cb, $data); } } diff --git a/core/jaxl_sock5.php b/core/jaxl_sock5.php index 7322664..efaca10 100644 --- a/core/jaxl_sock5.php +++ b/core/jaxl_sock5.php @@ -1,132 +1,133 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ -class JAXLSock5 { +class JAXLSock5 +{ private $client = null; protected $transport = null; protected $ip = null; protected $port = null; public function __construct($transport = 'tcp') { $this->transport = $transport; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } public function __destruct() { } public function connect($ip, $port = 1080) { $this->ip = $ip; $this->port = $port; $sock_path = $this->_sock_path(); if ($this->client->connect($sock_path)) { _debug("established connection to $sock_path"); return true; } else { _error("unable to connect $sock_path"); return false; } } // // Three phases of SOCK5 // // Negotiation pkt consists of 3 part: // 0x05 => Sock protocol version // 0x01 => Number of method identifier octet // // Following auth methods are defined: // 0x00 => No authentication required // 0x01 => GSSAPI // 0x02 => USERNAME/PASSWORD // 0x03 to 0x7F => IANA ASSIGNED // 0x80 to 0xFE => RESERVED FOR PRIVATE METHODS // 0xFF => NO ACCEPTABLE METHODS public function negotiate() { $pkt = pack("C3", 0x05, 0x01, 0x00); $this->client->send($pkt); // enter sub-negotiation state } public function relay_request() { // enter wait for reply state } public function send_data() { } // // Socket client callback // public function on_response($raw) { _debug($raw); } // // Private // protected function _sock_path() { return $this->transport.'://'.$this->ip.':'.$this->port; } } diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index 78c96d1..6a45cba 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,224 +1,225 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ -class JAXLSocketClient { +class JAXLSocketClient +{ private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; public function __construct($stream_context = null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ public function connect($socket_path) { if (gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); if (sizeof($path_parts) == 3) $this->port = $path_parts[2]; _info("trying ".$socket_path); if ($this->stream_context) $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); else $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); } else { $this->fd = &$socket_path; } if ($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); $this->disconnect(); return false; } } public function disconnect() { JAXLLoop::unwatch($this->fd, array( 'read' => true, 'write' => true )); @fclose($this->fd); $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); return $ret; } public function send($data) { $this->obuffer .= $data; // add watch for write events if ($this->writing) return; JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if ($bytes === 0) { $meta = stream_get_meta_data($fd); if ($meta['eof'] === TRUE) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); if ($bytes > 0) _debug($raw); // callback if ($this->recv_cb) call_user_func($this->recv_cb, $raw); } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if (strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } } diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index d1747cf..f1a4263 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,262 +1,263 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; -class JAXLSocketServer { +class JAXLSocketServer +{ public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; public function __construct($path, $accept_cb, $request_cb) { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; $ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog))); if (($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { if (@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); } else { _error("unable to set non block flag"); } } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } public function __destruct() { _info("shutting down socket server"); } public function read($client_id) { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } public function send($client_id, $data) { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } public function close($client_id) { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } public function on_server_accept_ready($server) { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); if (!$client) { _error("unable to accept new client conn"); return; } if (@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do if ($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); } // if no accept callback is registered // close the accepted connection else { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } } else { _error("unable to set non block flag"); } } public function on_client_read_ready($client) { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); if ($bytes === 0) { $meta = stream_get_meta_data($client); if ($meta['eof'] === TRUE) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); @fclose($client); unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; if ($this->request_cb) call_user_func($this->request_cb, $client_id, $total); $this->clients[$client_id]['ibuffer'] = ''; } public function on_client_write_ready($client) { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); if ($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; } else if ($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler if (strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } } catch(JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // protected function add_read_cb($client_id) { if ($this->clients[$client_id]['reading']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } protected function add_write_cb($client_id) { if ($this->clients[$client_id]['writing']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } protected function del_read_cb($client_id) { if (!$this->clients[$client_id]['reading']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } protected function del_write_cb($client_id) { if (!$this->clients[$client_id]['writing']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } } diff --git a/core/jaxl_util.php b/core/jaxl_util.php index add9bc4..1cddb7e 100644 --- a/core/jaxl_util.php +++ b/core/jaxl_util.php @@ -1,67 +1,68 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh * */ -class JAXLUtil { +class JAXLUtil +{ public static function get_nonce($binary = true) { $nce = ''; mt_srand((double) microtime()*10000000); for ($i = 0; $i<32; $i++) $nce .= chr(mt_rand(0, 255)); return $binary ? $nce : base64_encode($nce); } public static function get_dns_srv($domain) { $rec = dns_get_record("_xmpp-client._tcp.".$domain, DNS_SRV); if (is_array($rec)) { if (sizeof($rec) == 0) return array($domain, 5222); if (sizeof($rec) > 0) return array($rec[0]['target'], $rec[0]['port']); } } public static function pbkdf2($data, $secret, $iteration, $dkLen = 32, $algo = 'sha1') { return ''; } } diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index f4a2e12..6c8f186 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,203 +1,204 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ -class JAXLXml { +class JAXLXml +{ public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if (is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if (is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if (is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; foreach ($attrs as $k => $v) { if ($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } public function t($text, $append = FALSE) { if (!$append) { $this->rover->text = $text; } else { if ($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; } return $this; } public function c($name, $ns = null, $attrs = array(), $text = null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { if ($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } public function top() { $this->rover = &$this; return $this; } public function exists($name, $ns = null, $attrs = array()) { foreach ($this->childrens as $child) { if ($ns) { if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; } else if ($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } public function update($name, $ns = null, $attrs = array(), $text = null) { foreach ($this->childrens as $k => $child) { if ($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } public function to_string($parent_ns = null) { $xml = ''; $xml .= '<'.$this->name; if ($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; foreach ($this->attrs as $k => $v) if (!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; foreach ($this->childrens as $child) $xml .= $child->to_string($this->ns); if ($this->text) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } } diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php index 33ae2ff..1d7c1b7 100644 --- a/core/jaxl_xml_stream.php +++ b/core/jaxl_xml_stream.php @@ -1,196 +1,197 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Enter description here ... * @author abhinavsingh * */ -class JAXLXmlStream { +class JAXLXmlStream +{ private $delimiter = '\\'; private $ns; private $parser; private $stanza; private $depth = -1; private $start_cb; private $stanza_cb; private $end_cb; public function __construct() { $this->init_parser(); } private function init_parser() { $this->depth = -1; $this->parser = xml_parser_create_ns("UTF-8", $this->delimiter); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); xml_set_character_data_handler($this->parser, array(&$this, "handle_character")); xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag")); } public function __destruct() { //_debug("cleaning up xml parser..."); @xml_parser_free($this->parser); } public function reset_parser() { $this->parse_final(null); @xml_parser_free($this->parser); $this->parser = null; $this->init_parser(); } public function set_callback($start_cb, $end_cb, $stanza_cb) { $this->start_cb = $start_cb; $this->end_cb = $end_cb; $this->stanza_cb = $stanza_cb; } public function parse($str) { xml_parse($this->parser, $str, false); } public function parse_final($str) { xml_parse($this->parser, $str, true); } protected function handle_start_tag($parser, $name, $attrs) { $name = $this->explode($name); //echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL; // replace ns with prefix foreach ($attrs as $key => $v) { $k = $this->explode($key); // no ns specified if ($k[0] == null) { $attrs[$k[1]] = $v; } // xml ns else if ($k[0] == NS_XML) { unset($attrs[$key]); $attrs['xml:'.$k[1]] = $v; } else { _error("==================> unhandled ns prefix on attribute"); // remove attribute else will cause error with bad stanza format // report to developer if above error message is ever encountered unset($attrs[$key]); } } if ($this->depth <= 0) { $this->depth = 0; $this->ns = $name[1]; if ($this->start_cb) { $stanza = new JAXLXml($name[1], $name[0], $attrs); call_user_func($this->start_cb, $stanza); } } else { if (!$this->stanza) { $stanza = new JAXLXml($name[1], $name[0], $attrs); $this->stanza = &$stanza; } else { $this->stanza->c($name[1], $name[0], $attrs); } } ++$this->depth; } protected function handle_end_tag($parser, $name) { $name = explode($this->delimiter, $name); $name = sizeof($name) == 1 ? array('', $name[0]) : $name; //echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL; if ($this->depth == 1) { if ($this->end_cb) { $stanza = new JAXLXml($name[1], $this->ns); call_user_func($this->end_cb, $stanza); } } else if ($this->depth > 1) { if ($this->stanza) $this->stanza->up(); if ($this->depth == 2) { if ($this->stanza_cb) { call_user_func($this->stanza_cb, $this->stanza); $this->stanza = null; } } } --$this->depth; } protected function handle_character($parser, $data) { //echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL; if ($this->stanza) { $this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), TRUE); } } private function implode($data) { return implode($this->delimiter, $data); } private function explode($data) { $data = explode($this->delimiter, $data); $data = sizeof($data) == 1 ? array(null, $data[0]) : $data; return $data; } } diff --git a/http/http_client.php b/http/http_client.php index 5032704..a0db058 100644 --- a/http/http_client.php +++ b/http/http_client.php @@ -1,145 +1,146 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ -class HTTPClient { +class HTTPClient +{ private $url = null; private $parts = array(); private $headers = array(); private $data = null; public $method = null; private $client = null; public function __construct($url, $headers = array(), $data = null) { $this->url = $url; $this->headers = $headers; $this->data = $data; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } public function start($method = 'GET') { $this->method = $method; $this->parts = parse_url($this->url); $transport = $this->_transport(); $ip = $this->_ip(); $port = $this->_port(); $socket_path = $transport.'://'.$ip.':'.$port; if ($this->client->connect($socket_path)) { _debug("connection to $this->url established"); // send request data $this->send_request(); // start main loop JAXLLoop::run(); } else { _debug("unable to open $this->url"); } } public function on_response($raw) { _info("got http response"); } protected function send_request() { $this->client->send($this->_line()."\r\n"); $this->client->send($this->_ua()."\r\n"); $this->client->send($this->_host()."\r\n"); $this->client->send("\r\n"); } // // private methods on uri parts // private function _line() { return $this->method.' '.$this->_uri().' HTTP/1.1'; } private function _ua() { return 'User-Agent: jaxl_http_client/3.x'; } private function _host() { return 'Host: '.$this->parts['host'].':'.$this->_port(); } private function _transport() { return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl'); } private function _ip() { return gethostbyname($this->parts['host']); } private function _port() { return @$this->parts['port'] ? $this->parts['port'] : 80; } private function _uri() { $uri = $this->parts['path']; if (@$this->parts['query']) $uri .= '?'.$this->parts['query']; if (@$this->parts['fragment']) $uri .= '#'.$this->parts['fragment']; return $uri; } } diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php index 4030b5c..8a4f88f 100644 --- a/http/http_dispatcher.php +++ b/http/http_dispatcher.php @@ -1,122 +1,124 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // // (optionally) set an array of url dispatch rules // each dispatch rule is defined by an array of size 4 like: // array($callback, $pattern, $methods, $extra), where // $callback the method which will be called if this rule matches // $pattern regular expression to match request path // $methods list of allowed methods for this rule // pass boolean true to allow all http methods // if omitted or an empty array() is passed (which actually doesnt make sense) // by default 'GET' will be the method allowed on this rule // $extra reserved for future (you can totally omit this as of now) // -class HTTPDispatchRule { +class HTTPDispatchRule +{ // match callback public $cb = null; // regexp to match on request path public $pattern = null; // methods to match upon // add atleast 1 method for this rule to work public $methods = null; // other matching rules public $extra = array(); public function __construct($cb, $pattern, $methods = array('GET'), $extra = array()) { $this->cb = $cb; $this->pattern = $pattern; $this->methods = $methods; $this->extra = $extra; } public function match($path, $method) { if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) { if (in_array($method, $this->methods)) { return $matches; } } return false; } } -class HTTPDispatcher { +class HTTPDispatcher +{ protected $rules = array(); public function __construct() { $this->rules = array(); } public function add_rule($rule) { $s = sizeof($rule); if ($s > 4) { _debug("invalid rule"); return; } // fill up defaults if ($s == 3) { $rule[] = array(); } else if ($s == 2) { $rule[] = array('GET'); $rule[] = array(); } else { _debug("invalid rule"); return; } $this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]); } public function dispatch($request) { foreach ($this->rules as $rule) { //_debug("matching $request->path with pattern $rule->pattern"); if (($matches = $rule->match($request->path, $request->method)) !== false) { _debug("matching rule found, dispatching"); $params = array($request); // TODO: a bad way to restrict on 'pk', fix me for generalization if (@isset($matches['pk'])) $params[] = $matches['pk']; call_user_func_array($rule->cb, $params); return true; } } return false; } } diff --git a/http/http_multipart.php b/http/http_multipart.php index 3f44820..6f3daf4 100644 --- a/http/http_multipart.php +++ b/http/http_multipart.php @@ -1,170 +1,171 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; -class HTTPMultiPart extends JAXLFsm { +class HTTPMultiPart extends JAXLFsm +{ public $boundary = null; public $form_data = array(); public $index = -1; public function handle_invalid_state($r) { _error("got invalid event $r"); } public function __construct($boundary) { $this->boundary = $boundary; parent::__construct('wait_for_boundary_start'); } public function state() { return $this->state; } public function wait_for_boundary_start($event, $data) { if ($event == 'process') { if ($data[0] == '--'.$this->boundary) { $this->index += 1; $this->form_data[$this->index] = array( 'meta' => array(), 'headers' => array(), 'body' => '' ); return array('wait_for_content_disposition', true); } else { _warning("invalid boundary start $data[0] while expecting $this->boundary"); return array('wait_for_boundary_start', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_boundary_start', false); } } public function wait_for_content_disposition($event, $data) { if ($event == 'process') { $disposition = explode(":", $data[0]); if (strtolower(trim($disposition[0])) == 'content-disposition') { $this->form_data[$this->index]['headers'][$disposition[0]] = trim($disposition[1]); $meta = explode(";", $disposition[1]); if (trim(array_shift($meta)) == 'form-data') { foreach ($meta as $k) { list($k, $v) = explode("=", $k); $this->form_data[$this->index]['meta'][$k] = $v; } return array('wait_for_content_type', true); } else { _warning("first part of meta is not form-data"); return array('wait_for_content_disposition', false); } } else { _warning("not a valid content-disposition line"); return array('wait_for_content_disposition', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_disposition', false); } } public function wait_for_content_type($event, $data) { if ($event == 'process') { $type = explode(":", $data[0]); if (strtolower(trim($type[0])) == 'content-type') { $this->form_data[$this->index]['headers'][$type[0]] = trim($type[1]); $this->form_data[$this->index]['meta']['type'] = $type[1]; return array('wait_for_content_body', true); } else { _debug("not a valid content-type line"); return array('wait_for_content_type', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_type', false); } } public function wait_for_content_body($event, $data) { if ($event == 'process') { if ($data[0] == '--'.$this->boundary) { _debug("start of new multipart/form-data detected"); return array('wait_for_content_disposition', true); } else if ($data[0] == '--'.$this->boundary.'--') { _debug("end of multipart form data detected"); return array('wait_for_empty_line', true); } else { $this->form_data[$this->index]['body'] .= $data[0]; return array('wait_for_content_body', true); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_body', false); } } public function wait_for_empty_line($event, $data) { if ($event == 'process') { if ($data[0] == '') { return array('done', true); } else { _warning("invalid empty line $data[0] received"); return array('wait_for_empty_line', false); } } else { _warning("got $event in done state with data $data[0]"); return array('wait_for_empty_line', false); } } public function done($event, $data) { _warning("got unhandled event $event with data $data[0]"); return array('done', false); } } diff --git a/http/http_request.php b/http/http_request.php index 2c24a19..d3b0808 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,502 +1,503 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers = array(), $body = null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // -class HTTPRequest extends JAXLFsm { +class HTTPRequest extends JAXLFsm +{ // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if (sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation // public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; if ($this->body === null) $this->body = $rcvd; else $this->body .= $rcvd; if ($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach ($form_data as $data) { //_debug("passing $data to multipart fsm"); if (!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if (!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if (!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { switch($event) { case 'empty_line': return 'headers_received'; break; default: if (substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if (method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } } else if (@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { $k = trim($k); $v = ltrim($v); // is expect header? if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if (strtolower($k) == 'content-type') { $ctype = explode(';', $v); if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if (strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if ($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { if (sizeof($args) == 0) { $body = null; $headers = array(); } if (sizeof($args) == 1) { // http headers or body only received if (is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } } else if (sizeof($args) == 2) { // body and http headers both received if (is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { foreach ($headers as $k => $v) $this->_send_header($k, $v); } protected function _send_body($body) { $this->_send($body); } protected function _send_response($code, $headers = array(), $body = null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set if ($body && !isset($headers['Content-Length'])) $headers['Content-Length'] = strlen($body); // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); if ($body) $this->_send_body(HTTP_CRLF.$body); } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if (sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach ($query as $q) { $q = explode("=", $q); if (sizeof($q) == 1) $q[1] = ""; $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } } diff --git a/http/http_server.php b/http/http_server.php index 4e9383e..7e5f731 100644 --- a/http/http_server.php +++ b/http/http_server.php @@ -1,198 +1,199 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/http/http_dispatcher.php'; require_once JAXL_CWD.'/http/http_request.php'; // carriage return and line feed define('HTTP_CRLF', "\r\n"); // 1xx informational define('HTTP_100', "Continue"); define('HTTP_101', "Switching Protocols"); // 2xx success define('HTTP_200', "OK"); // 3xx redirection define('HTTP_301', 'Moved Permanently'); define('HTTP_304', 'Not Modified'); // 4xx client error define('HTTP_400', 'Bad Request'); define('HTTP_403', 'Forbidden'); define('HTTP_404', 'Not Found'); define('HTTP_405', 'Method Not Allowed'); define('HTTP_499', 'Client Closed Request'); // Nginx // 5xx server error define('HTTP_500', 'Internal Server Error'); define('HTTP_503', 'Service Unavailable'); -class HTTPServer { +class HTTPServer +{ private $server = null; public $cb = null; private $dispatcher = null; private $requests = array(); public function __construct($port = 9699, $address = "127.0.0.1") { $path = 'tcp://'.$address.':'.$port; $this->server = new JAXLSocketServer( $path, array(&$this, 'on_accept'), array(&$this, 'on_request') ); $this->dispatcher = new HTTPDispatcher(); } public function __destruct() { $this->server = null; } public function dispatch($rules) { foreach ($rules as $rule) { $this->dispatcher->add_rule($rule); } } public function start($cb = null) { $this->cb = $cb; JAXLLoop::run(); } public function on_accept($sock, $addr) { _debug("on_accept for client#$sock, addr:$addr"); // initialize new request obj $request = new HTTPRequest($sock, $addr); // setup sock cb $request->set_sock_cb( array(&$this->server, 'send'), array(&$this->server, 'read'), array(&$this->server, 'close') ); // cache request object $this->requests[$sock] = &$request; // reactive client for further read $this->server->read($sock); } public function on_request($sock, $raw) { _debug("on_request for client#$sock"); $request = $this->requests[$sock]; // 'wait_for_body' state is reached when ever // application calls recv_body() method // on received $request object if ($request->state() == 'wait_for_body') { $request->body($raw); } else { // break on crlf $lines = explode(HTTP_CRLF, $raw); // parse request line if ($request->state() == 'wait_for_request_line') { list($method, $resource, $version) = explode(" ", $lines[0]); $request->line($method, $resource, $version); unset($lines[0]); _info($request->ip." ".$request->method." ".$request->resource." ".$request->version); } // parse headers foreach ($lines as $line) { $line_parts = explode(":", $line); if (sizeof($line_parts) > 1) { if (strlen($line_parts[0]) > 0) { $k = $line_parts[0]; unset($line_parts[0]); $v = implode(":", $line_parts); $request->set_header($k, $v); } } else if (strlen(trim($line_parts[0])) == 0) { $request->empty_line(); } // if exploded line array size is 1 // and thr is something in $line_parts[0] // must be request body else { $request->body($line); } } } // if request has reached 'headers_received' state? if ($request->state() == 'headers_received') { // dispatch to any matching rule found _debug("delegating to dispatcher for further routing"); $dispatched = $this->dispatcher->dispatch($request); // if no dispatch rule matched call generic callback if (!$dispatched && $this->cb) { _debug("no dispatch rule matched, sending to generic callback"); call_user_func($this->cb, $request); } // else if not dispatched and not generic callbacked // send 404 not_found else if (!$dispatched) { // TODO: send 404 if no callback is registered for this request _debug("dropping request since no matching dispatch rule or generic callback was specified"); $request->not_found('404 Not Found'); } } // if state is not 'headers_received' // reactivate client socket for read event else { $this->server->read($sock); } } } diff --git a/jaxl.php b/jaxl.php index 29060d6..bdfa365 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,576 +1,577 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ -class JAXL extends XMPPStream { +class JAXL extends XMPPStream +{ // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger if (isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if (isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if ($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if (!is_dir($this->priv_dir)) mkdir($this->priv_dir); if (!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if (!is_dir($this->pid_dir)) mkdir($this->pid_dir); if (!is_dir($this->log_dir)) mkdir($this->log_dir); if (!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if (!is_array($xeps)) $xeps = array($xeps); foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri = 1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show = 'chat', $priority = 10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type' => 'chat', 'to' => $to, 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid = null, $cb = null) { $attrs = array( 'type' => 'get', 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb = null) { $pkt = $this->get_iq_pkt( array( 'type' => 'get', 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts = array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) $this->enable_debug_shell(); if (@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } diff --git a/jaxlctl b/jaxlctl index 3a9afc6..36fd3cc 100755 --- a/jaxlctl +++ b/jaxlctl @@ -1,196 +1,197 @@ #!/usr/bin/env php <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ $params = $argv; $exe = array_shift($params); $command = array_shift($params); require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // TODO: an abstract JAXLCtlCommand class // with seperate class per command // a mechanism to register new commands -class JAXLCtl { +class JAXLCtl +{ protected $ipc = null; protected $buffer = ''; protected $buffer_cb = null; protected $cli = null; public $dots = "....... "; protected $symbols = array(); public function __construct($command, $params) { global $exe; if (method_exists($this, $command)) { $r = call_user_func_array(array(&$this, $command), $params); if (sizeof($r) == 2) { list($buffer_cb, $quit_cb) = $r; $this->buffer_cb = $buffer_cb; $this->cli = new JAXLCli(array(&$this, 'on_terminal_input'), $quit_cb); $this->run(); } else { _colorize("oops! internal command error", JAXL_ERROR); exit; } } else { _colorize("error: invalid command '$command' received", JAXL_ERROR); _colorize("type '$exe help' for list of available commands", JAXL_NOTICE); exit; } } public function run() { JAXLCli::prompt(); JAXLLoop::run(); } public function on_terminal_input($raw) { $raw = trim($raw); $last = substr($raw, -1, 1); if ($last == ";") { // dispatch to buffer callback call_user_func($this->buffer_cb, $this->buffer.$raw); $this->buffer = ''; } else if ($last == '\\') { $this->buffer .= substr($raw, 0, -1); echo $this->dots; } else { // buffer command $this->buffer .= $raw."; "; echo $this->dots; } } public static function print_help() { global $exe; _colorize("Usage: $exe command [options...]\n", JAXL_INFO); _colorize("Commands:", JAXL_NOTICE); _colorize(" help This help text", JAXL_DEBUG); _colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG); _colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG); echo "\n"; } protected function help() { JAXLCtl::print_help(); exit; } // // shell command // protected function shell() { return array(array(&$this, 'on_shell_input'), array(&$this, 'on_shell_quit')); } private function _eval($raw, $symbols) { extract($symbols); eval($raw); $g = get_defined_vars(); unset($g['raw']); unset($g['symbols']); return $g; } public function on_shell_input($raw) { $this->symbols = $this->_eval($raw, $this->symbols); JAXLCli::prompt(); } public function on_shell_quit() { exit; } // // debug command // protected function debug($sock_path) { $this->ipc = new JAXLSocketClient(); $this->ipc->set_callback(array(&$this, 'on_debug_response')); $this->ipc->connect('unix://'.$sock_path); return array(array(&$this, 'on_debug_input'), array(&$this, 'on_debug_quit')); } public function on_debug_response($raw) { $ret = unserialize($raw); print_r($ret); echo "\n"; JAXLCli::prompt(); } public function on_debug_input($raw) { $this->ipc->send($this->buffer.$raw); } public function on_debug_quit() { $this->ipc->disconnect(); exit; } } // we atleast need a command argument if ($argc < 2) { JAXLCtl::print_help(); exit; } $ctl = new JAXLCtl($command, $params); echo "done\n"; diff --git a/tests/test_jaxl_event.php b/tests/test_jaxl_event.php index 0a87350..dd74261 100644 --- a/tests/test_jaxl_event.php +++ b/tests/test_jaxl_event.php @@ -1,72 +1,73 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ -class JAXLEventTest extends PHPUnit_Framework_TestCase { +class JAXLEventTest extends PHPUnit_Framework_TestCase +{ function test_jaxl_event() { $ev = new JAXLEvent(); $ref1 = $ev->add('on_connect', 'some_func', 0); $ref2 = $ev->add('on_connect', 'some_func1', 0); $ref3 = $ev->add('on_connect', 'some_func2', 1); $ref4 = $ev->add('on_connect', 'some_func3', 4); $ref5 = $ev->add('on_disconnect', 'some_func', 1); $ref6 = $ev->add('on_disconnect', 'some_func1', 1); //$ev->emit('on_connect', null); $ev->del($ref2); $ev->del($ref1); $ev->del($ref6); $ev->del($ref5); $ev->del($ref4); $ev->del($ref3); //print_r($ev->reg); } } diff --git a/tests/test_jaxl_socket_client.php b/tests/test_jaxl_socket_client.php index de8b689..d58d558 100644 --- a/tests/test_jaxl_socket_client.php +++ b/tests/test_jaxl_socket_client.php @@ -1,60 +1,61 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ -class JAXLSocketClientTest extends PHPUnit_Framework_TestCase { +class JAXLSocketClientTest extends PHPUnit_Framework_TestCase +{ function test_jaxl_socket_client() { $sock = new JAXLSocketClient("127.0.0.1", 5222); $sock->connect(); $sock->send("<stream:stream>"); while ($sock->fd) { $sock->recv(); } } } diff --git a/tests/test_jaxl_xml_stream.php b/tests/test_jaxl_xml_stream.php index 8701420..0538af6 100644 --- a/tests/test_jaxl_xml_stream.php +++ b/tests/test_jaxl_xml_stream.php @@ -1,78 +1,79 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ -class JAXLXmlStreamTest extends PHPUnit_Framework_TestCase { +class JAXLXmlStreamTest extends PHPUnit_Framework_TestCase +{ function xml_start_cb($node) { $this->assertEquals('stream', $node->name); $this->assertEquals(NS_XMPP, $node->ns); } function xml_end_cb($node) { $this->assertEquals('stream', $node->name); } function xml_stanza_cb($node) { $this->assertEquals('features', $node->name); $this->assertEquals(1, sizeof($node->childrens)); } function test_xml_stream_callbacks() { $xml = new JAXLXmlStream(); $xml->set_callback(array(&$this, "xml_start_cb"), array(&$this, "xml_end_cb"), array(&$this, "xml_stanza_cb")); $xml->parse('<stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">'); $xml->parse('<features>'); $xml->parse('<mechanisms>'); $xml->parse('</mechanisms>'); $xml->parse('</features>'); $xml->parse('</stream:stream>'); } } diff --git a/tests/test_xmpp_jid.php b/tests/test_xmpp_jid.php index 00b93fd..6d6fd94 100644 --- a/tests/test_xmpp_jid.php +++ b/tests/test_xmpp_jid.php @@ -1,64 +1,65 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ -class XMPPJidTest extends PHPUnit_Framework_TestCase { +class XMPPJidTest extends PHPUnit_Framework_TestCase +{ function test_xmpp_jid_construct() { $jid = new XMPPJid("[email protected]/res"); $this->assertEquals('[email protected]/res', $jid->to_string()); $jid = new XMPPJid("domain.tld/res"); $this->assertEquals('domain.tld/res', $jid->to_string()); $jid = new XMPPJid("component.domain.tld"); $this->assertEquals('component.domain.tld', $jid->to_string()); $jid = new XMPPJid("[email protected]"); $this->assertEquals('[email protected]', $jid->to_string()); } } diff --git a/tests/test_xmpp_msg.php b/tests/test_xmpp_msg.php index 8440e74..93702fc 100644 --- a/tests/test_xmpp_msg.php +++ b/tests/test_xmpp_msg.php @@ -1,68 +1,69 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ -class XMPPMsgTest extends PHPUnit_Framework_TestCase { +class XMPPMsgTest extends PHPUnit_Framework_TestCase +{ function test_xmpp_msg() { $msg = new XMPPMsg(array('to' => '[email protected]', 'from' => '[email protected]/~', 'type' => 'chat'), 'hi', 'thread1'); echo $msg->to.PHP_EOL; echo $msg->to_node.PHP_EOL; echo $msg->from.PHP_EOL; echo $msg->to_string().PHP_EOL; $msg->to = '[email protected]/sp'; $msg->body = 'hello world'; $msg->subject = 'some subject'; echo $msg->to.PHP_EOL; echo $msg->to_node.PHP_EOL; echo $msg->from.PHP_EOL; echo $msg->to_string().PHP_EOL; } } diff --git a/tests/test_xmpp_stanza.php b/tests/test_xmpp_stanza.php index 50b0bce..3e0fa33 100644 --- a/tests/test_xmpp_stanza.php +++ b/tests/test_xmpp_stanza.php @@ -1,77 +1,78 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ -class XMPPStanzaTest extends PHPUnit_Framework_TestCase { +class XMPPStanzaTest extends PHPUnit_Framework_TestCase +{ function test_xmpp_stanza_nested() { $stanza = new JAXLXml('message', array('to' => '[email protected]', 'from' => '[email protected]')); $stanza ->c('body')->attrs(array('xml:lang' => 'en'))->t('hello')->up() ->c('thread')->t('1234')->up() ->c('nested') ->c('nest')->t('nest1')->up() ->c('nest')->t('nest2')->up() ->c('nest')->t('nest3')->up()->up() ->c('c')->attrs(array('hash' => '84jsdmnskd')); $this->assertEquals( '<message to="[email protected]" from="[email protected]"><body xml:lang="en">hello</body><thread>1234</thread><nested><nest>nest1</nest><nest>nest2</nest><nest>nest3</nest></nested><c hash="84jsdmnskd"></c></message>', $stanza->to_string() ); } function test_xmpp_stanza_from_jaxl_xml() { // xml to stanza test $xml = new JAXLXml('message', NS_JABBER_CLIENT, array('to' => '[email protected]', 'from' => '[email protected]/q')); $stanza = new XMPPStanza($xml); $stanza->c('body')->t('hello world'); echo $stanza->to."\n"; echo $stanza->to_string()."\n"; } } diff --git a/tests/test_xmpp_stream.php b/tests/test_xmpp_stream.php index c03f8e0..8e72f4c 100644 --- a/tests/test_xmpp_stream.php +++ b/tests/test_xmpp_stream.php @@ -1,60 +1,61 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ -class XMPPStreamTest extends PHPUnit_Framework_TestCase { +class XMPPStreamTest extends PHPUnit_Framework_TestCase +{ function test_xmpp_stream() { $xmpp = new XMPPStream("test@localhost", "password"); $xmpp->connect(); $xmpp->start_stream(); while ($xmpp->sock->fd) { $xmpp->sock->recv(); } } } diff --git a/tests/tests.php b/tests/tests.php index 129bc05..8d467a8 100644 --- a/tests/tests.php +++ b/tests/tests.php @@ -1,50 +1,51 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ -class JAXLTest extends PHPUnit_Framework_TestCase { +class JAXLTest extends PHPUnit_Framework_TestCase +{ } diff --git a/xep/xep_0030.php b/xep/xep_0030.php index 2d14786..c6d5cfd 100644 --- a/xep/xep_0030.php +++ b/xep/xep_0030.php @@ -1,94 +1,95 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DISCO_INFO', 'http://jabber.org/protocol/disco#info'); define('NS_DISCO_ITEMS', 'http://jabber.org/protocol/disco#items'); -class XEP_0030 extends XMPPXep { +class XEP_0030 extends XMPPXep +{ // // abstract method // public function init() { return array( ); } // // api methods // public function get_info_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid), new JAXLXml('query', NS_DISCO_INFO) ); } public function get_info($entity_jid, $callback = null) { $pkt = $this->get_info_pkt($entity_jid); if ($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } public function get_items_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid), new JAXLXml('query', NS_DISCO_ITEMS) ); } public function get_items($entity_jid, $callback = null) { $pkt = $this->get_items_pkt($entity_jid); if ($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } // // event callbacks // } diff --git a/xep/xep_0045.php b/xep/xep_0045.php index 5ecbacc..5e405a2 100644 --- a/xep/xep_0045.php +++ b/xep/xep_0045.php @@ -1,117 +1,118 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_MUC', 'http://jabber.org/protocol/muc'); -class XEP_0045 extends XMPPXep { +class XEP_0045 extends XMPPXep +{ // // abstract method // public function init() { return array(); } public function send_groupchat($room_jid, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type' => 'groupchat', 'to' => (($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid), 'from' => $this->jaxl->full_jid->to_string() ), $body, $thread, $subject ); $this->jaxl->send($msg); } // // api methods (occupant use case) // // room_full_jid simply means room jid with nick name as resource public function get_join_room_pkt($room_full_jid, $options) { $pkt = $this->jaxl->get_pres_pkt( array( 'from' => $this->jaxl->full_jid->to_string(), 'to' => (($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid) ) ); $x = $pkt->c('x', NS_MUC); if (isset($options['no_history'])) { $x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0)); } return $x; } public function join_room($room_full_jid, $options = array()) { $pkt = $this->get_join_room_pkt($room_full_jid, $options); $this->jaxl->send($pkt); } public function get_leave_room_pkt($room_full_jid) { return $this->jaxl->get_pres_pkt( array('type' => 'unavailable', 'from' => $this->jaxl->full_jid->to_string(), 'to' => (($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid)) ); } public function leave_room($room_full_jid) { $pkt = $this->get_leave_room_pkt($room_full_jid); $this->jaxl->send($pkt); } // // api methods (moderator use case) // // // event callbacks // } diff --git a/xep/xep_0060.php b/xep/xep_0060.php index 2a1c70c..318f9c7 100644 --- a/xep/xep_0060.php +++ b/xep/xep_0060.php @@ -1,149 +1,150 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_PUBSUB', 'http://jabber.org/protocol/pubsub'); -class XEP_0060 extends XMPPXep { +class XEP_0060 extends XMPPXep +{ // // abstract method // public function init() { return array(); } // // api methods (entity use case) // // // api methods (subscriber use case) // public function get_subscribe_pkt($service, $node, $jid = null) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('subscribe', null, array('node' => $node, 'jid' => ($jid ? $jid : $this->jaxl->full_jid->to_string()))); return $this->get_iq_pkt($service, $child); } public function subscribe($service, $node, $jid = null) { $this->jaxl->send($this->get_subscribe_pkt($service, $node, $jid)); } public function unsubscribe() { } public function get_subscription_options() { } public function set_subscription_options() { } public function get_node_items() { } // // api methods (publisher use case) // public function get_publish_item_pkt($service, $node, $item) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('publish', null, array('node' => $node)); $child->cnode($item); return $this->get_iq_pkt($service, $child); } public function publish_item($service, $node, $item) { $this->jaxl->send($this->get_publish_item_pkt($service, $node, $item)); } public function delete_item() { } // // api methods (owner use case) // public function get_create_node_pkt($service, $node) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('create', null, array('node' => $node)); return $this->get_iq_pkt($service, $child); } public function create_node($service, $node) { $this->jaxl->send($this->get_create_node_pkt($service, $node)); } // // event callbacks // // // local methods // // this always add attrs protected function get_iq_pkt($service, $child, $type = 'set') { return $this->jaxl->get_iq_pkt( array('type' => $type, 'from' => $this->jaxl->full_jid->to_string(), 'to' => $service), $child ); } } diff --git a/xep/xep_0077.php b/xep/xep_0077.php index 5250a14..5ca27da 100644 --- a/xep/xep_0077.php +++ b/xep/xep_0077.php @@ -1,84 +1,85 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_FEATURE_REGISTER', 'http://jabber.org/features/iq-register'); define('NS_INBAND_REGISTER', 'jabber:iq:register'); -class XEP_0077 extends XMPPXep { +class XEP_0077 extends XMPPXep +{ // // abstract method // public function init() { return array( ); } // // api methods // public function get_form_pkt($domain) { return $this->jaxl->get_iq_pkt( array('to' => $domain, 'type' => 'get'), new JAXLXml('query', NS_INBAND_REGISTER) ); } public function get_form($domain) { $this->jaxl->send($this->get_form_pkt($domain)); } public function set_form($domain, $form) { $query = new JAXLXml('query', NS_INBAND_REGISTER); foreach ($form as $k => $v) $query->c($k, null, array(), $v)->up(); $pkt = $this->jaxl->get_iq_pkt( array('to' => $domain, 'type' => 'set'), $query ); $this->jaxl->send($pkt); } } diff --git a/xep/xep_0114.php b/xep/xep_0114.php index e27a0ec..de3c154 100644 --- a/xep/xep_0114.php +++ b/xep/xep_0114.php @@ -1,96 +1,97 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_JABBER_COMPONENT_ACCEPT', 'jabber:component:accept'); -class XEP_0114 extends XMPPXep { +class XEP_0114 extends XMPPXep +{ // // abstract method // public function init() { return array( 'on_connect' => 'start_stream', 'on_stream_start' => 'start_handshake', 'on_handshake_stanza' => 'logged_in', 'on_error_stanza' => 'logged_out' ); } // // event callbacks // public function start_stream() { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" to="'.$this->jaxl->jid->to_string().'" xmlns="'.NS_JABBER_COMPONENT_ACCEPT.'">'; $this->jaxl->send_raw($xml); } public function start_handshake($stanza) { _debug("starting component handshake"); $id = $stanza->id; $hash = strtolower(sha1($id.$this->jaxl->pass)); $stanza = new JAXLXml('handshake', null, $hash); $this->jaxl->send($stanza); } public function logged_in($stanza) { _debug("component handshake complete"); $this->jaxl->handle_auth_success(); return array("logged_in", 1); } public function logged_out($stanza) { if ($stanza->name == "error" && $stanza->ns == NS_XMPP) { $reason = $stanza->childrens[0]->name; $this->jaxl->handle_auth_failure($reason); $this->jaxl->send_end_stream(); return array("logged_out", 0); } else { _debug("uncatched stanza received in logged_out"); } } } diff --git a/xep/xep_0115.php b/xep/xep_0115.php index 53e2fe3..13d8176 100644 --- a/xep/xep_0115.php +++ b/xep/xep_0115.php @@ -1,72 +1,73 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_CAPS', 'http://jabber.org/protocol/caps'); -class XEP_0115 extends XMPPXep { +class XEP_0115 extends XMPPXep +{ // // abstract method // public function init() { return array(); } // // api methods // public function get_caps_pkt($cat, $type, $lang, $name, $node, $features) { asort($features); $S = $cat.'/'.$type.'/'.$lang.'/'.$name.'<'; foreach ($features as $feature) $S .= $feature.'<'; $ver = base64_encode(sha1($S, true)); $stanza = new JAXLXml('c', NS_CAPS, array('hash' => 'sha1', 'node' => $node, 'ver' => $ver)); return $stanza; } // // event callbacks // } diff --git a/xep/xep_0199.php b/xep/xep_0199.php index d71c1d4..91bb445 100644 --- a/xep/xep_0199.php +++ b/xep/xep_0199.php @@ -1,62 +1,63 @@ <?php require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_XMPP_PING', 'urn:xmpp:ping'); -class XEP_0199 extends XMPPXep { +class XEP_0199 extends XMPPXep +{ // // abstract method // public function init() { return array( 'on_auth_success' => 'on_auth_success', 'on_get_iq' => 'on_xmpp_ping' ); } // // api methods // public function get_ping_pkt() { $attrs = array( 'type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $this->jaxl->full_jid->domain ); return $this->jaxl->get_iq_pkt( $attrs, new JAXLXml('ping', NS_XMPP_PING) ); } public function ping() { $this->jaxl->send($this->get_ping_pkt()); } // // event callbacks // public function on_auth_success() { JAXLLoop::$clock->call_fun_periodic(30 * pow(10,6), array(&$this, 'ping')); } public function on_xmpp_ping($stanza) { if ($stanza->exists('ping', NS_XMPP_PING)) { $stanza->type = "result"; $stanza->to = $stanza->from; $stanza->from = $this->jaxl->full_jid->to_string(); $this->jaxl->send($stanza); } } } diff --git a/xep/xep_0203.php b/xep/xep_0203.php index ae1968d..39ea10a 100644 --- a/xep/xep_0203.php +++ b/xep/xep_0203.php @@ -1,61 +1,62 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DELAYED_DELIVERY', 'urn:xmpp:delay'); -class XEP_0203 extends XMPPXep { +class XEP_0203 extends XMPPXep +{ // // abstract method // public function init() { return array(); } // // api methods // // // event callbacks // } diff --git a/xep/xep_0206.php b/xep/xep_0206.php index 9b7a4e3..61e73fc 100644 --- a/xep/xep_0206.php +++ b/xep/xep_0206.php @@ -1,238 +1,239 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind'); define('NS_BOSH', 'urn:xmpp:xbosh'); -class XEP_0206 extends XMPPXep { +class XEP_0206 extends XMPPXep +{ private $mch = null; public $chs = array(); private $recv_cb = null; public $rid = null; public $sid = null; private $hold = 1; private $wait = 30; private $restarted = false; public $headers = array( 'Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8' ); // // abstract method // public function init() { $this->mch = curl_multi_init(); return array( ); } // // event callbacks // public function send($body) { if (is_object($body)) { $body = $body->to_string(); } else { if (substr($body, 0, 15) == '<stream:stream ') { $this->restarted = true; $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'xmpp:restart' => 'true', 'xmlns:xmpp' => NS_BOSH )); $body = $body->to_string(); } else if (substr($body, 0, 16) == '</stream:stream>') { $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'type' => 'terminate' )); $body = $body->to_string(); } else { $body = $this->wrap($body); } } _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body); $this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']); curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers); curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false); curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1); curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body); curl_multi_add_handle($this->mch, $this->chs[$this->rid]); } public function recv() { if ($this->restarted) { $this->restarted = false; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); } _debug("recving for $this->rid"); do { $ret = curl_multi_exec($this->mch, $running); $changed = curl_multi_select($this->mch, 0.1); if ($changed == 0 && $running == 0) { $ch = @$this->chs[$this->rid]; if ($ch) { $data = curl_multi_getcontent($ch); curl_multi_remove_handle($this->mch, $ch); unset($this->chs[$this->rid]); _debug("recvd for $this->rid ".$data); list($body, $stanza) = $this->unwrap($data); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if (@$attrs['type'] == 'terminate') { // fool me again if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); } else { if (!$this->sid) { $this->sid = $attrs['sid']; } if ($this->recv_cb) call_user_func($this->recv_cb, $stanza); } } else { _error("no ch found"); exit; } } } while ($running); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function wrap($stanza) { return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>'; } public function unwrap($body) { // a dirty way but it works efficiently if (substr($body, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); if (isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; else $envelop = "<body/>"; if (isset($m[2][0])) $payload = $m[2][0]; else $payload = ''; return array($envelop, $payload); } public function session_start() { $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000); $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold; $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); $attrs = array( 'content' => 'text/xml; charset=utf-8', 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'], 'secure' => 'true', 'xml:lang' => 'en', 'xmpp:version' => '1.0', 'xmlns:xmpp' => NS_BOSH, 'hold' => $this->hold, 'wait' => $this->wait, 'rid' => $this->rid, 'ver' => '1.10' ); if (@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; $body = new JAXLXml('body', NS_HTTP_BIND, $attrs); $this->send($body); } public function ping() { $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid)); $this->send($body); } public function session_end() { $this->disconnect(); } public function disconnect() { _debug("disconnecting"); } } diff --git a/xep/xep_0249.php b/xep/xep_0249.php index 59bd115..12dd79b 100644 --- a/xep/xep_0249.php +++ b/xep/xep_0249.php @@ -1,81 +1,82 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DIRECT_MUC_INVITATION', 'jabber:x:conference'); -class XEP_0249 extends XMPPXep { +class XEP_0249 extends XMPPXep +{ // // abstract method // public function init() { return array(); } // // api methods // public function get_invite_pkt($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) { $xattrs = array('jid' => $room_jid); if ($password) $xattrs['password'] = $password; if ($reason) $xattrs['reason'] = $reason; if ($thread) $xattrs['thread'] = $thread; if ($continue) $xattrs['continue'] = $continue; return $this->jaxl->get_msg_pkt( array('from' => $this->jaxl->full_jid->to_string(), 'to' => $to_bare_jid), null, null, null, new JAXLXml('x', NS_DIRECT_MUC_INVITATION, $xattrs) ); } public function invite($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) { $this->jaxl->send($this->get_invite_pkt($to_bare_jid, $room_jid, $password, $reason, $thread, $continue)); } // // event callbacks // } diff --git a/xmpp/xmpp_iq.php b/xmpp/xmpp_iq.php index 19103bf..1bf80f3 100644 --- a/xmpp/xmpp_iq.php +++ b/xmpp/xmpp_iq.php @@ -1,47 +1,48 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; -class XMPPIq extends XMPPStanza { +class XMPPIq extends XMPPStanza +{ public function __construct($attrs) { parent::__construct('iq', $attrs); } } diff --git a/xmpp/xmpp_jid.php b/xmpp/xmpp_jid.php index 249a643..5b1b89d 100644 --- a/xmpp/xmpp_jid.php +++ b/xmpp/xmpp_jid.php @@ -1,80 +1,81 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Xmpp Jid * * @author abhinavsingh * */ -class XMPPJid { +class XMPPJid +{ public $node = null; public $domain = null; public $resource = null; public $bare = null; public function __construct($str) { $tmp = explode("@", $str); if (sizeof($tmp) == 2) { $this->node = $tmp[0]; $tmp = explode("/", $tmp[1]); if (sizeof($tmp) == 2) { $this->domain = $tmp[0]; $this->resource = $tmp[1]; } else { $this->domain = $tmp[0]; } } else if (sizeof($tmp) == 1) { $this->domain = $tmp[0]; } $this->bare = $this->node ? $this->node."@".$this->domain : $this->domain; } public function to_string() { $str = ""; if ($this->node) $str .= $this->node.'@'.$this->domain; else if ($this->domain) $str .= $this->domain; if ($this->resource) $str .= '/'.$this->resource; return $str; } } diff --git a/xmpp/xmpp_msg.php b/xmpp/xmpp_msg.php index 9847246..838d332 100644 --- a/xmpp/xmpp_msg.php +++ b/xmpp/xmpp_msg.php @@ -1,51 +1,52 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; -class XMPPMsg extends XMPPStanza { +class XMPPMsg extends XMPPStanza +{ public function __construct($attrs, $body = null, $thread = null, $subject = null) { parent::__construct('message', $attrs); if ($body) $this->c('body')->t($body)->up(); if ($thread) $this->c('thread')->t($thread)->up(); if ($subject) $this->c('subject')->t($subject)->up(); } } diff --git a/xmpp/xmpp_pres.php b/xmpp/xmpp_pres.php index f76bb6c..a054686 100644 --- a/xmpp/xmpp_pres.php +++ b/xmpp/xmpp_pres.php @@ -1,51 +1,52 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; -class XMPPPres extends XMPPStanza { +class XMPPPres extends XMPPStanza +{ public function __construct($attrs, $status = null, $show = null, $priority = null) { parent::__construct('presence', $attrs); if ($status) $this->c('status')->t($status)->up(); if ($show) $this->c('show')->t($show)->up(); if ($priority) $this->c('priority')->t($priority)->up(); } } diff --git a/xmpp/xmpp_roster_item.php b/xmpp/xmpp_roster_item.php index cab1eee..be0613b 100644 --- a/xmpp/xmpp_roster_item.php +++ b/xmpp/xmpp_roster_item.php @@ -1,57 +1,58 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh */ -class XMPPRosterItem { +class XMPPRosterItem +{ public $jid = null; public $subscription = null; public $groups = array(); public $resources = array(); public $vcard = null; public function __construct($jid, $subscription, $groups) { $this->jid = $jid; $this->subscription = $subscription; $this->groups = $groups; } } diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php index 50ac613..f8be8da 100644 --- a/xmpp/xmpp_stanza.php +++ b/xmpp/xmpp_stanza.php @@ -1,177 +1,178 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; /** * Generic xmpp stanza object which provide convinient access pattern over xml objects * Also to be able to convert an existing xml object into stanza object (to get access patterns going) * this class doesn't extend xml, but infact works on a reference of xml object * If not provided during constructor, new xml object is created and saved as reference * * @author abhinavsingh * */ -class XMPPStanza { +class XMPPStanza +{ private $xml; public function __construct($name, $attrs = array(), $ns = NS_JABBER_CLIENT) { if ($name instanceof JAXLXml) $this->xml = $name; else $this->xml = new JAXLXml($name, $ns, $attrs); } public function __call($method, $args) { return call_user_func_array(array($this->xml, $method), $args); } public function __get($prop) { switch($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': return @$this->xml->attrs[$prop] ? $this->xml->attrs[$prop] : null; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val = @$this->xml->attrs[$attr] ? $this->xml->attrs[$attr] : null; if (!$val) return null; $val = new XMPPJid($val); return $val->$key; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val = $this->xml->exists($prop); if (!$val) return null; return $val->text; break; default: return null; break; } } public function __set($prop, $val) { switch($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop = $val; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': $this->xml->attrs[$prop] = $val; return true; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val1 = @$this->xml->attrs[$attr]; if (!$val1) $val1 = ''; $val1 = new XMPPJid($val1); $val1->$key = $val; $this->xml->attrs[$attr] = $val1->to_string(); return true; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val1 = $this->xml->exists($prop); if (!$val1) $this->xml->c($prop)->t($val)->up(); else $this->xml->update($prop, $val1->ns, $val1->attrs, $val); return true; break; default: return null; break; } } } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index d96ca4d..d2a2ec3 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,569 +1,570 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ -abstract class XMPPStream extends JAXLFsm { +abstract class XMPPStream extends JAXLFsm +{ // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass = null, $resource = null, $force_tls = false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if (isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; if (isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if (strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if (!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc' => $nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if (isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if (!$msg->id) $msg->id = $this->get_id(); if ($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if (!$pres->id) $pres->id = $this->get_id(); if ($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if (!$iq->id) $iq->id = $this->get_id(); if ($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } else if (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach ($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach (array('realm', 'cnonce', 'digest-uri') as $key) if (!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if (isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if ($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { diff --git a/xmpp/xmpp_xep.php b/xmpp/xmpp_xep.php index 2d1058f..1b88461 100644 --- a/xmpp/xmpp_xep.php +++ b/xmpp/xmpp_xep.php @@ -1,65 +1,66 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh * */ -abstract class XMPPXep { +abstract class XMPPXep +{ // init() method defines various callbacks // required by this xep extension abstract public function init(); //abstract public $description; //abstract public $dependencies; // reference to jaxl instance // which required me protected $jaxl = null; public function __construct($jaxl) { $this->jaxl = $jaxl; } public function __destruct() { } }
jaxl/JAXL
d2796e919b9f8e16848130b49e62bcaffdee42a2
Fix PSR: Opening brace should be on a new line
diff --git a/core/jaxl_cli.php b/core/jaxl_cli.php index 1f6f259..3f539fb 100644 --- a/core/jaxl_cli.php +++ b/core/jaxl_cli.php @@ -1,93 +1,98 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLCli { public static $counter = 0; private $in = null; private $quit_cb = null; private $recv_cb = null; private $recv_chunk_size = 1024; - public function __construct($recv_cb = null, $quit_cb = null) { + public function __construct($recv_cb = null, $quit_cb = null) + { $this->recv_cb = $recv_cb; $this->quit_cb = $quit_cb; // catch read event on stdin $this->in = fopen('php://stdin', 'r'); stream_set_blocking($this->in, false); JAXLLoop::watch($this->in, array( 'read' => array(&$this, 'on_read_ready') )); } - public function __destruct() { + public function __destruct() + { @fclose($this->in); } - public function stop() { + public function stop() + { JAXLLoop::unwatch($this->in, array( 'read' => true )); } - public function on_read_ready($in) { + public function on_read_ready($in) + { $raw = @fread($in, $this->recv_chunk_size); if (ord($raw) == 10) { // enter key JAXLCli::prompt(false); return; } else if (trim($raw) == 'quit') { $this->stop(); $this->in = null; if ($this->quit_cb) call_user_func($this->quit_cb); return; } if ($this->recv_cb) call_user_func($this->recv_cb, $raw); } - public static function prompt($inc = true) { + public static function prompt($inc = true) + { if ($inc) ++self::$counter; echo "jaxl ".self::$counter."> "; } } diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php index e631298..d74af6c 100644 --- a/core/jaxl_clock.php +++ b/core/jaxl_clock.php @@ -1,121 +1,128 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class JAXLClock { // current clock time in microseconds private $tick = 0; // current Unix timestamp with microseconds public $time = null; // scheduled jobs public $jobs = array(); - public function __construct() { + public function __construct() + { $this->time = microtime(true); } - public function __destruct() { + public function __destruct() + { _info("shutting down clock server..."); } - public function tick($by = null) { + public function tick($by = null) + { // update clock if ($by) { $this->tick += $by; $this->time += $by / pow(10,6); } else { $time = microtime(true); $by = $time - $this->time; $this->tick += $by * pow(10, 6); $this->time = $time; } // run scheduled jobs foreach ($this->jobs as $ref => $job) { if ($this->tick >= $job['scheduled_on'] + $job['after']) { //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".$job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); call_user_func($job['cb'], $job['args']); if (!$job['is_periodic']) { unset($this->jobs[$ref]); } else { $job['scheduled_on'] = $this->tick; $job['runs']++; $this->jobs[$ref] = $job; } } } } // calculate execution time of callback - public function tc($callback, $args = null) { + public function tc($callback, $args = null) + { } // callback after $time microseconds - public function call_fun_after($time, $callback, $args = null) { + public function call_fun_after($time, $callback, $args = null) + { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => false, 'runs' => 0 ); return sizeof($this->jobs); } // callback periodically after $time microseconds - public function call_fun_periodic($time, $callback, $args = null) { + public function call_fun_periodic($time, $callback, $args = null) + { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => true, 'runs' => 0 ); return sizeof($this->jobs); } // cancel a previously scheduled callback - public function cancel_fun_call($ref) { + public function cancel_fun_call($ref) + { unset($this->jobs[$ref-1]); } } diff --git a/core/jaxl_event.php b/core/jaxl_event.php index 315afda..56c6898 100644 --- a/core/jaxl_event.php +++ b/core/jaxl_event.php @@ -1,118 +1,124 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * following kind of events are possible: * 1) hook i.e. if a callback for such an event is registered, calling function is responsible for the workflow from their on * 2) filter i.e. calling function will manipulate passed arguments and modified arguments will be passed to next chain of filter * * As a rule of thumb, only 1 hook can be registered for an event, while more than 1 filter is allowed for an event * hook and filter both cannot be applied on an event * * @author abhinavsingh * */ class JAXLEvent { protected $common = array(); public $reg = array(); - public function __construct($common) { + public function __construct($common) + { $this->common = $common; } - public function __destruct() { + public function __destruct() + { } // add callback on a event // returns a reference to be used while deleting callback // callback'd method must return TRUE to be persistent // if none returned or FALSE, callback will be removed automatically - public function add($ev, $cb, $pri) { + public function add($ev, $cb, $pri) + { if (!isset($this->reg[$ev])) $this->reg[$ev] = array(); $ref = sizeof($this->reg[$ev]); $this->reg[$ev][] = array($pri, $cb); return $ev."-".$ref; } // emit event to notify registered callbacks // is a pqueue required here for performance enhancement // in case we have too many cbs on a specific event? - public function emit($ev, $data = array()) { + public function emit($ev, $data = array()) + { $data = array_merge($this->common, $data); $cbs = array(); if (!isset($this->reg[$ev])) return $data; foreach ($this->reg[$ev] as $cb) { if (!isset($cbs[$cb[0]])) $cbs[$cb[0]] = array(); $cbs[$cb[0]][] = $cb[1]; } foreach ($cbs as $pri => $cb) { foreach ($cb as $c) { $ret = call_user_func_array($c, $data); // this line is for fixing situation where callback function doesn't return an array type // in such cases next call of call_user_func_array will report error since $data is not an array type as expected // things will change in future, atleast put the callback inside a try/catch block // here we only check if there was a return, if yes we update $data with return value // this is bad design, need more thoughts, should work as of now if ($ret) $data = $ret; } } unset($cbs); return $data; } // remove previous registered callback - public function del($ref) { + public function del($ref) + { $ref = explode("-", $ref); unset($this->reg[$ref[0]][$ref[1]]); } - public function exists($ev) { + public function exists($ev) + { $ret = isset($this->reg[$ev]); //_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists")); return $ret; } } diff --git a/core/jaxl_exception.php b/core/jaxl_exception.php index 72d6db1..276ad40 100644 --- a/core/jaxl_exception.php +++ b/core/jaxl_exception.php @@ -1,91 +1,95 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ error_reporting(E_ALL | E_STRICT); /** * * @author abhinavsingh */ class JAXLException extends Exception { - public function __construct($message = null, $code = null, $file = null, $line = null) { + public function __construct($message = null, $code = null, $file = null, $line = null) + { _notice("got jaxl exception construct with $message, $code, $file, $line"); if ($code === null) { parent::__construct($message); } else { parent::__construct($message, $code); } if ($file !== null) { $this->file = $file; } if ($line !== null) { $this->line = $line; } } - public static function error_handler($errno, $error, $file, $line, $vars) { + public static function error_handler($errno, $error, $file, $line, $vars) + { _debug("error handler called with $errno, $error, $file, $line"); if ($errno === 0 || ($errno & error_reporting()) === 0) { return; } throw new JAXLException($error, $errno, $file, $line); } - public static function exception_handler($e) { + public static function exception_handler($e) + { _debug("exception handler catched ".json_encode($e)); // TODO: Pretty print backtrace //print_r(debug_backtrace()); } - public static function shutdown_handler() { + public static function shutdown_handler() + { try { _debug("got shutdown handler"); if (null !== ($error = error_get_last())) { throw new JAXLException($error['message'], $error['type'], $error['file'], $error['line']); } } catch(Exception $e) { _debug("shutdown handler catched with exception ".json_encode($e)); } } } diff --git a/core/jaxl_fsm.php b/core/jaxl_fsm.php index 7b18cce..abf6bc7 100644 --- a/core/jaxl_fsm.php +++ b/core/jaxl_fsm.php @@ -1,80 +1,82 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ abstract class JAXLFsm { protected $state = null; // abstract method abstract public function handle_invalid_state($r); - public function __construct($state) { + public function __construct($state) + { $this->state = $state; } // returned value from state callbacks can be: // 1) array() <-- is_callable method // 2) array([0] => 'new_state', [1] => 'return value for current callback') <-- is_not_callable method // 3) array([0] => 'new_state') // 4) 'new_state' // // for case 1) new state will be an array // for other cases new state will be a string - public function __call($event, $args) { + public function __call($event, $args) + { if ($this->state) { // call state method _debug("calling state handler '".(is_array($this->state) ? $this->state[1] : $this->state)."' for incoming event '".$event."'"); $call = is_callable($this->state) ? $this->state : (method_exists($this, $this->state) ? array(&$this, $this->state): $this->state); $r = call_user_func($call, $event, $args); // 4 cases of possible return value if (is_callable($r)) $this->state = $r; else if (is_array($r) && sizeof($r) == 2) list($this->state, $ret) = $r; else if (is_array($r) && sizeof($r) == 1) $this->state = $r[0]; else if (is_string($r)) $this->state = $r; else $this->handle_invalid_state($r); _debug("current state '".(is_array($this->state) ? $this->state[1] : $this->state)."'"); // return case if (!is_callable($r) && is_array($r) && sizeof($r) == 2) return $ret; } else { _debug("invalid state found, nothing called for event ".$event.""); } } } diff --git a/core/jaxl_logger.php b/core/jaxl_logger.php index b871262..c2d1d08 100644 --- a/core/jaxl_logger.php +++ b/core/jaxl_logger.php @@ -1,89 +1,109 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // log level define('JAXL_ERROR', 1); define('JAXL_WARNING', 2); define('JAXL_NOTICE', 3); define('JAXL_INFO', 4); define('JAXL_DEBUG', 5); // generic global logging shortcuts for different level of verbosity -function _error($msg) { JAXLLogger::log($msg, JAXL_ERROR); } -function _warning($msg) { JAXLLogger::log($msg, JAXL_WARNING); } -function _notice($msg) { JAXLLogger::log($msg, JAXL_NOTICE); } -function _info($msg) { JAXLLogger::log($msg, JAXL_INFO); } -function _debug($msg) { JAXLLogger::log($msg, JAXL_DEBUG); } +function _error($msg) +{ + JAXLLogger::log($msg, JAXL_ERROR); +} +function _warning($msg) +{ + JAXLLogger::log($msg, JAXL_WARNING); +} +function _notice($msg) +{ + JAXLLogger::log($msg, JAXL_NOTICE); +} +function _info($msg) +{ + JAXLLogger::log($msg, JAXL_INFO); +} +function _debug($msg) +{ + JAXLLogger::log($msg, JAXL_DEBUG); +} // generic global terminal output colorize method // finally sends colorized message to terminal using error_log/1 // this method is mainly to escape $msg from file:line and time // prefix done by _debug, _error, ... methods -function _colorize($msg, $verbosity) { error_log(JAXLLogger::colorize($msg, $verbosity)); } +function _colorize($msg, $verbosity) +{ + error_log(JAXLLogger::colorize($msg, $verbosity)); +} class JAXLLogger { public static $level = JAXL_DEBUG; public static $path = null; public static $max_log_size = 1000; protected static $colors = array( 1 => 31, // error: red 2 => 34, // warning: blue 3 => 33, // notice: yellow 4 => 32, // info: green 5 => 37 // debug: white ); - public static function log($msg, $verbosity = 1) { + public static function log($msg, $verbosity = 1) + { if ($verbosity <= self::$level) { $bt = debug_backtrace(); array_shift($bt); $callee = array_shift($bt); $msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg; $size = strlen($msg); if ($size > self::$max_log_size) $msg = substr($msg, 0, self::$max_log_size) . ' ...'; if (isset(self::$path)) error_log($msg . PHP_EOL, 3, self::$path); else error_log(self::colorize($msg, $verbosity)); } } - public static function colorize($msg, $verbosity) { + public static function colorize($msg, $verbosity) + { return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m"; } } diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index 1c3f8f1..316155a 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,154 +1,163 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLLoop { public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; - private function __construct() {} - private function __clone() {} + private function __construct() + { + } + + private function __clone() + { + } - public static function watch($fd, $opts) { + public static function watch($fd, $opts) + { if (isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } if (isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } - public static function unwatch($fd, $opts) { + public static function unwatch($fd, $opts) + { if (isset($opts['read'])) { $fdid = (int) $fd; if (isset(self::$read_fds[$fdid])) { unset(self::$read_fds[$fdid]); unset(self::$read_cbs[$fdid]); --self::$active_read_fds; } } if (isset($opts['write'])) { $fdid = (int) $fd; if (isset(self::$write_fds[$fdid])) { unset(self::$write_fds[$fdid]); unset(self::$write_cbs[$fdid]); --self::$active_write_fds; } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } - public static function run() { + public static function run() + { if (!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); while ((self::$active_read_fds + self::$active_write_fds) > 0) self::select(); _debug("no more active fd's to select"); self::$is_running = false; } } - private static function select() { + private static function select() + { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); if ($changed === false) { _error("error in the event loop, shutting down..."); /*foreach (self::$read_fds as $fd) { if (is_resource($fd)) print_r(stream_get_meta_data($fd)); }*/ exit; } else if ($changed > 0) { // read callback foreach ($read as $r) { $fdid = array_search($r, self::$read_fds); if (isset(self::$read_fds[$fdid])) call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); } // write callback foreach ($write as $w) { $fdid = array_search($w, self::$write_fds); if (isset(self::$write_fds[$fdid])) call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); } self::$clock->tick(); } else if ($changed === 0) { //_debug("nothing changed while selecting for read"); self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); } } } diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php index 2188e68..e10f937 100644 --- a/core/jaxl_pipe.php +++ b/core/jaxl_pipe.php @@ -1,110 +1,115 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * bidirectional communication pipes for processes * * This is how this will be (when complete): * $pipe = new JAXLPipe() will return an array of size 2 * $pipe[0] represents the read end of the pipe * $pipe[1] represents the write end of the pipe * * Proposed functionality might even change (currently consider this as experimental) * * @author abhinavsingh * */ class JAXLPipe { protected $perm = 0600; protected $recv_cb = null; protected $fd = null; protected $client = null; public $name = null; - public function __construct($name, $read_cb = null) { + public function __construct($name, $read_cb = null) + { $pipes_folder = JAXL_CWD.'/.jaxl/pipes'; if (!is_dir($pipes_folder)) mkdir($pipes_folder); $this->ev = new JAXLEvent(); $this->name = $name; $this->read_cb = $read_cb; $pipe_path = $this->get_pipe_file_path(); if (!file_exists($pipe_path)) { posix_mkfifo($pipe_path, $this->perm); $this->fd = fopen($pipe_path, 'r+'); if (!$this->fd) { _error("unable to open pipe"); } else { _debug("pipe opened using path $pipe_path"); _notice("Usage: $ echo 'Hello World!' > $pipe_path"); $this->client = new JAXLSocketClient(); $this->client->connect($this->fd); $this->client->set_callback(array(&$this, 'on_data')); } } else { _error("pipe with name $name already exists"); } } - public function __destruct() { + public function __destruct() + { @fclose($this->fd); @unlink($this->get_pipe_file_path()); _debug("unlinking pipe file"); } - public function get_pipe_file_path() { + public function get_pipe_file_path() + { return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe'; } - public function set_callback($recv_cb) { + public function set_callback($recv_cb) + { $this->recv_cb = $recv_cb; } - public function on_data($data) { + public function on_data($data) + { // callback if ($this->recv_cb) call_user_func($this->recv_cb, $data); } } diff --git a/core/jaxl_sock5.php b/core/jaxl_sock5.php index 8493133..7322664 100644 --- a/core/jaxl_sock5.php +++ b/core/jaxl_sock5.php @@ -1,124 +1,132 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ class JAXLSock5 { private $client = null; protected $transport = null; protected $ip = null; protected $port = null; - public function __construct($transport = 'tcp') { + public function __construct($transport = 'tcp') + { $this->transport = $transport; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } - public function __destruct() { + public function __destruct() + { } - public function connect($ip, $port = 1080) { + public function connect($ip, $port = 1080) + { $this->ip = $ip; $this->port = $port; $sock_path = $this->_sock_path(); if ($this->client->connect($sock_path)) { _debug("established connection to $sock_path"); return true; } else { _error("unable to connect $sock_path"); return false; } } // // Three phases of SOCK5 // // Negotiation pkt consists of 3 part: // 0x05 => Sock protocol version // 0x01 => Number of method identifier octet // // Following auth methods are defined: // 0x00 => No authentication required // 0x01 => GSSAPI // 0x02 => USERNAME/PASSWORD // 0x03 to 0x7F => IANA ASSIGNED // 0x80 to 0xFE => RESERVED FOR PRIVATE METHODS // 0xFF => NO ACCEPTABLE METHODS - public function negotiate() { + public function negotiate() + { $pkt = pack("C3", 0x05, 0x01, 0x00); $this->client->send($pkt); // enter sub-negotiation state } - public function relay_request() { + public function relay_request() + { // enter wait for reply state } - public function send_data() { + public function send_data() + { } // // Socket client callback // - public function on_response($raw) { + public function on_response($raw) + { _debug($raw); } // // Private // - protected function _sock_path() { + protected function _sock_path() + { return $this->transport.'://'.$this->ip.':'.$this->port; } } diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index bc2fb6b..78c96d1 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,214 +1,224 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; - public function __construct($stream_context = null) { + public function __construct($stream_context = null) + { $this->stream_context = $stream_context; } - public function __destruct() { + public function __destruct() + { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } - public function set_callback($recv_cb) { + public function set_callback($recv_cb) + { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ - public function connect($socket_path) { + public function connect($socket_path) + { if (gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); if (sizeof($path_parts) == 3) $this->port = $path_parts[2]; _info("trying ".$socket_path); if ($this->stream_context) $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); else $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); } else { $this->fd = &$socket_path; } if ($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); $this->disconnect(); return false; } } - public function disconnect() { + public function disconnect() + { JAXLLoop::unwatch($this->fd, array( 'read' => true, 'write' => true )); @fclose($this->fd); $this->fd = null; } - public function compress() { + public function compress() + { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } - public function crypt() { + public function crypt() + { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); return $ret; } - public function send($data) { + public function send($data) + { $this->obuffer .= $data; // add watch for write events if ($this->writing) return; JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } - public function on_read_ready($fd) { + public function on_read_ready($fd) + { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if ($bytes === 0) { $meta = stream_get_meta_data($fd); if ($meta['eof'] === TRUE) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); if ($bytes > 0) _debug($raw); // callback if ($this->recv_cb) call_user_func($this->recv_cb, $raw); } - public function on_write_ready($fd) { + public function on_write_ready($fd) + { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if (strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } } diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index 7c447cf..d1747cf 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,250 +1,262 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLSocketServer { public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; - public function __construct($path, $accept_cb, $request_cb) { + public function __construct($path, $accept_cb, $request_cb) + { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; $ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog))); if (($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { if (@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); } else { _error("unable to set non block flag"); } } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } - public function __destruct() { + public function __destruct() + { _info("shutting down socket server"); } - public function read($client_id) { + public function read($client_id) + { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } - public function send($client_id, $data) { + public function send($client_id, $data) + { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } - public function close($client_id) { + public function close($client_id) + { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } - public function on_server_accept_ready($server) { + public function on_server_accept_ready($server) + { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); if (!$client) { _error("unable to accept new client conn"); return; } if (@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do if ($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); } // if no accept callback is registered // close the accepted connection else { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } } else { _error("unable to set non block flag"); } } - public function on_client_read_ready($client) { + public function on_client_read_ready($client) + { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); if ($bytes === 0) { $meta = stream_get_meta_data($client); if ($meta['eof'] === TRUE) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); @fclose($client); unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; if ($this->request_cb) call_user_func($this->request_cb, $client_id, $total); $this->clients[$client_id]['ibuffer'] = ''; } - public function on_client_write_ready($client) { + public function on_client_write_ready($client) + { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); if ($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; } else if ($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler if (strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } } catch(JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // - protected function add_read_cb($client_id) { + protected function add_read_cb($client_id) + { if ($this->clients[$client_id]['reading']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } - protected function add_write_cb($client_id) { + protected function add_write_cb($client_id) + { if ($this->clients[$client_id]['writing']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } - protected function del_read_cb($client_id) { + protected function del_read_cb($client_id) + { if (!$this->clients[$client_id]['reading']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } - protected function del_write_cb($client_id) { + protected function del_write_cb($client_id) + { if (!$this->clients[$client_id]['writing']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } } diff --git a/core/jaxl_util.php b/core/jaxl_util.php index ffe5aac..add9bc4 100644 --- a/core/jaxl_util.php +++ b/core/jaxl_util.php @@ -1,64 +1,67 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh * */ class JAXLUtil { - public static function get_nonce($binary = true) { + public static function get_nonce($binary = true) + { $nce = ''; mt_srand((double) microtime()*10000000); for ($i = 0; $i<32; $i++) $nce .= chr(mt_rand(0, 255)); return $binary ? $nce : base64_encode($nce); } - public static function get_dns_srv($domain) { + public static function get_dns_srv($domain) + { $rec = dns_get_record("_xmpp-client._tcp.".$domain, DNS_SRV); if (is_array($rec)) { if (sizeof($rec) == 0) return array($domain, 5222); if (sizeof($rec) > 0) return array($rec[0]['target'], $rec[0]['port']); } } - public static function pbkdf2($data, $secret, $iteration, $dkLen = 32, $algo = 'sha1') { + public static function pbkdf2($data, $secret, $iteration, $dkLen = 32, $algo = 'sha1') + { return ''; } } diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index 4b7ba34..f4a2e12 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,191 +1,203 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; - public function __construct() { + public function __construct() + { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if (is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if (is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if (is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } - public function __destruct() { + public function __destruct() + { } - public function attrs($attrs) { + public function attrs($attrs) + { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } - public function match_attrs($attrs) { + public function match_attrs($attrs) + { $matches = true; foreach ($attrs as $k => $v) { if ($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } - public function t($text, $append = FALSE) { + public function t($text, $append = FALSE) + { if (!$append) { $this->rover->text = $text; } else { if ($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; } return $this; } - public function c($name, $ns = null, $attrs = array(), $text = null) { + public function c($name, $ns = null, $attrs = array(), $text = null) + { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } - public function cnode($node) { + public function cnode($node) + { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } - public function up() { + public function up() + { if ($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } - public function top() { + public function top() + { $this->rover = &$this; return $this; } - public function exists($name, $ns = null, $attrs = array()) { + public function exists($name, $ns = null, $attrs = array()) + { foreach ($this->childrens as $child) { if ($ns) { if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; } else if ($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } - public function update($name, $ns = null, $attrs = array(), $text = null) { + public function update($name, $ns = null, $attrs = array(), $text = null) + { foreach ($this->childrens as $k => $child) { if ($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } - public function to_string($parent_ns = null) { + public function to_string($parent_ns = null) + { $xml = ''; $xml .= '<'.$this->name; if ($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; foreach ($this->attrs as $k => $v) if (!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; foreach ($this->childrens as $child) $xml .= $child->to_string($this->ns); if ($this->text) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } } diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php index d3b4766..33ae2ff 100644 --- a/core/jaxl_xml_stream.php +++ b/core/jaxl_xml_stream.php @@ -1,184 +1,196 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Enter description here ... * @author abhinavsingh * */ class JAXLXmlStream { private $delimiter = '\\'; private $ns; private $parser; private $stanza; private $depth = -1; private $start_cb; private $stanza_cb; private $end_cb; - public function __construct() { + public function __construct() + { $this->init_parser(); } - private function init_parser() { + private function init_parser() + { $this->depth = -1; $this->parser = xml_parser_create_ns("UTF-8", $this->delimiter); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); xml_set_character_data_handler($this->parser, array(&$this, "handle_character")); xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag")); } - public function __destruct() { + public function __destruct() + { //_debug("cleaning up xml parser..."); @xml_parser_free($this->parser); } - public function reset_parser() { + public function reset_parser() + { $this->parse_final(null); @xml_parser_free($this->parser); $this->parser = null; $this->init_parser(); } - public function set_callback($start_cb, $end_cb, $stanza_cb) { + public function set_callback($start_cb, $end_cb, $stanza_cb) + { $this->start_cb = $start_cb; $this->end_cb = $end_cb; $this->stanza_cb = $stanza_cb; } - public function parse($str) { + public function parse($str) + { xml_parse($this->parser, $str, false); } - public function parse_final($str) { + public function parse_final($str) + { xml_parse($this->parser, $str, true); } - protected function handle_start_tag($parser, $name, $attrs) { + protected function handle_start_tag($parser, $name, $attrs) + { $name = $this->explode($name); //echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL; // replace ns with prefix foreach ($attrs as $key => $v) { $k = $this->explode($key); // no ns specified if ($k[0] == null) { $attrs[$k[1]] = $v; } // xml ns else if ($k[0] == NS_XML) { unset($attrs[$key]); $attrs['xml:'.$k[1]] = $v; } else { _error("==================> unhandled ns prefix on attribute"); // remove attribute else will cause error with bad stanza format // report to developer if above error message is ever encountered unset($attrs[$key]); } } if ($this->depth <= 0) { $this->depth = 0; $this->ns = $name[1]; if ($this->start_cb) { $stanza = new JAXLXml($name[1], $name[0], $attrs); call_user_func($this->start_cb, $stanza); } } else { if (!$this->stanza) { $stanza = new JAXLXml($name[1], $name[0], $attrs); $this->stanza = &$stanza; } else { $this->stanza->c($name[1], $name[0], $attrs); } } ++$this->depth; } - protected function handle_end_tag($parser, $name) { + protected function handle_end_tag($parser, $name) + { $name = explode($this->delimiter, $name); $name = sizeof($name) == 1 ? array('', $name[0]) : $name; //echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL; if ($this->depth == 1) { if ($this->end_cb) { $stanza = new JAXLXml($name[1], $this->ns); call_user_func($this->end_cb, $stanza); } } else if ($this->depth > 1) { if ($this->stanza) $this->stanza->up(); if ($this->depth == 2) { if ($this->stanza_cb) { call_user_func($this->stanza_cb, $this->stanza); $this->stanza = null; } } } --$this->depth; } - protected function handle_character($parser, $data) { + protected function handle_character($parser, $data) + { //echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL; if ($this->stanza) { $this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), TRUE); } } - private function implode($data) { + private function implode($data) + { return implode($this->delimiter, $data); } - private function explode($data) { + private function explode($data) + { $data = explode($this->delimiter, $data); $data = sizeof($data) == 1 ? array(null, $data[0]) : $data; return $data; } } diff --git a/docs/users/cron_jobs.rst b/docs/users/cron_jobs.rst index 6b57904..bae1936 100644 --- a/docs/users/cron_jobs.rst +++ b/docs/users/cron_jobs.rst @@ -1,61 +1,62 @@ Cron Jobs ========= ``JAXLClock`` maintains a global clock which is updated after every iteration of the :ref:`main select loop <jaxl-instance>`. During the clock tick phase, ``JAXLClock`` also dispatches any scheduled cron jobs. Lets try some cron job scheduling using Jaxl interactive shell: >>> ./jaxlctl shell jaxl 1> - jaxl 1> function do_job($params) { + jaxl 1> function do_job($params) + ....... { ....... echo "cron job called"; ....... } jaxl 2> jaxl 2> $ref = JAXLLoop::$clock->call_fun_after( ....... 4000, ....... 'do_job', ....... 'some_parameters' ....... ); jaxl 3> echo $ref; 1 jaxl 4> cron job called jaxl 5> quit >>> We just saw a live example of a cron job. Using ``JAXLClock::call_fun_after/3`` we were able to call our ``do_job`` function after 4000 microseconds. .. note:: Since cron jobs are called inside main select loop, do not execute long running cron jobs using ``JAXLClock`` else the main select loop will not be able to detect any new activity on watched file descriptors. In short, these cron job callbacks are blocking. In future, cron jobs might get executed in a seperate process space, overcoming the above limitation. Until then know what your jobs are doing and for how long or execute them in a seperate process space yourself. You have been warned !!! one time jobs ------------- ``call_fun_after($time, $callback, $args)`` schedules $callback with $args after $time microseconds periodic jobs ------------- ``call_fun_periodic($time, $callback, $args)`` schedules periodic $callback with $args after $time microseconds cancel a job ------------ ``cancel_fun_call($ref)`` cancels a previously scheduled $callback detecting bottlenecks --------------------- ``tc($callback, $args)`` calculate execution time of a $callback with $args diff --git a/docs/users/http_examples.rst b/docs/users/http_examples.rst index 990fd05..af515bb 100644 --- a/docs/users/http_examples.rst +++ b/docs/users/http_examples.rst @@ -1,99 +1,102 @@ HTTP Examples ============= Writing HTTP Server ------------------- Intialize an ``HTTPServer`` instance .. code-block:: ruby require_once 'jaxl.php'; require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this. Define a callback method that will accept all incoming ``HTTPRequest`` objects .. code-block:: ruby - function on_request($request) { + function on_request($request) + { if ($request->method == 'GET') { $body = json_encode($request); $request->ok($body, array('Content-Type' => 'application:json')); } else { $request->not_found(); } } ``on_request`` callback method will receive a ``HTTPRequest`` object instance. For this example, we will simply echo back json encoded ``$request`` object for every http GET request. Start http server: .. code-block:: ruby $http->start('on_request'); We pass ``on_request`` method as first parameter to ``HTTPServer::start/1``. If nothing is passed, requests will fail with a default 404 not found error message Writing REST API Server ----------------------- Intialize an ``HTTPServer`` instance .. code-block:: ruby require_once 'jaxl.php'; require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this. Define our REST resources callback methods: .. code-block:: ruby - function index($request) { + function index($request) + { $request->send_response( 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } - function upload($request) { + function upload($request) + { if ($request->method == 'GET') { $request->send_response( 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action=""><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' ); } else if ($request->method == 'POST') { if ($request->body === null && $request->expect) { $request->recv_body(); } else { // got upload body, save it _debug("file upload complete, got ".strlen($request->body)." bytes of data"); $request->close(); } } } Next we need to register dispatch rules for our callbacks above: .. code-block:: ruby $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); $rules = array($index, $upload); $http->dispatch($rules); Start REST api server: .. code-block:: ruby $http->start(); Make an HTTP request -------------------- diff --git a/examples/echo_http_server.php b/examples/echo_http_server.php index e2c3902..0ad9d31 100644 --- a/examples/echo_http_server.php +++ b/examples/echo_http_server.php @@ -1,58 +1,59 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // print usage notice and parse addr/port parameters if passed _colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE); $port = ($argc == 2 ? $argv[1] : 9699); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer($port); // catch all incoming requests here -function on_request($request) { +function on_request($request) +{ $body = json_encode($request); $request->ok($body, array('Content-Type' => 'application/json')); } // start http server $http->start('on_request'); diff --git a/examples/echo_unix_sock_server.php b/examples/echo_unix_sock_server.php index 0b939a5..69e5908 100644 --- a/examples/echo_unix_sock_server.php +++ b/examples/echo_unix_sock_server.php @@ -1,59 +1,60 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 2) { echo "Usage: $argv[0] /path/to/server.sock\n"; exit; } require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; $server = null; -function on_request($client, $raw) { +function on_request($client, $raw) +{ global $server; $server->send($client, $raw); _info("got client callback ".$raw); } @unlink($argv[1]); $server = new JAXLSocketServer('unix://'.$argv[1], NULL, 'on_request'); JAXLLoop::run(); echo "done\n"; diff --git a/examples/http_rest_server.php b/examples/http_rest_server.php index 7f32dc1..de1aa63 100644 --- a/examples/http_rest_server.php +++ b/examples/http_rest_server.php @@ -1,115 +1,121 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // print usage notice and parse addr/port parameters if passed _colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE); $port = ($argc == 2 ? $argv[1] : 9699); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer($port); // callback method for dispatch rule (see below) -function index($request) { +function index($request) +{ $request->send_response( 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } // callback method for dispatch rule (see below) -function upload($request) { +function upload($request) +{ if ($request->method == 'GET') { $request->ok(array( 'Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' ); } else if ($request->method == 'POST') { if ($request->body === null && $request->expect) { $request->recv_body(); } else { // got upload body, save it _info("file upload complete, got ".strlen($request->body)." bytes of data"); $upload_data = $request->multipart->form_data[0]['body']; $request->ok($upload_data, array('Content-Type' => $request->multipart->form_data[0]['headers']['Content-Type'])); } } } // add dispatch rules with callback method as first argument $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); // some REST CRUD style callback methods // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules -function create_event($request) { +function create_event($request) +{ _info("got event create request"); $request->close(); } -function read_event($request, $pk) { +function read_event($request, $pk) +{ _info("got event read request for $pk"); $request->close(); } -function update_event($request, $pk) { +function update_event($request, $pk) +{ _info("got event update request for $pk"); $request->close(); } -function delete_event($request, $pk) { +function delete_event($request, $pk) +{ _info("got event delete request for $pk"); $request->close(); } $event_create = array('create_event', '^/event/create/$', array('PUT')); $event_read = array('read_event', '^/event/(?P<pk>\d+)/$', array('GET', 'HEAD')); $event_update = array('update_event', '^/event/(?P<pk>\d+)/$', array('POST')); $event_delete = array('delete_event', '^/event/(?P<pk>\d+)/$', array('DELETE')); // prepare rule set $rules = array($index, $upload, $event_create, $event_read, $event_update, $event_delete); $http->dispatch($rules); // start http server $http->start(); diff --git a/examples/multi_client.php b/examples/multi_client.php index 4208b51..8bc4057 100644 --- a/examples/multi_client.php +++ b/examples/multi_client.php @@ -1,127 +1,132 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // enable multi client support // this will force 1st parameter of callbacks // as connected client instance define('JAXL_MULTI_CLIENT', true); // input multiple account credentials $accounts = array(); $add_new = TRUE; while ($add_new) { $jid = readline('Enter Jabber Id: '); $pass = readline('Enter Password: '); $accounts[] = array($jid, $pass); $next = readline('Add another account (y/n): '); $add_new = $next == 'y' ? TRUE : FALSE; } // setup jaxl require_once 'jaxl.php'; // // common callbacks // -function on_auth_success($client) { +function on_auth_success($client) +{ _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // fetch roster list $client->get_roster(); // fetch vcard $client->get_vcard(); // set status $client->set_status("available!", "dnd", 10); } -function on_auth_failure($client, $reason) { +function on_auth_failure($client, $reason) +{ _info("got on_auth_failure cb with reason $reason"); $client->send_end_stream(); } -function on_chat_message($client, $stanza) { +function on_chat_message($client, $stanza) +{ // echo back incoming chat message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); } -function on_presence_stanza($client, $stanza) { +function on_presence_stanza($client, $stanza) +{ global $client; $type = ($stanza->type ? $stanza->type : "available"); $show = ($stanza->show ? $stanza->show : "???"); _info($stanza->from." is now ".$type." ($show)"); if ($type == "available") { // fetch vcard $client->get_vcard($stanza->from); } } -function on_disconnect($client) { +function on_disconnect($client) +{ _info("got on_disconnect cb"); } // // bootstrap all account instances // foreach ($accounts as $account) { $client = new JAXL(array( 'jid' => $account[0], 'pass' => $account[1], 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', 'on_auth_success'); $client->add_cb('on_auth_failure', 'on_auth_failure'); $client->add_cb('on_chat_message', 'on_chat_message'); $client->add_cb('on_presence_stanza', 'on_presence_stanza'); $client->add_cb('on_disconnect', 'on_disconnect'); $client->connect($client->get_socket_path()); $client->start_stream(); } // start core loop JAXLLoop::run(); echo "done\n"; diff --git a/examples/register_user.php b/examples/register_user.php index 480cfac..a035f63 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,164 +1,166 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // $form = array(); -function wait_for_register_response($event, $args) { +function wait_for_register_response($event, $args) +{ global $client, $form; if ($event == 'stanza_cb') { $stanza = $args[0]; if ($stanza->name == 'iq') { $form['type'] = $stanza->attrs['type']; if ($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } else if ($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } } } else { _notice("unhandled event $event rcvd"); } } -function wait_for_register_form($event, $args) { +function wait_for_register_form($event, $args) +{ global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if ($query) { $instructions = $query->exists('instructions'); if ($instructions) { echo $instructions->text.PHP_EOL; } foreach ($query->childrens as $k => $child) { if ($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // $client->add_cb('on_stream_features', function($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; }); $client->add_cb('on_disconnect', function() { global $form; _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); }); // // finally start configured xmpp stream // $client->start(); // // if registration was successful // try to connect with newly registered account // if ($form['type'] == 'result') { _info("connecting newly registered user account"); $client = new JAXL(array( 'jid' => $form['username'].'@'.$argv[1], 'pass' => $form['password'], 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', function() { global $client; $client->set_status('Available'); }); $client->start(); } echo "done\n"; diff --git a/http/http_client.php b/http/http_client.php index ad4adc1..5032704 100644 --- a/http/http_client.php +++ b/http/http_client.php @@ -1,134 +1,145 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ class HTTPClient { private $url = null; private $parts = array(); private $headers = array(); private $data = null; public $method = null; private $client = null; - public function __construct($url, $headers = array(), $data = null) { + public function __construct($url, $headers = array(), $data = null) + { $this->url = $url; $this->headers = $headers; $this->data = $data; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } - public function start($method = 'GET') { + public function start($method = 'GET') + { $this->method = $method; $this->parts = parse_url($this->url); $transport = $this->_transport(); $ip = $this->_ip(); $port = $this->_port(); $socket_path = $transport.'://'.$ip.':'.$port; if ($this->client->connect($socket_path)) { _debug("connection to $this->url established"); // send request data $this->send_request(); // start main loop JAXLLoop::run(); } else { _debug("unable to open $this->url"); } } - public function on_response($raw) { + public function on_response($raw) + { _info("got http response"); } - protected function send_request() { + protected function send_request() + { $this->client->send($this->_line()."\r\n"); $this->client->send($this->_ua()."\r\n"); $this->client->send($this->_host()."\r\n"); $this->client->send("\r\n"); } // // private methods on uri parts // - private function _line() { + private function _line() + { return $this->method.' '.$this->_uri().' HTTP/1.1'; } - private function _ua() { + private function _ua() + { return 'User-Agent: jaxl_http_client/3.x'; } - private function _host() { + private function _host() + { return 'Host: '.$this->parts['host'].':'.$this->_port(); } - private function _transport() { + private function _transport() + { return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl'); } - private function _ip() { + private function _ip() + { return gethostbyname($this->parts['host']); } - private function _port() { + private function _port() + { return @$this->parts['port'] ? $this->parts['port'] : 80; } - private function _uri() { + private function _uri() + { $uri = $this->parts['path']; if (@$this->parts['query']) $uri .= '?'.$this->parts['query']; if (@$this->parts['fragment']) $uri .= '#'.$this->parts['fragment']; return $uri; } } diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php index be14f31..4030b5c 100644 --- a/http/http_dispatcher.php +++ b/http/http_dispatcher.php @@ -1,117 +1,122 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // // (optionally) set an array of url dispatch rules // each dispatch rule is defined by an array of size 4 like: // array($callback, $pattern, $methods, $extra), where // $callback the method which will be called if this rule matches // $pattern regular expression to match request path // $methods list of allowed methods for this rule // pass boolean true to allow all http methods // if omitted or an empty array() is passed (which actually doesnt make sense) // by default 'GET' will be the method allowed on this rule // $extra reserved for future (you can totally omit this as of now) // class HTTPDispatchRule { // match callback public $cb = null; // regexp to match on request path public $pattern = null; // methods to match upon // add atleast 1 method for this rule to work public $methods = null; // other matching rules public $extra = array(); - public function __construct($cb, $pattern, $methods = array('GET'), $extra = array()) { + public function __construct($cb, $pattern, $methods = array('GET'), $extra = array()) + { $this->cb = $cb; $this->pattern = $pattern; $this->methods = $methods; $this->extra = $extra; } - public function match($path, $method) { + public function match($path, $method) + { if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) { if (in_array($method, $this->methods)) { return $matches; } } return false; } } class HTTPDispatcher { protected $rules = array(); - public function __construct() { + public function __construct() + { $this->rules = array(); } - public function add_rule($rule) { + public function add_rule($rule) + { $s = sizeof($rule); if ($s > 4) { _debug("invalid rule"); return; } // fill up defaults if ($s == 3) { $rule[] = array(); } else if ($s == 2) { $rule[] = array('GET'); $rule[] = array(); } else { _debug("invalid rule"); return; } $this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]); } - public function dispatch($request) { + public function dispatch($request) + { foreach ($this->rules as $rule) { //_debug("matching $request->path with pattern $rule->pattern"); if (($matches = $rule->match($request->path, $request->method)) !== false) { _debug("matching rule found, dispatching"); $params = array($request); // TODO: a bad way to restrict on 'pk', fix me for generalization if (@isset($matches['pk'])) $params[] = $matches['pk']; call_user_func_array($rule->cb, $params); return true; } } return false; } } diff --git a/http/http_multipart.php b/http/http_multipart.php index 7a0b5c5..3f44820 100644 --- a/http/http_multipart.php +++ b/http/http_multipart.php @@ -1,161 +1,170 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; class HTTPMultiPart extends JAXLFsm { public $boundary = null; public $form_data = array(); public $index = -1; - public function handle_invalid_state($r) { + public function handle_invalid_state($r) + { _error("got invalid event $r"); } - public function __construct($boundary) { + public function __construct($boundary) + { $this->boundary = $boundary; parent::__construct('wait_for_boundary_start'); } - public function state() { + public function state() + { return $this->state; } - public function wait_for_boundary_start($event, $data) { + public function wait_for_boundary_start($event, $data) + { if ($event == 'process') { if ($data[0] == '--'.$this->boundary) { $this->index += 1; $this->form_data[$this->index] = array( 'meta' => array(), 'headers' => array(), 'body' => '' ); return array('wait_for_content_disposition', true); } else { _warning("invalid boundary start $data[0] while expecting $this->boundary"); return array('wait_for_boundary_start', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_boundary_start', false); } } - public function wait_for_content_disposition($event, $data) { + public function wait_for_content_disposition($event, $data) + { if ($event == 'process') { $disposition = explode(":", $data[0]); if (strtolower(trim($disposition[0])) == 'content-disposition') { $this->form_data[$this->index]['headers'][$disposition[0]] = trim($disposition[1]); $meta = explode(";", $disposition[1]); if (trim(array_shift($meta)) == 'form-data') { foreach ($meta as $k) { list($k, $v) = explode("=", $k); $this->form_data[$this->index]['meta'][$k] = $v; } return array('wait_for_content_type', true); } else { _warning("first part of meta is not form-data"); return array('wait_for_content_disposition', false); } } else { _warning("not a valid content-disposition line"); return array('wait_for_content_disposition', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_disposition', false); } } - public function wait_for_content_type($event, $data) { + public function wait_for_content_type($event, $data) + { if ($event == 'process') { $type = explode(":", $data[0]); if (strtolower(trim($type[0])) == 'content-type') { $this->form_data[$this->index]['headers'][$type[0]] = trim($type[1]); $this->form_data[$this->index]['meta']['type'] = $type[1]; return array('wait_for_content_body', true); } else { _debug("not a valid content-type line"); return array('wait_for_content_type', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_type', false); } } - public function wait_for_content_body($event, $data) { + public function wait_for_content_body($event, $data) + { if ($event == 'process') { if ($data[0] == '--'.$this->boundary) { _debug("start of new multipart/form-data detected"); return array('wait_for_content_disposition', true); } else if ($data[0] == '--'.$this->boundary.'--') { _debug("end of multipart form data detected"); return array('wait_for_empty_line', true); } else { $this->form_data[$this->index]['body'] .= $data[0]; return array('wait_for_content_body', true); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_body', false); } } - public function wait_for_empty_line($event, $data) { + public function wait_for_empty_line($event, $data) + { if ($event == 'process') { if ($data[0] == '') { return array('done', true); } else { _warning("invalid empty line $data[0] received"); return array('wait_for_empty_line', false); } } else { _warning("got $event in done state with data $data[0]"); return array('wait_for_empty_line', false); } } - public function done($event, $data) { + public function done($event, $data) + { _warning("got unhandled event $event with data $data[0]"); return array('done', false); } } diff --git a/http/http_request.php b/http/http_request.php index 9a60fe1..2c24a19 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,479 +1,502 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers = array(), $body = null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); - public function __construct($sock, $addr) { + public function __construct($sock, $addr) + { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if (sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } - public function __destruct() { + public function __destruct() + { _debug("http request going down in ".$this->state." state"); } - public function state() { + public function state() + { return $this->state; } // // abstract method implementation // - public function handle_invalid_state($r) { + public function handle_invalid_state($r) + { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // - public function setup($event, $args) { + public function setup($event, $args) + { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } - public function wait_for_request_line($event, $args) { + public function wait_for_request_line($event, $args) + { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } - public function wait_for_headers($event, $args) { + public function wait_for_headers($event, $args) + { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } - public function maybe_headers_received($event, $args) { + public function maybe_headers_received($event, $args) + { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } - public function wait_for_body($event, $args) { + public function wait_for_body($event, $args) + { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; if ($this->body === null) $this->body = $rcvd; else $this->body .= $rcvd; if ($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach ($form_data as $data) { //_debug("passing $data to multipart fsm"); if (!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if (!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if (!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received - public function headers_received($event, $args) { + public function headers_received($event, $args) + { switch($event) { case 'empty_line': return 'headers_received'; break; default: if (substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if (method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } } else if (@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } - public function closed($event, $args) { + public function closed($event, $args) + { _warning("uncatched $event"); } // sets input headers // called internally for every header received - protected function set_header($k, $v) { + protected function set_header($k, $v) + { $k = trim($k); $v = ltrim($v); // is expect header? if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if (strtolower($k) == 'content-type') { $ctype = explode(';', $v); if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if (strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler - protected function handle_shortcut($event, $args) { + protected function handle_shortcut($event, $args) + { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if ($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } - private function parse_shortcut_args($args) { + private function parse_shortcut_args($args) + { if (sizeof($args) == 0) { $body = null; $headers = array(); } if (sizeof($args) == 1) { // http headers or body only received if (is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } } else if (sizeof($args) == 2) { // body and http headers both received if (is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // - protected function _send_line($code) { + protected function _send_line($code) + { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } - protected function _send_header($k, $v) { + protected function _send_header($k, $v) + { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } - protected function _send_headers($code, $headers) { + protected function _send_headers($code, $headers) + { foreach ($headers as $k => $v) $this->_send_header($k, $v); } - protected function _send_body($body) { + protected function _send_body($body) + { $this->_send($body); } - protected function _send_response($code, $headers = array(), $body = null) { + protected function _send_response($code, $headers = array(), $body = null) + { // send out response line $this->_send_line($code); // set content length of body exists and is not already set if ($body && !isset($headers['Content-Length'])) $headers['Content-Length'] = strlen($body); // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); if ($body) $this->_send_body(HTTP_CRLF.$body); } // // internal methods // // initializes status line elements - private function _line($method, $resource, $version) { + private function _line($method, $resource, $version) + { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if (sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach ($query as $q) { $q = explode("=", $q); if (sizeof($q) == 1) $q[1] = ""; $this->query[$q[0]] = $q[1]; } } $this->version = $version; } - private function _send($raw) { + private function _send($raw) + { call_user_func($this->_send_cb, $this->sock, $raw); } - private function _read() { + private function _read() + { call_user_func($this->_read_cb, $this->sock); } - private function _close() { + private function _close() + { call_user_func($this->_close_cb, $this->sock); } } diff --git a/http/http_server.php b/http/http_server.php index 6474b00..4e9383e 100644 --- a/http/http_server.php +++ b/http/http_server.php @@ -1,192 +1,198 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/http/http_dispatcher.php'; require_once JAXL_CWD.'/http/http_request.php'; // carriage return and line feed define('HTTP_CRLF', "\r\n"); // 1xx informational define('HTTP_100', "Continue"); define('HTTP_101', "Switching Protocols"); // 2xx success define('HTTP_200', "OK"); // 3xx redirection define('HTTP_301', 'Moved Permanently'); define('HTTP_304', 'Not Modified'); // 4xx client error define('HTTP_400', 'Bad Request'); define('HTTP_403', 'Forbidden'); define('HTTP_404', 'Not Found'); define('HTTP_405', 'Method Not Allowed'); define('HTTP_499', 'Client Closed Request'); // Nginx // 5xx server error define('HTTP_500', 'Internal Server Error'); define('HTTP_503', 'Service Unavailable'); class HTTPServer { private $server = null; public $cb = null; private $dispatcher = null; private $requests = array(); - public function __construct($port = 9699, $address = "127.0.0.1") { + public function __construct($port = 9699, $address = "127.0.0.1") + { $path = 'tcp://'.$address.':'.$port; $this->server = new JAXLSocketServer( $path, array(&$this, 'on_accept'), array(&$this, 'on_request') ); $this->dispatcher = new HTTPDispatcher(); } - public function __destruct() { + public function __destruct() + { $this->server = null; } - public function dispatch($rules) { + public function dispatch($rules) + { foreach ($rules as $rule) { $this->dispatcher->add_rule($rule); } } - public function start($cb = null) { + public function start($cb = null) + { $this->cb = $cb; JAXLLoop::run(); } - public function on_accept($sock, $addr) { + public function on_accept($sock, $addr) + { _debug("on_accept for client#$sock, addr:$addr"); // initialize new request obj $request = new HTTPRequest($sock, $addr); // setup sock cb $request->set_sock_cb( array(&$this->server, 'send'), array(&$this->server, 'read'), array(&$this->server, 'close') ); // cache request object $this->requests[$sock] = &$request; // reactive client for further read $this->server->read($sock); } - public function on_request($sock, $raw) { + public function on_request($sock, $raw) + { _debug("on_request for client#$sock"); $request = $this->requests[$sock]; // 'wait_for_body' state is reached when ever // application calls recv_body() method // on received $request object if ($request->state() == 'wait_for_body') { $request->body($raw); } else { // break on crlf $lines = explode(HTTP_CRLF, $raw); // parse request line if ($request->state() == 'wait_for_request_line') { list($method, $resource, $version) = explode(" ", $lines[0]); $request->line($method, $resource, $version); unset($lines[0]); _info($request->ip." ".$request->method." ".$request->resource." ".$request->version); } // parse headers foreach ($lines as $line) { $line_parts = explode(":", $line); if (sizeof($line_parts) > 1) { if (strlen($line_parts[0]) > 0) { $k = $line_parts[0]; unset($line_parts[0]); $v = implode(":", $line_parts); $request->set_header($k, $v); } } else if (strlen(trim($line_parts[0])) == 0) { $request->empty_line(); } // if exploded line array size is 1 // and thr is something in $line_parts[0] // must be request body else { $request->body($line); } } } // if request has reached 'headers_received' state? if ($request->state() == 'headers_received') { // dispatch to any matching rule found _debug("delegating to dispatcher for further routing"); $dispatched = $this->dispatcher->dispatch($request); // if no dispatch rule matched call generic callback if (!$dispatched && $this->cb) { _debug("no dispatch rule matched, sending to generic callback"); call_user_func($this->cb, $request); } // else if not dispatched and not generic callbacked // send 404 not_found else if (!$dispatched) { // TODO: send 404 if no callback is registered for this request _debug("dropping request since no matching dispatch rule or generic callback was specified"); $request->not_found('404 Not Found'); } } // if state is not 'headers_received' // reactivate client socket for read event else { $this->server->read($sock); } } } diff --git a/jaxl.php b/jaxl.php index 1f10a7f..29060d6 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,795 +1,836 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) - public function __construct($config) { + public function __construct($config) + { $this->cfg = $config; // setup logger if (isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if (isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if ($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if (!is_dir($this->priv_dir)) mkdir($this->priv_dir); if (!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if (!is_dir($this->pid_dir)) mkdir($this->pid_dir); if (!is_dir($this->log_dir)) mkdir($this->log_dir); if (!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } - public function __destruct() { + public function __destruct() + { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } - public function add_exception_handlers() { + public function add_exception_handlers() + { _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } - public function get_pid_file_path() { + public function get_pid_file_path() + { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } - public function get_sock_file_path() { + public function get_sock_file_path() + { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } - public function require_xep($xeps) { + public function require_xep($xeps) + { if (!is_array($xeps)) $xeps = array($xeps); foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } - public function add_cb($ev, $cb, $pri = 1) { + public function add_cb($ev, $cb, $pri = 1) + { return $this->ev->add($ev, $cb, $pri); } - public function del_cb($ref) { + public function del_cb($ref) + { $this->ev->del($ref); } - public function set_status($status, $show = 'chat', $priority = 10) { + public function set_status($status, $show = 'chat', $priority = 10) + { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } - public function send_chat_msg($to, $body, $thread = null, $subject = null) { + public function send_chat_msg($to, $body, $thread = null, $subject = null) + { $msg = new XMPPMsg( array( 'type' => 'chat', 'to' => $to, 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } - public function get_vcard($jid = null, $cb = null) { + public function get_vcard($jid = null, $cb = null) + { $attrs = array( 'type' => 'get', 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } - public function get_roster($cb = null) { + public function get_roster($cb = null) + { $pkt = $this->get_iq_pkt( array( 'type' => 'get', 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } - public function subscribe($to) { + public function subscribe($to) + { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribe') )); } - public function subscribed($to) { + public function subscribed($to) + { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribed') )); } - public function unsubscribe($to) { + public function unsubscribe($to) + { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribe') )); } - public function unsubscribed($to) { + public function unsubscribed($to) + { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribed') )); } - public function get_socket_path() { + public function get_socket_path() + { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } - public function retry() { + public function retry() + { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } - public function start($opts = array()) { + public function start($opts = array()) + { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) $this->enable_debug_shell(); if (@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption - public function signal_handler($sig) { + public function signal_handler($sig) + { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption - public function on_unix_sock_accept($_c, $addr) { + public function on_unix_sock_accept($_c, $addr) + { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production - public function on_unix_sock_request($_c, $_raw) { + public function on_unix_sock_request($_c, $_raw) + { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } - public function enable_unix_sock() { + public function enable_unix_sock() + { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here - public function handle_debug_shell($_raw) { + public function handle_debug_shell($_raw) + { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } - protected function enable_debug_shell() { + protected function enable_debug_shell() + { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // - protected function send_fb_challenge_response($challenge) { + protected function send_fb_challenge_response($challenge) + { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber - public function get_fb_challenge_response_pkt($challenge) { + public function get_fb_challenge_response_pkt($challenge) + { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } - public function wait_for_fb_sasl_response($event, $args) { + public function wait_for_fb_sasl_response($event, $args) + { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream - public function wait_for_cram_md5_response($event, $args) { + public function wait_for_cram_md5_response($event, $args) + { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 - public function get_scram_sha1_response($pass, $challenge) { + public function get_scram_sha1_response($pass, $challenge) + { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } - public function wait_for_scram_sha1_response($event, $args) { + public function wait_for_scram_sha1_response($event, $args) + { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } - public function handle_auth_mechs($stanza, $mechanisms) { + public function handle_auth_mechs($stanza, $mechanisms) + { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if ($mechanisms) foreach ($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if ($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach ($mechs as $mech => $any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if ($mech == 'X-FACEBOOK-PLATFORM') { if (@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if ($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if ($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if ($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } - public function handle_auth_success() { + public function handle_auth_success() + { // if not a component /*if (!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } - public function handle_auth_failure($reason) { + public function handle_auth_failure($reason) + { $this->ev->emit('on_auth_failure', array( $reason )); } - public function handle_stream_start($stanza) { + public function handle_stream_start($stanza) + { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } - public function handle_iq($stanza) { + public function handle_iq($stanza) + { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach ($query->childrens as $child) { if ($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach ($child->childrens as $group) { if ($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if (!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if (@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if (!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } - public function handle_presence($stanza) { + public function handle_presence($stanza) + { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if ($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if ($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if ($type == 'unavailable') { if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if ($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } - public function handle_message($stanza) { + public function handle_message($stanza) + { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks - public function handle_other($event, $args) { + public function handle_other($event, $args) + { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if ($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } - public function handle_domain_info($stanza) { + public function handle_domain_info($stanza) + { $query = $stanza->exists('query', NS_DISCO_INFO); foreach ($query->childrens as $k => $child) { if ($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if ($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if ($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } - public function handle_domain_items($stanza) { + public function handle_domain_items($stanza) + { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach ($query->childrens as $k => $child) { if ($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } diff --git a/jaxlctl b/jaxlctl index 350c1c0..3a9afc6 100755 --- a/jaxlctl +++ b/jaxlctl @@ -1,183 +1,196 @@ #!/usr/bin/env php <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ $params = $argv; $exe = array_shift($params); $command = array_shift($params); require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // TODO: an abstract JAXLCtlCommand class // with seperate class per command // a mechanism to register new commands class JAXLCtl { protected $ipc = null; protected $buffer = ''; protected $buffer_cb = null; protected $cli = null; public $dots = "....... "; protected $symbols = array(); - public function __construct($command, $params) { + public function __construct($command, $params) + { global $exe; if (method_exists($this, $command)) { $r = call_user_func_array(array(&$this, $command), $params); if (sizeof($r) == 2) { list($buffer_cb, $quit_cb) = $r; $this->buffer_cb = $buffer_cb; $this->cli = new JAXLCli(array(&$this, 'on_terminal_input'), $quit_cb); $this->run(); } else { _colorize("oops! internal command error", JAXL_ERROR); exit; } } else { _colorize("error: invalid command '$command' received", JAXL_ERROR); _colorize("type '$exe help' for list of available commands", JAXL_NOTICE); exit; } } - public function run() { + public function run() + { JAXLCli::prompt(); JAXLLoop::run(); } - public function on_terminal_input($raw) { + public function on_terminal_input($raw) + { $raw = trim($raw); $last = substr($raw, -1, 1); if ($last == ";") { // dispatch to buffer callback call_user_func($this->buffer_cb, $this->buffer.$raw); $this->buffer = ''; } else if ($last == '\\') { $this->buffer .= substr($raw, 0, -1); echo $this->dots; } else { // buffer command $this->buffer .= $raw."; "; echo $this->dots; } } - public static function print_help() { + public static function print_help() + { global $exe; _colorize("Usage: $exe command [options...]\n", JAXL_INFO); _colorize("Commands:", JAXL_NOTICE); _colorize(" help This help text", JAXL_DEBUG); _colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG); _colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG); echo "\n"; } - protected function help() { + protected function help() + { JAXLCtl::print_help(); exit; } // // shell command // - protected function shell() { + protected function shell() + { return array(array(&$this, 'on_shell_input'), array(&$this, 'on_shell_quit')); } - private function _eval($raw, $symbols) { + private function _eval($raw, $symbols) + { extract($symbols); eval($raw); $g = get_defined_vars(); unset($g['raw']); unset($g['symbols']); return $g; } - public function on_shell_input($raw) { + public function on_shell_input($raw) + { $this->symbols = $this->_eval($raw, $this->symbols); JAXLCli::prompt(); } - public function on_shell_quit() { + public function on_shell_quit() + { exit; } // // debug command // - protected function debug($sock_path) { + protected function debug($sock_path) + { $this->ipc = new JAXLSocketClient(); $this->ipc->set_callback(array(&$this, 'on_debug_response')); $this->ipc->connect('unix://'.$sock_path); return array(array(&$this, 'on_debug_input'), array(&$this, 'on_debug_quit')); } - public function on_debug_response($raw) { + public function on_debug_response($raw) + { $ret = unserialize($raw); print_r($ret); echo "\n"; JAXLCli::prompt(); } - public function on_debug_input($raw) { + public function on_debug_input($raw) + { $this->ipc->send($this->buffer.$raw); } - public function on_debug_quit() { + public function on_debug_quit() + { $this->ipc->disconnect(); exit; } } // we atleast need a command argument if ($argc < 2) { JAXLCtl::print_help(); exit; } $ctl = new JAXLCtl($command, $params); echo "done\n"; diff --git a/tests/test_jaxl_event.php b/tests/test_jaxl_event.php index 7bb6d6a..0a87350 100644 --- a/tests/test_jaxl_event.php +++ b/tests/test_jaxl_event.php @@ -1,71 +1,72 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLEventTest extends PHPUnit_Framework_TestCase { - function test_jaxl_event() { + function test_jaxl_event() + { $ev = new JAXLEvent(); $ref1 = $ev->add('on_connect', 'some_func', 0); $ref2 = $ev->add('on_connect', 'some_func1', 0); $ref3 = $ev->add('on_connect', 'some_func2', 1); $ref4 = $ev->add('on_connect', 'some_func3', 4); $ref5 = $ev->add('on_disconnect', 'some_func', 1); $ref6 = $ev->add('on_disconnect', 'some_func1', 1); //$ev->emit('on_connect', null); $ev->del($ref2); $ev->del($ref1); $ev->del($ref6); $ev->del($ref5); $ev->del($ref4); $ev->del($ref3); //print_r($ev->reg); } } diff --git a/tests/test_jaxl_socket_client.php b/tests/test_jaxl_socket_client.php index f1fadb8..de8b689 100644 --- a/tests/test_jaxl_socket_client.php +++ b/tests/test_jaxl_socket_client.php @@ -1,59 +1,60 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLSocketClientTest extends PHPUnit_Framework_TestCase { - function test_jaxl_socket_client() { + function test_jaxl_socket_client() + { $sock = new JAXLSocketClient("127.0.0.1", 5222); $sock->connect(); $sock->send("<stream:stream>"); while ($sock->fd) { $sock->recv(); } } } diff --git a/tests/test_jaxl_xml_stream.php b/tests/test_jaxl_xml_stream.php index e201475..8701420 100644 --- a/tests/test_jaxl_xml_stream.php +++ b/tests/test_jaxl_xml_stream.php @@ -1,74 +1,78 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLXmlStreamTest extends PHPUnit_Framework_TestCase { - function xml_start_cb($node) { + function xml_start_cb($node) + { $this->assertEquals('stream', $node->name); $this->assertEquals(NS_XMPP, $node->ns); } - function xml_end_cb($node) { + function xml_end_cb($node) + { $this->assertEquals('stream', $node->name); } - function xml_stanza_cb($node) { + function xml_stanza_cb($node) + { $this->assertEquals('features', $node->name); $this->assertEquals(1, sizeof($node->childrens)); } - function test_xml_stream_callbacks() { + function test_xml_stream_callbacks() + { $xml = new JAXLXmlStream(); $xml->set_callback(array(&$this, "xml_start_cb"), array(&$this, "xml_end_cb"), array(&$this, "xml_stanza_cb")); $xml->parse('<stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">'); $xml->parse('<features>'); $xml->parse('<mechanisms>'); $xml->parse('</mechanisms>'); $xml->parse('</features>'); $xml->parse('</stream:stream>'); } } diff --git a/tests/test_xmpp_jid.php b/tests/test_xmpp_jid.php index 2b4f951..00b93fd 100644 --- a/tests/test_xmpp_jid.php +++ b/tests/test_xmpp_jid.php @@ -1,63 +1,64 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPJidTest extends PHPUnit_Framework_TestCase { - function test_xmpp_jid_construct() { + function test_xmpp_jid_construct() + { $jid = new XMPPJid("[email protected]/res"); $this->assertEquals('[email protected]/res', $jid->to_string()); $jid = new XMPPJid("domain.tld/res"); $this->assertEquals('domain.tld/res', $jid->to_string()); $jid = new XMPPJid("component.domain.tld"); $this->assertEquals('component.domain.tld', $jid->to_string()); $jid = new XMPPJid("[email protected]"); $this->assertEquals('[email protected]', $jid->to_string()); } } diff --git a/tests/test_xmpp_msg.php b/tests/test_xmpp_msg.php index 84b8dc6..8440e74 100644 --- a/tests/test_xmpp_msg.php +++ b/tests/test_xmpp_msg.php @@ -1,67 +1,68 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPMsgTest extends PHPUnit_Framework_TestCase { - function test_xmpp_msg() { + function test_xmpp_msg() + { $msg = new XMPPMsg(array('to' => '[email protected]', 'from' => '[email protected]/~', 'type' => 'chat'), 'hi', 'thread1'); echo $msg->to.PHP_EOL; echo $msg->to_node.PHP_EOL; echo $msg->from.PHP_EOL; echo $msg->to_string().PHP_EOL; $msg->to = '[email protected]/sp'; $msg->body = 'hello world'; $msg->subject = 'some subject'; echo $msg->to.PHP_EOL; echo $msg->to_node.PHP_EOL; echo $msg->from.PHP_EOL; echo $msg->to_string().PHP_EOL; } } diff --git a/tests/test_xmpp_stanza.php b/tests/test_xmpp_stanza.php index 06bb11c..50b0bce 100644 --- a/tests/test_xmpp_stanza.php +++ b/tests/test_xmpp_stanza.php @@ -1,75 +1,77 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPStanzaTest extends PHPUnit_Framework_TestCase { - function test_xmpp_stanza_nested() { + function test_xmpp_stanza_nested() + { $stanza = new JAXLXml('message', array('to' => '[email protected]', 'from' => '[email protected]')); $stanza ->c('body')->attrs(array('xml:lang' => 'en'))->t('hello')->up() ->c('thread')->t('1234')->up() ->c('nested') ->c('nest')->t('nest1')->up() ->c('nest')->t('nest2')->up() ->c('nest')->t('nest3')->up()->up() ->c('c')->attrs(array('hash' => '84jsdmnskd')); $this->assertEquals( '<message to="[email protected]" from="[email protected]"><body xml:lang="en">hello</body><thread>1234</thread><nested><nest>nest1</nest><nest>nest2</nest><nest>nest3</nest></nested><c hash="84jsdmnskd"></c></message>', $stanza->to_string() ); } - function test_xmpp_stanza_from_jaxl_xml() { + function test_xmpp_stanza_from_jaxl_xml() + { // xml to stanza test $xml = new JAXLXml('message', NS_JABBER_CLIENT, array('to' => '[email protected]', 'from' => '[email protected]/q')); $stanza = new XMPPStanza($xml); $stanza->c('body')->t('hello world'); echo $stanza->to."\n"; echo $stanza->to_string()."\n"; } } diff --git a/tests/test_xmpp_stream.php b/tests/test_xmpp_stream.php index e078789..c03f8e0 100644 --- a/tests/test_xmpp_stream.php +++ b/tests/test_xmpp_stream.php @@ -1,59 +1,60 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPStreamTest extends PHPUnit_Framework_TestCase { - function test_xmpp_stream() { + function test_xmpp_stream() + { $xmpp = new XMPPStream("test@localhost", "password"); $xmpp->connect(); $xmpp->start_stream(); while ($xmpp->sock->fd) { $xmpp->sock->recv(); } } } diff --git a/xep/xep_0030.php b/xep/xep_0030.php index a17cd55..2d14786 100644 --- a/xep/xep_0030.php +++ b/xep/xep_0030.php @@ -1,89 +1,94 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DISCO_INFO', 'http://jabber.org/protocol/disco#info'); define('NS_DISCO_ITEMS', 'http://jabber.org/protocol/disco#items'); class XEP_0030 extends XMPPXep { // // abstract method // - public function init() { + public function init() + { return array( ); } // // api methods // - public function get_info_pkt($entity_jid) { + public function get_info_pkt($entity_jid) + { return $this->jaxl->get_iq_pkt( array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid), new JAXLXml('query', NS_DISCO_INFO) ); } - public function get_info($entity_jid, $callback = null) { + public function get_info($entity_jid, $callback = null) + { $pkt = $this->get_info_pkt($entity_jid); if ($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } - public function get_items_pkt($entity_jid) { + public function get_items_pkt($entity_jid) + { return $this->jaxl->get_iq_pkt( array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid), new JAXLXml('query', NS_DISCO_ITEMS) ); } - public function get_items($entity_jid, $callback = null) { + public function get_items($entity_jid, $callback = null) + { $pkt = $this->get_items_pkt($entity_jid); if ($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } // // event callbacks // } diff --git a/xep/xep_0045.php b/xep/xep_0045.php index 46e3c56..5ecbacc 100644 --- a/xep/xep_0045.php +++ b/xep/xep_0045.php @@ -1,111 +1,117 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_MUC', 'http://jabber.org/protocol/muc'); class XEP_0045 extends XMPPXep { // // abstract method // - public function init() { + public function init() + { return array(); } - public function send_groupchat($room_jid, $body, $thread = null, $subject = null) { + public function send_groupchat($room_jid, $body, $thread = null, $subject = null) + { $msg = new XMPPMsg( array( 'type' => 'groupchat', 'to' => (($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid), 'from' => $this->jaxl->full_jid->to_string() ), $body, $thread, $subject ); $this->jaxl->send($msg); } // // api methods (occupant use case) // // room_full_jid simply means room jid with nick name as resource - public function get_join_room_pkt($room_full_jid, $options) { + public function get_join_room_pkt($room_full_jid, $options) + { $pkt = $this->jaxl->get_pres_pkt( array( 'from' => $this->jaxl->full_jid->to_string(), 'to' => (($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid) ) ); $x = $pkt->c('x', NS_MUC); if (isset($options['no_history'])) { $x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0)); } return $x; } - public function join_room($room_full_jid, $options = array()) { + public function join_room($room_full_jid, $options = array()) + { $pkt = $this->get_join_room_pkt($room_full_jid, $options); $this->jaxl->send($pkt); } - public function get_leave_room_pkt($room_full_jid) { + public function get_leave_room_pkt($room_full_jid) + { return $this->jaxl->get_pres_pkt( array('type' => 'unavailable', 'from' => $this->jaxl->full_jid->to_string(), 'to' => (($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid)) ); } - public function leave_room($room_full_jid) { + public function leave_room($room_full_jid) + { $pkt = $this->get_leave_room_pkt($room_full_jid); $this->jaxl->send($pkt); } // // api methods (moderator use case) // // // event callbacks // } diff --git a/xep/xep_0060.php b/xep/xep_0060.php index c50ab7e..2a1c70c 100644 --- a/xep/xep_0060.php +++ b/xep/xep_0060.php @@ -1,136 +1,149 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_PUBSUB', 'http://jabber.org/protocol/pubsub'); class XEP_0060 extends XMPPXep { // // abstract method // - public function init() { + public function init() + { return array(); } // // api methods (entity use case) // // // api methods (subscriber use case) // - public function get_subscribe_pkt($service, $node, $jid = null) { + public function get_subscribe_pkt($service, $node, $jid = null) + { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('subscribe', null, array('node' => $node, 'jid' => ($jid ? $jid : $this->jaxl->full_jid->to_string()))); return $this->get_iq_pkt($service, $child); } - public function subscribe($service, $node, $jid = null) { + public function subscribe($service, $node, $jid = null) + { $this->jaxl->send($this->get_subscribe_pkt($service, $node, $jid)); } - public function unsubscribe() { + public function unsubscribe() + { } - public function get_subscription_options() { + public function get_subscription_options() + { } - public function set_subscription_options() { + public function set_subscription_options() + { } - public function get_node_items() { + public function get_node_items() + { } // // api methods (publisher use case) // - public function get_publish_item_pkt($service, $node, $item) { + public function get_publish_item_pkt($service, $node, $item) + { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('publish', null, array('node' => $node)); $child->cnode($item); return $this->get_iq_pkt($service, $child); } - public function publish_item($service, $node, $item) { + public function publish_item($service, $node, $item) + { $this->jaxl->send($this->get_publish_item_pkt($service, $node, $item)); } - public function delete_item() { + public function delete_item() + { } // // api methods (owner use case) // - public function get_create_node_pkt($service, $node) { + public function get_create_node_pkt($service, $node) + { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('create', null, array('node' => $node)); return $this->get_iq_pkt($service, $child); } - public function create_node($service, $node) { + public function create_node($service, $node) + { $this->jaxl->send($this->get_create_node_pkt($service, $node)); } // // event callbacks // // // local methods // // this always add attrs - protected function get_iq_pkt($service, $child, $type = 'set') { + protected function get_iq_pkt($service, $child, $type = 'set') + { return $this->jaxl->get_iq_pkt( array('type' => $type, 'from' => $this->jaxl->full_jid->to_string(), 'to' => $service), $child ); } } diff --git a/xep/xep_0077.php b/xep/xep_0077.php index da440fd..5250a14 100644 --- a/xep/xep_0077.php +++ b/xep/xep_0077.php @@ -1,80 +1,84 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_FEATURE_REGISTER', 'http://jabber.org/features/iq-register'); define('NS_INBAND_REGISTER', 'jabber:iq:register'); class XEP_0077 extends XMPPXep { // // abstract method // - public function init() { + public function init() + { return array( ); } // // api methods // - public function get_form_pkt($domain) { + public function get_form_pkt($domain) + { return $this->jaxl->get_iq_pkt( array('to' => $domain, 'type' => 'get'), new JAXLXml('query', NS_INBAND_REGISTER) ); } - public function get_form($domain) { + public function get_form($domain) + { $this->jaxl->send($this->get_form_pkt($domain)); } - public function set_form($domain, $form) { + public function set_form($domain, $form) + { $query = new JAXLXml('query', NS_INBAND_REGISTER); foreach ($form as $k => $v) $query->c($k, null, array(), $v)->up(); $pkt = $this->jaxl->get_iq_pkt( array('to' => $domain, 'type' => 'set'), $query ); $this->jaxl->send($pkt); } } diff --git a/xep/xep_0114.php b/xep/xep_0114.php index 99ecd8a..e27a0ec 100644 --- a/xep/xep_0114.php +++ b/xep/xep_0114.php @@ -1,91 +1,96 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_JABBER_COMPONENT_ACCEPT', 'jabber:component:accept'); class XEP_0114 extends XMPPXep { // // abstract method // - public function init() { + public function init() + { return array( 'on_connect' => 'start_stream', 'on_stream_start' => 'start_handshake', 'on_handshake_stanza' => 'logged_in', 'on_error_stanza' => 'logged_out' ); } // // event callbacks // - public function start_stream() { + public function start_stream() + { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" to="'.$this->jaxl->jid->to_string().'" xmlns="'.NS_JABBER_COMPONENT_ACCEPT.'">'; $this->jaxl->send_raw($xml); } - public function start_handshake($stanza) { + public function start_handshake($stanza) + { _debug("starting component handshake"); $id = $stanza->id; $hash = strtolower(sha1($id.$this->jaxl->pass)); $stanza = new JAXLXml('handshake', null, $hash); $this->jaxl->send($stanza); } - public function logged_in($stanza) { + public function logged_in($stanza) + { _debug("component handshake complete"); $this->jaxl->handle_auth_success(); return array("logged_in", 1); } - public function logged_out($stanza) { + public function logged_out($stanza) + { if ($stanza->name == "error" && $stanza->ns == NS_XMPP) { $reason = $stanza->childrens[0]->name; $this->jaxl->handle_auth_failure($reason); $this->jaxl->send_end_stream(); return array("logged_out", 0); } else { _debug("uncatched stanza received in logged_out"); } } } diff --git a/xep/xep_0115.php b/xep/xep_0115.php index d5d38e6..53e2fe3 100644 --- a/xep/xep_0115.php +++ b/xep/xep_0115.php @@ -1,70 +1,72 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_CAPS', 'http://jabber.org/protocol/caps'); class XEP_0115 extends XMPPXep { // // abstract method // - public function init() { + public function init() + { return array(); } // // api methods // - public function get_caps_pkt($cat, $type, $lang, $name, $node, $features) { + public function get_caps_pkt($cat, $type, $lang, $name, $node, $features) + { asort($features); $S = $cat.'/'.$type.'/'.$lang.'/'.$name.'<'; foreach ($features as $feature) $S .= $feature.'<'; $ver = base64_encode(sha1($S, true)); $stanza = new JAXLXml('c', NS_CAPS, array('hash' => 'sha1', 'node' => $node, 'ver' => $ver)); return $stanza; } // // event callbacks // } diff --git a/xep/xep_0199.php b/xep/xep_0199.php index 01d3c9d..d71c1d4 100644 --- a/xep/xep_0199.php +++ b/xep/xep_0199.php @@ -1,57 +1,62 @@ <?php require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_XMPP_PING', 'urn:xmpp:ping'); class XEP_0199 extends XMPPXep { // // abstract method // - public function init() { + public function init() + { return array( 'on_auth_success' => 'on_auth_success', 'on_get_iq' => 'on_xmpp_ping' ); } // // api methods // - public function get_ping_pkt() { + public function get_ping_pkt() + { $attrs = array( 'type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $this->jaxl->full_jid->domain ); return $this->jaxl->get_iq_pkt( $attrs, new JAXLXml('ping', NS_XMPP_PING) ); } - public function ping() { + public function ping() + { $this->jaxl->send($this->get_ping_pkt()); } // // event callbacks // - public function on_auth_success() { + public function on_auth_success() + { JAXLLoop::$clock->call_fun_periodic(30 * pow(10,6), array(&$this, 'ping')); } - public function on_xmpp_ping($stanza) { + public function on_xmpp_ping($stanza) + { if ($stanza->exists('ping', NS_XMPP_PING)) { $stanza->type = "result"; $stanza->to = $stanza->from; $stanza->from = $this->jaxl->full_jid->to_string(); $this->jaxl->send($stanza); } } } diff --git a/xep/xep_0203.php b/xep/xep_0203.php index bfb5f6d..ae1968d 100644 --- a/xep/xep_0203.php +++ b/xep/xep_0203.php @@ -1,60 +1,61 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DELAYED_DELIVERY', 'urn:xmpp:delay'); class XEP_0203 extends XMPPXep { // // abstract method // - public function init() { + public function init() + { return array(); } // // api methods // // // event callbacks // } diff --git a/xep/xep_0206.php b/xep/xep_0206.php index 7bc76a1..9b7a4e3 100644 --- a/xep/xep_0206.php +++ b/xep/xep_0206.php @@ -1,228 +1,238 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind'); define('NS_BOSH', 'urn:xmpp:xbosh'); class XEP_0206 extends XMPPXep { private $mch = null; public $chs = array(); private $recv_cb = null; public $rid = null; public $sid = null; private $hold = 1; private $wait = 30; private $restarted = false; public $headers = array( 'Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8' ); // // abstract method // - public function init() { + public function init() + { $this->mch = curl_multi_init(); return array( ); } // // event callbacks // - public function send($body) { + public function send($body) + { if (is_object($body)) { $body = $body->to_string(); } else { if (substr($body, 0, 15) == '<stream:stream ') { $this->restarted = true; $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'xmpp:restart' => 'true', 'xmlns:xmpp' => NS_BOSH )); $body = $body->to_string(); } else if (substr($body, 0, 16) == '</stream:stream>') { $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'type' => 'terminate' )); $body = $body->to_string(); } else { $body = $this->wrap($body); } } _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body); $this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']); curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers); curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false); curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1); curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body); curl_multi_add_handle($this->mch, $this->chs[$this->rid]); } - public function recv() { + public function recv() + { if ($this->restarted) { $this->restarted = false; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); } _debug("recving for $this->rid"); do { $ret = curl_multi_exec($this->mch, $running); $changed = curl_multi_select($this->mch, 0.1); if ($changed == 0 && $running == 0) { $ch = @$this->chs[$this->rid]; if ($ch) { $data = curl_multi_getcontent($ch); curl_multi_remove_handle($this->mch, $ch); unset($this->chs[$this->rid]); _debug("recvd for $this->rid ".$data); list($body, $stanza) = $this->unwrap($data); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if (@$attrs['type'] == 'terminate') { // fool me again if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); } else { if (!$this->sid) { $this->sid = $attrs['sid']; } if ($this->recv_cb) call_user_func($this->recv_cb, $stanza); } } else { _error("no ch found"); exit; } } } while ($running); } - public function set_callback($recv_cb) { + public function set_callback($recv_cb) + { $this->recv_cb = $recv_cb; } - public function wrap($stanza) { + public function wrap($stanza) + { return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>'; } - public function unwrap($body) { + public function unwrap($body) + { // a dirty way but it works efficiently if (substr($body, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); if (isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; else $envelop = "<body/>"; if (isset($m[2][0])) $payload = $m[2][0]; else $payload = ''; return array($envelop, $payload); } - public function session_start() { + public function session_start() + { $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000); $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold; $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); $attrs = array( 'content' => 'text/xml; charset=utf-8', 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'], 'secure' => 'true', 'xml:lang' => 'en', 'xmpp:version' => '1.0', 'xmlns:xmpp' => NS_BOSH, 'hold' => $this->hold, 'wait' => $this->wait, 'rid' => $this->rid, 'ver' => '1.10' ); if (@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; $body = new JAXLXml('body', NS_HTTP_BIND, $attrs); $this->send($body); } - public function ping() { + public function ping() + { $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid)); $this->send($body); } - public function session_end() { + public function session_end() + { $this->disconnect(); } - public function disconnect() { + public function disconnect() + { _debug("disconnecting"); } } diff --git a/xep/xep_0249.php b/xep/xep_0249.php index 21761a1..59bd115 100644 --- a/xep/xep_0249.php +++ b/xep/xep_0249.php @@ -1,78 +1,81 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DIRECT_MUC_INVITATION', 'jabber:x:conference'); class XEP_0249 extends XMPPXep { // // abstract method // - public function init() { + public function init() + { return array(); } // // api methods // - public function get_invite_pkt($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) { + public function get_invite_pkt($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) + { $xattrs = array('jid' => $room_jid); if ($password) $xattrs['password'] = $password; if ($reason) $xattrs['reason'] = $reason; if ($thread) $xattrs['thread'] = $thread; if ($continue) $xattrs['continue'] = $continue; return $this->jaxl->get_msg_pkt( array('from' => $this->jaxl->full_jid->to_string(), 'to' => $to_bare_jid), null, null, null, new JAXLXml('x', NS_DIRECT_MUC_INVITATION, $xattrs) ); } - public function invite($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) { + public function invite($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) + { $this->jaxl->send($this->get_invite_pkt($to_bare_jid, $room_jid, $password, $reason, $thread, $continue)); } // // event callbacks // } diff --git a/xmpp/xmpp_iq.php b/xmpp/xmpp_iq.php index 8dd0a02..19103bf 100644 --- a/xmpp/xmpp_iq.php +++ b/xmpp/xmpp_iq.php @@ -1,46 +1,47 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; class XMPPIq extends XMPPStanza { - public function __construct($attrs) { + public function __construct($attrs) + { parent::__construct('iq', $attrs); } } diff --git a/xmpp/xmpp_jid.php b/xmpp/xmpp_jid.php index 0c8fa53..249a643 100644 --- a/xmpp/xmpp_jid.php +++ b/xmpp/xmpp_jid.php @@ -1,78 +1,80 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Xmpp Jid * * @author abhinavsingh * */ class XMPPJid { public $node = null; public $domain = null; public $resource = null; public $bare = null; - public function __construct($str) { + public function __construct($str) + { $tmp = explode("@", $str); if (sizeof($tmp) == 2) { $this->node = $tmp[0]; $tmp = explode("/", $tmp[1]); if (sizeof($tmp) == 2) { $this->domain = $tmp[0]; $this->resource = $tmp[1]; } else { $this->domain = $tmp[0]; } } else if (sizeof($tmp) == 1) { $this->domain = $tmp[0]; } $this->bare = $this->node ? $this->node."@".$this->domain : $this->domain; } - public function to_string() { + public function to_string() + { $str = ""; if ($this->node) $str .= $this->node.'@'.$this->domain; else if ($this->domain) $str .= $this->domain; if ($this->resource) $str .= '/'.$this->resource; return $str; } } diff --git a/xmpp/xmpp_msg.php b/xmpp/xmpp_msg.php index 7e1eb97..9847246 100644 --- a/xmpp/xmpp_msg.php +++ b/xmpp/xmpp_msg.php @@ -1,50 +1,51 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; class XMPPMsg extends XMPPStanza { - public function __construct($attrs, $body = null, $thread = null, $subject = null) { + public function __construct($attrs, $body = null, $thread = null, $subject = null) + { parent::__construct('message', $attrs); if ($body) $this->c('body')->t($body)->up(); if ($thread) $this->c('thread')->t($thread)->up(); if ($subject) $this->c('subject')->t($subject)->up(); } } diff --git a/xmpp/xmpp_pres.php b/xmpp/xmpp_pres.php index c9a7bce..f76bb6c 100644 --- a/xmpp/xmpp_pres.php +++ b/xmpp/xmpp_pres.php @@ -1,50 +1,51 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; class XMPPPres extends XMPPStanza { - public function __construct($attrs, $status = null, $show = null, $priority = null) { + public function __construct($attrs, $status = null, $show = null, $priority = null) + { parent::__construct('presence', $attrs); if ($status) $this->c('status')->t($status)->up(); if ($show) $this->c('show')->t($show)->up(); if ($priority) $this->c('priority')->t($priority)->up(); } } diff --git a/xmpp/xmpp_roster_item.php b/xmpp/xmpp_roster_item.php index ebd89a8..cab1eee 100644 --- a/xmpp/xmpp_roster_item.php +++ b/xmpp/xmpp_roster_item.php @@ -1,56 +1,57 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh */ class XMPPRosterItem { public $jid = null; public $subscription = null; public $groups = array(); public $resources = array(); public $vcard = null; - public function __construct($jid, $subscription, $groups) { + public function __construct($jid, $subscription, $groups) + { $this->jid = $jid; $this->subscription = $subscription; $this->groups = $groups; } } diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php index 3fb73a5..50ac613 100644 --- a/xmpp/xmpp_stanza.php +++ b/xmpp/xmpp_stanza.php @@ -1,173 +1,177 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; /** * Generic xmpp stanza object which provide convinient access pattern over xml objects * Also to be able to convert an existing xml object into stanza object (to get access patterns going) * this class doesn't extend xml, but infact works on a reference of xml object * If not provided during constructor, new xml object is created and saved as reference * * @author abhinavsingh * */ class XMPPStanza { private $xml; - public function __construct($name, $attrs = array(), $ns = NS_JABBER_CLIENT) { + public function __construct($name, $attrs = array(), $ns = NS_JABBER_CLIENT) + { if ($name instanceof JAXLXml) $this->xml = $name; else $this->xml = new JAXLXml($name, $ns, $attrs); } - public function __call($method, $args) { + public function __call($method, $args) + { return call_user_func_array(array($this->xml, $method), $args); } - public function __get($prop) { + public function __get($prop) + { switch($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': return @$this->xml->attrs[$prop] ? $this->xml->attrs[$prop] : null; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val = @$this->xml->attrs[$attr] ? $this->xml->attrs[$attr] : null; if (!$val) return null; $val = new XMPPJid($val); return $val->$key; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val = $this->xml->exists($prop); if (!$val) return null; return $val->text; break; default: return null; break; } } - public function __set($prop, $val) { + public function __set($prop, $val) + { switch($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop = $val; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': $this->xml->attrs[$prop] = $val; return true; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val1 = @$this->xml->attrs[$attr]; if (!$val1) $val1 = ''; $val1 = new XMPPJid($val1); $val1->$key = $val; $this->xml->attrs[$attr] = $val1->to_string(); return true; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val1 = $this->xml->exists($prop); if (!$val1) $this->xml->c($prop)->t($val)->up(); else $this->xml->update($prop, $val1->ns, $val1->attrs, $val); return true; break; default: return null; break; } } } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index b9d9645..d96ca4d 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,657 +1,699 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // - public function __construct($transport, $jid, $pass = null, $resource = null, $force_tls = false) { + public function __construct($transport, $jid, $pass = null, $resource = null, $force_tls = false) + { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } - public function __destruct() { + public function __destruct() + { //_debug("cleaning up xmpp stream..."); } - public function handle_invalid_state($r) { + public function handle_invalid_state($r) + { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } - public function send($stanza) { + public function send($stanza) + { $this->trans->send($stanza->to_string()); } - public function send_raw($data) { + public function send_raw($data) + { $this->trans->send($data); } // // pkt creation utilities // - public function get_start_stream($jid) { + public function get_start_stream($jid) + { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if (isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; if (isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } - public function get_end_stream() { + public function get_end_stream() + { return '</stream:stream>'; } - public function get_starttls_pkt() { + public function get_starttls_pkt() + { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } - public function get_compress_pkt($method) { + public function get_compress_pkt($method) + { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth - public function get_auth_pkt($mechanism, $user, $pass) { + public function get_auth_pkt($mechanism, $user, $pass) + { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if (strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } - public function get_challenge_response_pkt($challenge) { + public function get_challenge_response_pkt($challenge) + { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } - public function get_challenge_response($decoded) { + public function get_challenge_response($decoded) + { $response = array(); $nc = '00000001'; if (!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc' => $nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if (isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } - public function get_bind_pkt($resource) { + public function get_bind_pkt($resource) + { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } - public function get_session_pkt() { + public function get_session_pkt() + { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } - public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null) { + public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null) + { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if (!$msg->id) $msg->id = $this->get_id(); if ($payload) $msg->cnode($payload); return $msg; } - public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null) { + public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null) + { $pres = new XMPPPres($attrs, $status, $show, $priority); if (!$pres->id) $pres->id = $this->get_id(); if ($payload) $pres->cnode($payload); return $pres; } - public function get_iq_pkt($attrs, $payload) { + public function get_iq_pkt($attrs, $payload) + { $iq = new XMPPIq($attrs); if (!$iq->id) $iq->id = $this->get_id(); if ($payload) $iq->cnode($payload); return $iq; } - public function get_id() { + public function get_id() + { ++$this->last_id; return dechex($this->last_id); } - public function explode_data($data) { + public function explode_data($data) + { $data = explode(',', $data); $pairs = array(); $key = false; foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } else if (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } - public function implode_data($data) { + public function implode_data($data) + { $return = array(); foreach ($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } - public function encrypt_password($data, $user, $pass) { + public function encrypt_password($data, $user, $pass) + { foreach (array('realm', 'cnonce', 'digest-uri') as $key) if (!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if (isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // - protected function send_start_stream($jid) { + protected function send_start_stream($jid) + { $this->send_raw($this->get_start_stream($jid)); } - public function send_end_stream() { + public function send_end_stream() + { $this->send_raw($this->get_end_stream()); } - protected function send_auth_pkt($type, $user, $pass) { + protected function send_auth_pkt($type, $user, $pass) + { $this->send($this->get_auth_pkt($type, $user, $pass)); } - protected function send_starttls_pkt() { + protected function send_starttls_pkt() + { $this->send($this->get_starttls_pkt()); } - protected function send_compress_pkt($method) { + protected function send_compress_pkt($method) + { $this->send($this->get_compress_pkt($method)); } - protected function send_challenge_response($challenge) { + protected function send_challenge_response($challenge) + { $this->send($this->get_challenge_response_pkt($challenge)); } - protected function send_bind_pkt($resource) { + protected function send_bind_pkt($resource) + { $this->send($this->get_bind_pkt($resource)); } - protected function send_session_pkt() { + protected function send_session_pkt() + { $this->send($this->get_session_pkt()); } - private function do_connect($args) { + private function do_connect($args) + { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // - public function setup($event, $args) { + public function setup($event, $args) + { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } - public function connected($event, $args) { + public function connected($event, $args) + { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } - public function disconnected($event, $args) { + public function disconnected($event, $args) + { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } - public function wait_for_stream_start($event, $args) { + public function wait_for_stream_start($event, $args) + { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation - public function wait_for_stream_features($event, $args) { + public function wait_for_stream_features($event, $args) + { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if ($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } - public function wait_for_tls_result($event, $args) { + public function wait_for_tls_result($event, $args) + { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } - public function wait_for_compression_result($event, $args) { + public function wait_for_compression_result($event, $args) + { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } - public function wait_for_sasl_response($event, $args) { + public function wait_for_sasl_response($event, $args) + { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } else if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } else if ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } - public function wait_for_bind_response($event, $args) { + public function wait_for_bind_response($event, $args) + { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } - public function wait_for_session_response($event, $args) { + public function wait_for_session_response($event, $args) + { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } - public function logged_in($event, $args) { + public function logged_in($event, $args) + { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if ($stanza->name == 'message') { $this->handle_message($stanza); } else if ($stanza->name == 'presence') { $this->handle_presence($stanza); } else if ($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } - public function logged_out($event, $args) { + public function logged_out($event, $args) + { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } } diff --git a/xmpp/xmpp_xep.php b/xmpp/xmpp_xep.php index ea8e9d5..2d1058f 100644 --- a/xmpp/xmpp_xep.php +++ b/xmpp/xmpp_xep.php @@ -1,63 +1,65 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh * */ abstract class XMPPXep { // init() method defines various callbacks // required by this xep extension abstract public function init(); //abstract public $description; //abstract public $dependencies; // reference to jaxl instance // which required me protected $jaxl = null; - public function __construct($jaxl) { + public function __construct($jaxl) + { $this->jaxl = $jaxl; } - public function __destruct() { + public function __destruct() + { } }
jaxl/JAXL
6e17f076ea8c37380b328ea00cc9cfa97a86a06e
Fix PSR: Incorrect spacing
diff --git a/core/jaxl_cli.php b/core/jaxl_cli.php index 8c1ab01..1f6f259 100644 --- a/core/jaxl_cli.php +++ b/core/jaxl_cli.php @@ -1,93 +1,93 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLCli { public static $counter = 0; private $in = null; private $quit_cb = null; private $recv_cb = null; private $recv_chunk_size = 1024; - public function __construct($recv_cb=null, $quit_cb=null) { + public function __construct($recv_cb = null, $quit_cb = null) { $this->recv_cb = $recv_cb; $this->quit_cb = $quit_cb; // catch read event on stdin $this->in = fopen('php://stdin', 'r'); stream_set_blocking($this->in, false); JAXLLoop::watch($this->in, array( 'read' => array(&$this, 'on_read_ready') )); } public function __destruct() { @fclose($this->in); } public function stop() { JAXLLoop::unwatch($this->in, array( 'read' => true )); } public function on_read_ready($in) { $raw = @fread($in, $this->recv_chunk_size); if (ord($raw) == 10) { // enter key JAXLCli::prompt(false); return; } else if (trim($raw) == 'quit') { $this->stop(); $this->in = null; if ($this->quit_cb) call_user_func($this->quit_cb); return; } if ($this->recv_cb) call_user_func($this->recv_cb, $raw); } - public static function prompt($inc=true) { + public static function prompt($inc = true) { if ($inc) ++self::$counter; echo "jaxl ".self::$counter."> "; } } diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php index 81cbc88..e631298 100644 --- a/core/jaxl_clock.php +++ b/core/jaxl_clock.php @@ -1,121 +1,121 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class JAXLClock { // current clock time in microseconds private $tick = 0; // current Unix timestamp with microseconds public $time = null; // scheduled jobs public $jobs = array(); public function __construct() { $this->time = microtime(true); } public function __destruct() { _info("shutting down clock server..."); } - public function tick($by=null) { + public function tick($by = null) { // update clock if ($by) { $this->tick += $by; $this->time += $by / pow(10,6); } else { $time = microtime(true); $by = $time - $this->time; $this->tick += $by * pow(10, 6); $this->time = $time; } // run scheduled jobs foreach ($this->jobs as $ref => $job) { if ($this->tick >= $job['scheduled_on'] + $job['after']) { //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".$job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); call_user_func($job['cb'], $job['args']); if (!$job['is_periodic']) { unset($this->jobs[$ref]); } else { $job['scheduled_on'] = $this->tick; $job['runs']++; $this->jobs[$ref] = $job; } } } } // calculate execution time of callback - public function tc($callback, $args=null) { + public function tc($callback, $args = null) { } // callback after $time microseconds - public function call_fun_after($time, $callback, $args=null) { + public function call_fun_after($time, $callback, $args = null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => false, 'runs' => 0 ); return sizeof($this->jobs); } // callback periodically after $time microseconds - public function call_fun_periodic($time, $callback, $args=null) { + public function call_fun_periodic($time, $callback, $args = null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => true, 'runs' => 0 ); return sizeof($this->jobs); } // cancel a previously scheduled callback public function cancel_fun_call($ref) { unset($this->jobs[$ref-1]); } } diff --git a/core/jaxl_event.php b/core/jaxl_event.php index ee07efc..315afda 100644 --- a/core/jaxl_event.php +++ b/core/jaxl_event.php @@ -1,118 +1,118 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * following kind of events are possible: * 1) hook i.e. if a callback for such an event is registered, calling function is responsible for the workflow from their on * 2) filter i.e. calling function will manipulate passed arguments and modified arguments will be passed to next chain of filter * * As a rule of thumb, only 1 hook can be registered for an event, while more than 1 filter is allowed for an event * hook and filter both cannot be applied on an event * * @author abhinavsingh * */ class JAXLEvent { protected $common = array(); public $reg = array(); public function __construct($common) { $this->common = $common; } public function __destruct() { } // add callback on a event // returns a reference to be used while deleting callback // callback'd method must return TRUE to be persistent // if none returned or FALSE, callback will be removed automatically public function add($ev, $cb, $pri) { if (!isset($this->reg[$ev])) $this->reg[$ev] = array(); $ref = sizeof($this->reg[$ev]); $this->reg[$ev][] = array($pri, $cb); return $ev."-".$ref; } // emit event to notify registered callbacks // is a pqueue required here for performance enhancement // in case we have too many cbs on a specific event? - public function emit($ev, $data=array()) { + public function emit($ev, $data = array()) { $data = array_merge($this->common, $data); $cbs = array(); if (!isset($this->reg[$ev])) return $data; foreach ($this->reg[$ev] as $cb) { if (!isset($cbs[$cb[0]])) $cbs[$cb[0]] = array(); $cbs[$cb[0]][] = $cb[1]; } foreach ($cbs as $pri => $cb) { foreach ($cb as $c) { $ret = call_user_func_array($c, $data); // this line is for fixing situation where callback function doesn't return an array type // in such cases next call of call_user_func_array will report error since $data is not an array type as expected // things will change in future, atleast put the callback inside a try/catch block // here we only check if there was a return, if yes we update $data with return value // this is bad design, need more thoughts, should work as of now if ($ret) $data = $ret; } } unset($cbs); return $data; } // remove previous registered callback public function del($ref) { $ref = explode("-", $ref); unset($this->reg[$ref[0]][$ref[1]]); } public function exists($ev) { $ret = isset($this->reg[$ev]); //_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists")); return $ret; } } diff --git a/core/jaxl_logger.php b/core/jaxl_logger.php index 04d98de..b871262 100644 --- a/core/jaxl_logger.php +++ b/core/jaxl_logger.php @@ -1,89 +1,89 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // log level define('JAXL_ERROR', 1); define('JAXL_WARNING', 2); define('JAXL_NOTICE', 3); define('JAXL_INFO', 4); define('JAXL_DEBUG', 5); // generic global logging shortcuts for different level of verbosity function _error($msg) { JAXLLogger::log($msg, JAXL_ERROR); } function _warning($msg) { JAXLLogger::log($msg, JAXL_WARNING); } function _notice($msg) { JAXLLogger::log($msg, JAXL_NOTICE); } function _info($msg) { JAXLLogger::log($msg, JAXL_INFO); } function _debug($msg) { JAXLLogger::log($msg, JAXL_DEBUG); } // generic global terminal output colorize method // finally sends colorized message to terminal using error_log/1 // this method is mainly to escape $msg from file:line and time // prefix done by _debug, _error, ... methods function _colorize($msg, $verbosity) { error_log(JAXLLogger::colorize($msg, $verbosity)); } class JAXLLogger { public static $level = JAXL_DEBUG; public static $path = null; public static $max_log_size = 1000; protected static $colors = array( 1 => 31, // error: red 2 => 34, // warning: blue 3 => 33, // notice: yellow 4 => 32, // info: green 5 => 37 // debug: white ); - public static function log($msg, $verbosity=1) { + public static function log($msg, $verbosity = 1) { if ($verbosity <= self::$level) { $bt = debug_backtrace(); array_shift($bt); $callee = array_shift($bt); $msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg; $size = strlen($msg); if ($size > self::$max_log_size) $msg = substr($msg, 0, self::$max_log_size) . ' ...'; if (isset(self::$path)) error_log($msg . PHP_EOL, 3, self::$path); else error_log(self::colorize($msg, $verbosity)); } } public static function colorize($msg, $verbosity) { return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m"; } } diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php index 0664a08..2188e68 100644 --- a/core/jaxl_pipe.php +++ b/core/jaxl_pipe.php @@ -1,110 +1,110 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * bidirectional communication pipes for processes * * This is how this will be (when complete): * $pipe = new JAXLPipe() will return an array of size 2 * $pipe[0] represents the read end of the pipe * $pipe[1] represents the write end of the pipe * * Proposed functionality might even change (currently consider this as experimental) * * @author abhinavsingh * */ class JAXLPipe { protected $perm = 0600; protected $recv_cb = null; protected $fd = null; protected $client = null; public $name = null; - public function __construct($name, $read_cb=null) { + public function __construct($name, $read_cb = null) { $pipes_folder = JAXL_CWD.'/.jaxl/pipes'; if (!is_dir($pipes_folder)) mkdir($pipes_folder); $this->ev = new JAXLEvent(); $this->name = $name; $this->read_cb = $read_cb; $pipe_path = $this->get_pipe_file_path(); if (!file_exists($pipe_path)) { posix_mkfifo($pipe_path, $this->perm); $this->fd = fopen($pipe_path, 'r+'); if (!$this->fd) { _error("unable to open pipe"); } else { _debug("pipe opened using path $pipe_path"); _notice("Usage: $ echo 'Hello World!' > $pipe_path"); $this->client = new JAXLSocketClient(); $this->client->connect($this->fd); $this->client->set_callback(array(&$this, 'on_data')); } } else { _error("pipe with name $name already exists"); } } public function __destruct() { @fclose($this->fd); @unlink($this->get_pipe_file_path()); _debug("unlinking pipe file"); } public function get_pipe_file_path() { return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe'; } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function on_data($data) { // callback if ($this->recv_cb) call_user_func($this->recv_cb, $data); } } diff --git a/core/jaxl_sock5.php b/core/jaxl_sock5.php index 8eea396..8493133 100644 --- a/core/jaxl_sock5.php +++ b/core/jaxl_sock5.php @@ -1,124 +1,124 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ class JAXLSock5 { private $client = null; protected $transport = null; protected $ip = null; protected $port = null; - public function __construct($transport='tcp') { + public function __construct($transport = 'tcp') { $this->transport = $transport; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } public function __destruct() { } - public function connect($ip, $port=1080) { + public function connect($ip, $port = 1080) { $this->ip = $ip; $this->port = $port; $sock_path = $this->_sock_path(); if ($this->client->connect($sock_path)) { _debug("established connection to $sock_path"); return true; } else { _error("unable to connect $sock_path"); return false; } } // // Three phases of SOCK5 // // Negotiation pkt consists of 3 part: // 0x05 => Sock protocol version // 0x01 => Number of method identifier octet // // Following auth methods are defined: // 0x00 => No authentication required // 0x01 => GSSAPI // 0x02 => USERNAME/PASSWORD // 0x03 to 0x7F => IANA ASSIGNED // 0x80 to 0xFE => RESERVED FOR PRIVATE METHODS // 0xFF => NO ACCEPTABLE METHODS public function negotiate() { $pkt = pack("C3", 0x05, 0x01, 0x00); $this->client->send($pkt); // enter sub-negotiation state } public function relay_request() { // enter wait for reply state } public function send_data() { } // // Socket client callback // public function on_response($raw) { _debug($raw); } // // Private // protected function _sock_path() { return $this->transport.'://'.$this->ip.':'.$this->port; } } diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index ef54dba..bc2fb6b 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,214 +1,214 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; - public function __construct($stream_context=null) { + public function __construct($stream_context = null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ public function connect($socket_path) { if (gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); if (sizeof($path_parts) == 3) $this->port = $path_parts[2]; _info("trying ".$socket_path); if ($this->stream_context) $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); else $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); } else { $this->fd = &$socket_path; } if ($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); $this->disconnect(); return false; } } public function disconnect() { JAXLLoop::unwatch($this->fd, array( 'read' => true, 'write' => true )); @fclose($this->fd); $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); return $ret; } public function send($data) { $this->obuffer .= $data; // add watch for write events if ($this->writing) return; JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if ($bytes === 0) { $meta = stream_get_meta_data($fd); if ($meta['eof'] === TRUE) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); if ($bytes > 0) _debug($raw); // callback if ($this->recv_cb) call_user_func($this->recv_cb, $raw); } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if (strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } } diff --git a/core/jaxl_util.php b/core/jaxl_util.php index 4fd242d..ffe5aac 100644 --- a/core/jaxl_util.php +++ b/core/jaxl_util.php @@ -1,64 +1,64 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh * */ class JAXLUtil { - public static function get_nonce($binary=true) { + public static function get_nonce($binary = true) { $nce = ''; mt_srand((double) microtime()*10000000); - for ($i=0; $i<32; $i++) $nce .= chr(mt_rand(0, 255)); + for ($i = 0; $i<32; $i++) $nce .= chr(mt_rand(0, 255)); return $binary ? $nce : base64_encode($nce); } public static function get_dns_srv($domain) { $rec = dns_get_record("_xmpp-client._tcp.".$domain, DNS_SRV); if (is_array($rec)) { if (sizeof($rec) == 0) return array($domain, 5222); if (sizeof($rec) > 0) return array($rec[0]['target'], $rec[0]['port']); } } - public static function pbkdf2($data, $secret, $iteration, $dkLen=32, $algo='sha1') { + public static function pbkdf2($data, $secret, $iteration, $dkLen = 32, $algo = 'sha1') { return ''; } } diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index ef2604f..4b7ba34 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,191 +1,191 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if (is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if (is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if (is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; foreach ($attrs as $k => $v) { if ($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } - public function t($text, $append=FALSE) { + public function t($text, $append = FALSE) { if (!$append) { $this->rover->text = $text; } else { if ($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; } return $this; } - public function c($name, $ns=null, $attrs=array(), $text=null) { + public function c($name, $ns = null, $attrs = array(), $text = null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { if ($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } public function top() { $this->rover = &$this; return $this; } - public function exists($name, $ns=null, $attrs=array()) { + public function exists($name, $ns = null, $attrs = array()) { foreach ($this->childrens as $child) { if ($ns) { if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; } else if ($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } - public function update($name, $ns=null, $attrs=array(), $text=null) { + public function update($name, $ns = null, $attrs = array(), $text = null) { foreach ($this->childrens as $k => $child) { if ($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } - public function to_string($parent_ns=null) { + public function to_string($parent_ns = null) { $xml = ''; $xml .= '<'.$this->name; if ($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; foreach ($this->attrs as $k => $v) if (!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; foreach ($this->childrens as $child) $xml .= $child->to_string($this->ns); if ($this->text) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } } diff --git a/docs/users/jaxl_instance.rst b/docs/users/jaxl_instance.rst index 84a49da..d10398c 100644 --- a/docs/users/jaxl_instance.rst +++ b/docs/users/jaxl_instance.rst @@ -1,166 +1,166 @@ .. _jaxl-instance: JAXL Instance ============= ``JAXL`` instance configure/manage other :ref:`sub-packages <jaxl-instance>`. It provides an event based callback methodology on various underlying object. Whenever required ``JAXL`` instance will itself perform the configured defaults. Constructor options ------------------- #. ``jid`` #. ``pass`` #. ``resource`` If not passed Jaxl will use a random resource value #. ``auth_type`` DIGEST-MD5, PLAIN (default), CRAM-MD5, ANONYMOUS, X-FACEBOOK-PLATFORM #. ``host`` #. ``port`` #. ``bosh_url`` #. ``log_path`` #. ``log_level`` ``JAXL_ERROR``, ``JAXL_WARNING``, ``JAXL_NOTICE``, ``JAXL_INFO`` (default), ``JAXL_DEBUG`` #. ``fb_access_token`` required when using X-FACEBOOK-PLATFORM auth mechanism #. ``fb_app_key`` required when using X-FACEBOOK-PLATFORM auth mechanism #. ``force_tls`` #. ``stream_context`` #. ``priv_dir`` Jaxl creates 4 directories names ``log``, ``tmp``, ``run`` and ``sock`` inside a private directory which defaults to ``JAXL_CWD.'/.jaxl'``. If this option is passed, it will overwrite default private directory. .. note:: Jaxl currently doesn't check upon the permissions of passed ``priv_dir``. Make sure Jaxl library have sufficient permissions to create above mentioned directories. Available Event Callbacks ------------------------- Following ``$ev`` are available on ``JAXL`` lifecycle for registering callbacks: #. ``on_connect`` ``JAXL`` instance has connected successfully #. ``on_connect_error`` ``JAXL`` instance failed to connect #. ``on_stream_start`` ``JAXL`` instance has successfully initiated XMPP stream with the jabber server #. ``on_stream_features`` ``JAXL`` instance has received supported stream features #. ``on_auth_success`` authentication successful #. ``on_auth_failure`` authentication failed #. ``on_presence_stanza`` ``JAXL`` instance has received a presence stanza #. ``on_{$type}_message`` ``JAXL`` instance has received a message stanza. ``$type`` can be ``chat``, ``groupchat``, ``headline``, ``normal``, ``error`` #. ``on_stanza_id_{$id}`` Useful when dealing with iq stanza. This event is fired when ``JAXL`` instance has received response to a particular xmpp stanza id #. ``on_{$name}_stanza`` Useful when dealing with custom xmpp stanza #. ``on_disconnect`` ``JAXL`` instance has disconnected from the jabber server Available Methods ----------------- Following methods are available on initialized ``JAXL`` instance object: #. ``get_pid_file_path()`` returns path of ``JAXL`` instance pid file #. ``get_sock_file_path()`` returns path to ``JAXL`` ipc unix socket domain - #. ``require_xep($xeps=array())`` + #. ``require_xep($xeps = array())`` autoload and initialize passed XEP's - #. ``add_cb($ev, $cb, $pri=1)`` + #. ``add_cb($ev, $cb, $pri = 1)`` add a callback to function ``$cb`` on event ``$ev``, returns a reference of added callback #. ``del_cb($ref)`` delete previously registered event callback #. ``set_status($status, $show, $priority)`` send a presence status stanza - #. ``send_chat_msg($to, $body, $thread=null, $subject=null)`` + #. ``send_chat_msg($to, $body, $thread = null, $subject = null)`` send a message stanza of type chat - #. ``get_vcard($jid=null, $cb=null)`` + #. ``get_vcard($jid = null, $cb = null)`` fetch vcard for bare ``$jid``, passed ``$cb`` will be called with received vcard stanza - #. ``get_roster($cb=null)`` + #. ``get_roster($cb = null)`` fetch roster list of connected jabber client, passed ``$cb`` will be called with received roster stanza - #. ``start($opts=array())`` + #. ``start($opts = array())`` start configured ``JAXL`` instance, optionally accepts two options specified below: #. ``--with-debug-shell`` start ``JAXL`` instance and enter an interactive console #. ``--with-unix-sock`` start ``JAXL`` instance with support for IPC and remote debugging #. ``send($stanza)`` send an instance of JAXLXml packet over connected socket #. ``send_raw($data)`` send raw payload over connected socket - #. ``get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null)`` + #. ``get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null)`` - #. ``get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null)`` + #. ``get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null)`` #. ``get_iq_pkt($attrs, $payload)`` \ No newline at end of file diff --git a/docs/users/xml_objects.rst b/docs/users/xml_objects.rst index 01b566e..a11a049 100644 --- a/docs/users/xml_objects.rst +++ b/docs/users/xml_objects.rst @@ -1,121 +1,121 @@ .. _xml-objects: Xml Objects =========== Jaxl library works with custom XML implementation which is similar to inbuild PHP XML functions but is lightweight and easy to work with. JAXLXml ------- ``JAXLXml`` is the base XML object. Open up :ref:`Jaxl interactive shell <jaxl-instance>` and try some xml object creation/manipulation: >>> ./jaxlctl shell jaxl 1> jaxl 1> $xml = new JAXLXml( ....... 'dummy', ....... 'dummy:packet', ....... array('attr1' => '[email protected]', 'attr2' => ''), ....... 'Hello World!' ....... ); jaxl 2> echo $xml->to_string(); <dummy xmlns="dummy:packet" attr1="[email protected]" attr2="">Hello World!</dummy> jaxl 3> ``JAXLXml`` constructor instance accepts following parameters: * ``JAXLXml($name, $ns, $attrs, $text)`` * ``JAXLXml($name, $ns, $attrs)`` * ``JAXLXml($name, $ns, $text)`` * ``JAXLXml($name, $attrs, $text)`` * ``JAXLXml($name, $attrs)`` * ``JAXLXml($name, $ns)`` * ``JAXLXml($name)`` ``JAXLXml`` draws inspiration from StropheJS XML Builder class. Below are available methods for modifying and manipulating an ``JAXLXml`` object: - * ``t($text, $append=FALSE)`` + * ``t($text, $append = FALSE)`` update text of current rover - * ``c($name, $ns=null, $attrs=array(), $text=null)`` + * ``c($name, $ns = null, $attrs = array(), $text = null)`` append a child node at current rover * ``cnode($node)`` append a JAXLXml child node at current rover * ``up()`` move rover to one step up the xml tree * ``top()`` move rover back to top element in the xml tree - * ``exists($name, $ns=null, $attrs=array())`` + * ``exists($name, $ns = null, $attrs = array())`` checks if a child with $name exists, return child ``JAXLXml`` if found otherwise false. This function returns at first matching child. - * ``update($name, $ns=null, $attrs=array(), $text=null)`` + * ``update($name, $ns = null, $attrs = array(), $text = null)`` update specified child element * ``attrs($attrs)`` merge new attrs with attributes of current rover * ``match_attrs($attrs)`` pass a kv pair of ``$attrs``, return bool if all passed keys matches their respective values in the xml packet * ``to_string()`` get string representation of the object ``JAXLXml`` maintains a rover which points to the current level down the XML tree where manipulation is performed. XMPPStanza ---------- In the world of XMPP where everything incoming and outgoing payload is an ``JAXLXml`` instance code can become nasty, developers can get lost in dirty XML manipulations spreaded all over the application code base and what not. XML structures are not only unreadable for humans but even for machine. While an instance of ``JAXLXml`` provide direct access to XML ``name``, ``ns`` and ``text``, it can become painful and time consuming when trying to retrieve or modify a particular ``attrs`` or ``childrens``. I was fed up of doing ``getAttributeByName``, ``setAttributeByName``, ``getChild`` etc everytime i had to access common XMPP Stanza attributes. ``XMPPStanza`` is a wrapper on top of ``JAXLXml`` objects. Preserving all the functionalities of base ``JAXLXml`` instance it also provide direct access to most common XMPP Stanza attributes like ``to``, ``from``, ``id``, ``type`` etc. It also provides a framework for adding custom access patterns. ``XMPPMsg``, ``XMPPPres`` and ``XMPPIq`` extends ``XMPPStanza`` and also add a few custom access patterns like ``body``, ``thread``, ``subject``, ``status``, ``show`` etc. Here is a list of default access patterns: #. ``name`` #. ``ns`` #. ``text`` #. ``attrs`` #. ``childrens`` #. ``to`` #. ``from`` #. ``id`` #. ``type`` #. ``to_node`` #. ``to_domain`` #. ``to_resource`` #. ``from_node`` #. ``from_domain`` #. ``from_resource`` #. ``status`` #. ``show`` #. ``priority`` #. ``body`` #. ``thread`` #. ``subject`` diff --git a/http/http_client.php b/http/http_client.php index 5c9aaaa..ad4adc1 100644 --- a/http/http_client.php +++ b/http/http_client.php @@ -1,134 +1,134 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ class HTTPClient { private $url = null; private $parts = array(); private $headers = array(); private $data = null; public $method = null; private $client = null; - public function __construct($url, $headers=array(), $data=null) { + public function __construct($url, $headers = array(), $data = null) { $this->url = $url; $this->headers = $headers; $this->data = $data; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } - public function start($method='GET') { + public function start($method = 'GET') { $this->method = $method; $this->parts = parse_url($this->url); $transport = $this->_transport(); $ip = $this->_ip(); $port = $this->_port(); $socket_path = $transport.'://'.$ip.':'.$port; if ($this->client->connect($socket_path)) { _debug("connection to $this->url established"); // send request data $this->send_request(); // start main loop JAXLLoop::run(); } else { _debug("unable to open $this->url"); } } public function on_response($raw) { _info("got http response"); } protected function send_request() { $this->client->send($this->_line()."\r\n"); $this->client->send($this->_ua()."\r\n"); $this->client->send($this->_host()."\r\n"); $this->client->send("\r\n"); } // // private methods on uri parts // private function _line() { return $this->method.' '.$this->_uri().' HTTP/1.1'; } private function _ua() { return 'User-Agent: jaxl_http_client/3.x'; } private function _host() { return 'Host: '.$this->parts['host'].':'.$this->_port(); } private function _transport() { return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl'); } private function _ip() { return gethostbyname($this->parts['host']); } private function _port() { return @$this->parts['port'] ? $this->parts['port'] : 80; } private function _uri() { $uri = $this->parts['path']; if (@$this->parts['query']) $uri .= '?'.$this->parts['query']; if (@$this->parts['fragment']) $uri .= '#'.$this->parts['fragment']; return $uri; } } diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php index 2829a0d..be14f31 100644 --- a/http/http_dispatcher.php +++ b/http/http_dispatcher.php @@ -1,117 +1,117 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // // (optionally) set an array of url dispatch rules // each dispatch rule is defined by an array of size 4 like: // array($callback, $pattern, $methods, $extra), where // $callback the method which will be called if this rule matches // $pattern regular expression to match request path // $methods list of allowed methods for this rule // pass boolean true to allow all http methods // if omitted or an empty array() is passed (which actually doesnt make sense) // by default 'GET' will be the method allowed on this rule // $extra reserved for future (you can totally omit this as of now) // class HTTPDispatchRule { // match callback public $cb = null; // regexp to match on request path public $pattern = null; // methods to match upon // add atleast 1 method for this rule to work public $methods = null; // other matching rules public $extra = array(); - public function __construct($cb, $pattern, $methods=array('GET'), $extra=array()) { + public function __construct($cb, $pattern, $methods = array('GET'), $extra = array()) { $this->cb = $cb; $this->pattern = $pattern; $this->methods = $methods; $this->extra = $extra; } public function match($path, $method) { if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) { if (in_array($method, $this->methods)) { return $matches; } } return false; } } class HTTPDispatcher { protected $rules = array(); public function __construct() { $this->rules = array(); } public function add_rule($rule) { $s = sizeof($rule); if ($s > 4) { _debug("invalid rule"); return; } // fill up defaults if ($s == 3) { $rule[] = array(); } else if ($s == 2) { $rule[] = array('GET'); $rule[] = array(); } else { _debug("invalid rule"); return; } $this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]); } public function dispatch($request) { foreach ($this->rules as $rule) { //_debug("matching $request->path with pattern $rule->pattern"); if (($matches = $rule->match($request->path, $request->method)) !== false) { _debug("matching rule found, dispatching"); $params = array($request); // TODO: a bad way to restrict on 'pk', fix me for generalization if (@isset($matches['pk'])) $params[] = $matches['pk']; call_user_func_array($rule->cb, $params); return true; } } return false; } } diff --git a/http/http_request.php b/http/http_request.php index 076a01a..9a60fe1 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,479 +1,479 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // -// $request->send_response($code, $headers=array(), $body=null) +// $request->send_response($code, $headers = array(), $body = null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if (sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation // public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; if ($this->body === null) $this->body = $rcvd; else $this->body .= $rcvd; if ($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach ($form_data as $data) { //_debug("passing $data to multipart fsm"); if (!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if (!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if (!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { switch($event) { case 'empty_line': return 'headers_received'; break; default: if (substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if (method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } } else if (@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { $k = trim($k); $v = ltrim($v); // is expect header? if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if (strtolower($k) == 'content-type') { $ctype = explode(';', $v); if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if (strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if ($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { if (sizeof($args) == 0) { $body = null; $headers = array(); } if (sizeof($args) == 1) { // http headers or body only received if (is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } } else if (sizeof($args) == 2) { // body and http headers both received if (is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { foreach ($headers as $k => $v) $this->_send_header($k, $v); } protected function _send_body($body) { $this->_send($body); } - protected function _send_response($code, $headers=array(), $body=null) { + protected function _send_response($code, $headers = array(), $body = null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set if ($body && !isset($headers['Content-Length'])) $headers['Content-Length'] = strlen($body); // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); if ($body) $this->_send_body(HTTP_CRLF.$body); } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if (sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach ($query as $q) { $q = explode("=", $q); if (sizeof($q) == 1) $q[1] = ""; $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } } diff --git a/http/http_server.php b/http/http_server.php index 7b1ceef..6474b00 100644 --- a/http/http_server.php +++ b/http/http_server.php @@ -1,192 +1,192 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/http/http_dispatcher.php'; require_once JAXL_CWD.'/http/http_request.php'; // carriage return and line feed define('HTTP_CRLF', "\r\n"); // 1xx informational define('HTTP_100', "Continue"); define('HTTP_101', "Switching Protocols"); // 2xx success define('HTTP_200', "OK"); // 3xx redirection define('HTTP_301', 'Moved Permanently'); define('HTTP_304', 'Not Modified'); // 4xx client error define('HTTP_400', 'Bad Request'); define('HTTP_403', 'Forbidden'); define('HTTP_404', 'Not Found'); define('HTTP_405', 'Method Not Allowed'); define('HTTP_499', 'Client Closed Request'); // Nginx // 5xx server error define('HTTP_500', 'Internal Server Error'); define('HTTP_503', 'Service Unavailable'); class HTTPServer { private $server = null; public $cb = null; private $dispatcher = null; private $requests = array(); - public function __construct($port=9699, $address="127.0.0.1") { + public function __construct($port = 9699, $address = "127.0.0.1") { $path = 'tcp://'.$address.':'.$port; $this->server = new JAXLSocketServer( $path, array(&$this, 'on_accept'), array(&$this, 'on_request') ); $this->dispatcher = new HTTPDispatcher(); } public function __destruct() { $this->server = null; } public function dispatch($rules) { foreach ($rules as $rule) { $this->dispatcher->add_rule($rule); } } - public function start($cb=null) { + public function start($cb = null) { $this->cb = $cb; JAXLLoop::run(); } public function on_accept($sock, $addr) { _debug("on_accept for client#$sock, addr:$addr"); // initialize new request obj $request = new HTTPRequest($sock, $addr); // setup sock cb $request->set_sock_cb( array(&$this->server, 'send'), array(&$this->server, 'read'), array(&$this->server, 'close') ); // cache request object $this->requests[$sock] = &$request; // reactive client for further read $this->server->read($sock); } public function on_request($sock, $raw) { _debug("on_request for client#$sock"); $request = $this->requests[$sock]; // 'wait_for_body' state is reached when ever // application calls recv_body() method // on received $request object if ($request->state() == 'wait_for_body') { $request->body($raw); } else { // break on crlf $lines = explode(HTTP_CRLF, $raw); // parse request line if ($request->state() == 'wait_for_request_line') { list($method, $resource, $version) = explode(" ", $lines[0]); $request->line($method, $resource, $version); unset($lines[0]); _info($request->ip." ".$request->method." ".$request->resource." ".$request->version); } // parse headers foreach ($lines as $line) { $line_parts = explode(":", $line); if (sizeof($line_parts) > 1) { if (strlen($line_parts[0]) > 0) { $k = $line_parts[0]; unset($line_parts[0]); $v = implode(":", $line_parts); $request->set_header($k, $v); } } else if (strlen(trim($line_parts[0])) == 0) { $request->empty_line(); } // if exploded line array size is 1 // and thr is something in $line_parts[0] // must be request body else { $request->body($line); } } } // if request has reached 'headers_received' state? if ($request->state() == 'headers_received') { // dispatch to any matching rule found _debug("delegating to dispatcher for further routing"); $dispatched = $this->dispatcher->dispatch($request); // if no dispatch rule matched call generic callback if (!$dispatched && $this->cb) { _debug("no dispatch rule matched, sending to generic callback"); call_user_func($this->cb, $request); } // else if not dispatched and not generic callbacked // send 404 not_found else if (!$dispatched) { // TODO: send 404 if no callback is registered for this request _debug("dropping request since no matching dispatch rule or generic callback was specified"); $request->not_found('404 Not Found'); } } // if state is not 'headers_received' // reactivate client socket for read event else { $this->server->read($sock); } } } diff --git a/jaxl.php b/jaxl.php index e8a37af..1f10a7f 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,795 +1,795 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger if (isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if (isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if ($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if (!is_dir($this->priv_dir)) mkdir($this->priv_dir); if (!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if (!is_dir($this->pid_dir)) mkdir($this->pid_dir); if (!is_dir($this->log_dir)) mkdir($this->log_dir); if (!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if (!is_array($xeps)) $xeps = array($xeps); foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } - public function add_cb($ev, $cb, $pri=1) { + public function add_cb($ev, $cb, $pri = 1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } - public function set_status($status, $show='chat', $priority=10) { + public function set_status($status, $show = 'chat', $priority = 10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } - public function send_chat_msg($to, $body, $thread=null, $subject=null) { + public function send_chat_msg($to, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type' => 'chat', 'to' => $to, 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } - public function get_vcard($jid=null, $cb=null) { + public function get_vcard($jid = null, $cb = null) { $attrs = array( 'type' => 'get', 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } - public function get_roster($cb=null) { + public function get_roster($cb = null) { $pkt = $this->get_iq_pkt( array( 'type' => 'get', 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } - public function start($opts=array()) { + public function start($opts = array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) $this->enable_debug_shell(); if (@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if ($mechanisms) foreach ($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if ($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach ($mechs as $mech => $any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if ($mech == 'X-FACEBOOK-PLATFORM') { if (@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if ($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if ($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if ($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if (!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach ($query->childrens as $child) { if ($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach ($child->childrens as $group) { if ($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if (!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if (@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if (!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if ($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if ($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if ($type == 'unavailable') { if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if ($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if ($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach ($query->childrens as $k => $child) { if ($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if ($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if ($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach ($query->childrens as $k => $child) { if ($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } diff --git a/xep/xep_0030.php b/xep/xep_0030.php index b5a7ce2..a17cd55 100644 --- a/xep/xep_0030.php +++ b/xep/xep_0030.php @@ -1,89 +1,89 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DISCO_INFO', 'http://jabber.org/protocol/disco#info'); define('NS_DISCO_ITEMS', 'http://jabber.org/protocol/disco#items'); class XEP_0030 extends XMPPXep { // // abstract method // public function init() { return array( ); } // // api methods // public function get_info_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid), new JAXLXml('query', NS_DISCO_INFO) ); } - public function get_info($entity_jid, $callback=null) { + public function get_info($entity_jid, $callback = null) { $pkt = $this->get_info_pkt($entity_jid); if ($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } public function get_items_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid), new JAXLXml('query', NS_DISCO_ITEMS) ); } - public function get_items($entity_jid, $callback=null) { + public function get_items($entity_jid, $callback = null) { $pkt = $this->get_items_pkt($entity_jid); if ($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } // // event callbacks // } diff --git a/xep/xep_0045.php b/xep/xep_0045.php index 5d748e0..46e3c56 100644 --- a/xep/xep_0045.php +++ b/xep/xep_0045.php @@ -1,111 +1,111 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_MUC', 'http://jabber.org/protocol/muc'); class XEP_0045 extends XMPPXep { // // abstract method // public function init() { return array(); } - public function send_groupchat($room_jid, $body, $thread=null, $subject=null) { + public function send_groupchat($room_jid, $body, $thread = null, $subject = null) { $msg = new XMPPMsg( array( 'type' => 'groupchat', 'to' => (($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid), 'from' => $this->jaxl->full_jid->to_string() ), $body, $thread, $subject ); $this->jaxl->send($msg); } // // api methods (occupant use case) // // room_full_jid simply means room jid with nick name as resource public function get_join_room_pkt($room_full_jid, $options) { $pkt = $this->jaxl->get_pres_pkt( array( 'from' => $this->jaxl->full_jid->to_string(), 'to' => (($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid) ) ); $x = $pkt->c('x', NS_MUC); if (isset($options['no_history'])) { $x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0)); } return $x; } public function join_room($room_full_jid, $options = array()) { $pkt = $this->get_join_room_pkt($room_full_jid, $options); $this->jaxl->send($pkt); } public function get_leave_room_pkt($room_full_jid) { return $this->jaxl->get_pres_pkt( array('type' => 'unavailable', 'from' => $this->jaxl->full_jid->to_string(), 'to' => (($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid)) ); } public function leave_room($room_full_jid) { $pkt = $this->get_leave_room_pkt($room_full_jid); $this->jaxl->send($pkt); } // // api methods (moderator use case) // // // event callbacks // } diff --git a/xep/xep_0060.php b/xep/xep_0060.php index f824660..c50ab7e 100644 --- a/xep/xep_0060.php +++ b/xep/xep_0060.php @@ -1,136 +1,136 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_PUBSUB', 'http://jabber.org/protocol/pubsub'); class XEP_0060 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods (entity use case) // // // api methods (subscriber use case) // - public function get_subscribe_pkt($service, $node, $jid=null) { + public function get_subscribe_pkt($service, $node, $jid = null) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('subscribe', null, array('node' => $node, 'jid' => ($jid ? $jid : $this->jaxl->full_jid->to_string()))); return $this->get_iq_pkt($service, $child); } - public function subscribe($service, $node, $jid=null) { + public function subscribe($service, $node, $jid = null) { $this->jaxl->send($this->get_subscribe_pkt($service, $node, $jid)); } public function unsubscribe() { } public function get_subscription_options() { } public function set_subscription_options() { } public function get_node_items() { } // // api methods (publisher use case) // public function get_publish_item_pkt($service, $node, $item) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('publish', null, array('node' => $node)); $child->cnode($item); return $this->get_iq_pkt($service, $child); } public function publish_item($service, $node, $item) { $this->jaxl->send($this->get_publish_item_pkt($service, $node, $item)); } public function delete_item() { } // // api methods (owner use case) // public function get_create_node_pkt($service, $node) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('create', null, array('node' => $node)); return $this->get_iq_pkt($service, $child); } public function create_node($service, $node) { $this->jaxl->send($this->get_create_node_pkt($service, $node)); } // // event callbacks // // // local methods // // this always add attrs - protected function get_iq_pkt($service, $child, $type='set') { + protected function get_iq_pkt($service, $child, $type = 'set') { return $this->jaxl->get_iq_pkt( array('type' => $type, 'from' => $this->jaxl->full_jid->to_string(), 'to' => $service), $child ); } } diff --git a/xep/xep_0249.php b/xep/xep_0249.php index ba4a59f..21761a1 100644 --- a/xep/xep_0249.php +++ b/xep/xep_0249.php @@ -1,78 +1,78 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DIRECT_MUC_INVITATION', 'jabber:x:conference'); class XEP_0249 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods // - public function get_invite_pkt($to_bare_jid, $room_jid, $password=null, $reason=null, $thread=null, $continue=null) { + public function get_invite_pkt($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) { $xattrs = array('jid' => $room_jid); if ($password) $xattrs['password'] = $password; if ($reason) $xattrs['reason'] = $reason; if ($thread) $xattrs['thread'] = $thread; if ($continue) $xattrs['continue'] = $continue; return $this->jaxl->get_msg_pkt( array('from' => $this->jaxl->full_jid->to_string(), 'to' => $to_bare_jid), null, null, null, new JAXLXml('x', NS_DIRECT_MUC_INVITATION, $xattrs) ); } - public function invite($to_bare_jid, $room_jid, $password=null, $reason=null, $thread=null, $continue=null) { + public function invite($to_bare_jid, $room_jid, $password = null, $reason = null, $thread = null, $continue = null) { $this->jaxl->send($this->get_invite_pkt($to_bare_jid, $room_jid, $password, $reason, $thread, $continue)); } // // event callbacks // } diff --git a/xmpp/xmpp_msg.php b/xmpp/xmpp_msg.php index 16c588a..7e1eb97 100644 --- a/xmpp/xmpp_msg.php +++ b/xmpp/xmpp_msg.php @@ -1,50 +1,50 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; class XMPPMsg extends XMPPStanza { - public function __construct($attrs, $body=null, $thread=null, $subject=null) { + public function __construct($attrs, $body = null, $thread = null, $subject = null) { parent::__construct('message', $attrs); if ($body) $this->c('body')->t($body)->up(); if ($thread) $this->c('thread')->t($thread)->up(); if ($subject) $this->c('subject')->t($subject)->up(); } } diff --git a/xmpp/xmpp_pres.php b/xmpp/xmpp_pres.php index 411a746..c9a7bce 100644 --- a/xmpp/xmpp_pres.php +++ b/xmpp/xmpp_pres.php @@ -1,50 +1,50 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; class XMPPPres extends XMPPStanza { - public function __construct($attrs, $status=null, $show=null, $priority=null) { + public function __construct($attrs, $status = null, $show = null, $priority = null) { parent::__construct('presence', $attrs); if ($status) $this->c('status')->t($status)->up(); if ($show) $this->c('show')->t($show)->up(); if ($priority) $this->c('priority')->t($priority)->up(); } } diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php index d6abcaf..3fb73a5 100644 --- a/xmpp/xmpp_stanza.php +++ b/xmpp/xmpp_stanza.php @@ -1,173 +1,173 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; /** * Generic xmpp stanza object which provide convinient access pattern over xml objects * Also to be able to convert an existing xml object into stanza object (to get access patterns going) * this class doesn't extend xml, but infact works on a reference of xml object * If not provided during constructor, new xml object is created and saved as reference * * @author abhinavsingh * */ class XMPPStanza { private $xml; - public function __construct($name, $attrs=array(), $ns=NS_JABBER_CLIENT) { + public function __construct($name, $attrs = array(), $ns = NS_JABBER_CLIENT) { if ($name instanceof JAXLXml) $this->xml = $name; else $this->xml = new JAXLXml($name, $ns, $attrs); } public function __call($method, $args) { return call_user_func_array(array($this->xml, $method), $args); } public function __get($prop) { switch($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': return @$this->xml->attrs[$prop] ? $this->xml->attrs[$prop] : null; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val = @$this->xml->attrs[$attr] ? $this->xml->attrs[$attr] : null; if (!$val) return null; $val = new XMPPJid($val); return $val->$key; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val = $this->xml->exists($prop); if (!$val) return null; return $val->text; break; default: return null; break; } } public function __set($prop, $val) { switch($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop = $val; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': $this->xml->attrs[$prop] = $val; return true; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val1 = @$this->xml->attrs[$attr]; if (!$val1) $val1 = ''; $val1 = new XMPPJid($val1); $val1->$key = $val; $this->xml->attrs[$attr] = $val1->to_string(); return true; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val1 = $this->xml->exists($prop); if (!$val1) $this->xml->c($prop)->t($val)->up(); else $this->xml->update($prop, $val1->ns, $val1->attrs, $val); return true; break; default: return null; break; } } } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index 0565915..b9d9645 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,657 +1,657 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // - public function __construct($transport, $jid, $pass=null, $resource=null, $force_tls=false) { + public function __construct($transport, $jid, $pass = null, $resource = null, $force_tls = false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if (isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; if (isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if (strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if (!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc' => $nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if (isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } - public function get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null) { + public function get_msg_pkt($attrs, $body = null, $thread = null, $subject = null, $payload = null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if (!$msg->id) $msg->id = $this->get_id(); if ($payload) $msg->cnode($payload); return $msg; } - public function get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null) { + public function get_pres_pkt($attrs, $status = null, $show = null, $priority = null, $payload = null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if (!$pres->id) $pres->id = $this->get_id(); if ($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if (!$iq->id) $iq->id = $this->get_id(); if ($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } else if (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach ($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach (array('realm', 'cnonce', 'digest-uri') as $key) if (!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if (isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if ($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } else if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } else if ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if ($stanza->name == 'message') { $this->handle_message($stanza); } else if ($stanza->name == 'presence') { $this->handle_presence($stanza); } else if ($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } }
jaxl/JAXL
86db1d7f354f7d10f91c7a5da7b7850671e69adb
Fix PSR: File has mixed line endings
diff --git a/jaxl.php b/jaxl.php index b35ce90..e8a37af 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,644 +1,644 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; - - // setup logger - if (isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; - //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; - if (isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; + + // setup logger + if (isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; + //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; + if (isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; - + // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if ($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if (!is_dir($this->priv_dir)) mkdir($this->priv_dir); if (!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if (!is_dir($this->pid_dir)) mkdir($this->pid_dir); if (!is_dir($this->log_dir)) mkdir($this->log_dir); if (!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if (!is_array($xeps)) $xeps = array($xeps); foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type' => 'chat', 'to' => $to, 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type' => 'get', 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type' => 'get', 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) $this->enable_debug_shell(); if (@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if ($mechanisms) foreach ($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if ($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach ($mechs as $mech => $any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if ($mech == 'X-FACEBOOK-PLATFORM') { if (@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass);
jaxl/JAXL
c92735f02311e3dcad918a5ffaf6e8ebceef4b36
Fix PSR: Expected "} else"; found "}\n else"
diff --git a/core/jaxl_cli.php b/core/jaxl_cli.php index c49d063..8c1ab01 100644 --- a/core/jaxl_cli.php +++ b/core/jaxl_cli.php @@ -1,94 +1,93 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLCli { public static $counter = 0; private $in = null; private $quit_cb = null; private $recv_cb = null; private $recv_chunk_size = 1024; public function __construct($recv_cb=null, $quit_cb=null) { $this->recv_cb = $recv_cb; $this->quit_cb = $quit_cb; // catch read event on stdin $this->in = fopen('php://stdin', 'r'); stream_set_blocking($this->in, false); JAXLLoop::watch($this->in, array( 'read' => array(&$this, 'on_read_ready') )); } public function __destruct() { @fclose($this->in); } public function stop() { JAXLLoop::unwatch($this->in, array( 'read' => true )); } public function on_read_ready($in) { $raw = @fread($in, $this->recv_chunk_size); if (ord($raw) == 10) { // enter key JAXLCli::prompt(false); return; - } - else if (trim($raw) == 'quit') { + } else if (trim($raw) == 'quit') { $this->stop(); $this->in = null; if ($this->quit_cb) call_user_func($this->quit_cb); return; } if ($this->recv_cb) call_user_func($this->recv_cb, $raw); } public static function prompt($inc=true) { if ($inc) ++self::$counter; echo "jaxl ".self::$counter."> "; } } diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php index d2b380e..81cbc88 100644 --- a/core/jaxl_clock.php +++ b/core/jaxl_clock.php @@ -1,123 +1,121 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class JAXLClock { // current clock time in microseconds private $tick = 0; // current Unix timestamp with microseconds public $time = null; // scheduled jobs public $jobs = array(); public function __construct() { $this->time = microtime(true); } public function __destruct() { _info("shutting down clock server..."); } public function tick($by=null) { // update clock if ($by) { $this->tick += $by; $this->time += $by / pow(10,6); - } - else { + } else { $time = microtime(true); $by = $time - $this->time; $this->tick += $by * pow(10, 6); $this->time = $time; } // run scheduled jobs foreach ($this->jobs as $ref => $job) { if ($this->tick >= $job['scheduled_on'] + $job['after']) { //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".$job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); call_user_func($job['cb'], $job['args']); if (!$job['is_periodic']) { unset($this->jobs[$ref]); - } - else { + } else { $job['scheduled_on'] = $this->tick; $job['runs']++; $this->jobs[$ref] = $job; } } } } // calculate execution time of callback public function tc($callback, $args=null) { } // callback after $time microseconds public function call_fun_after($time, $callback, $args=null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => false, 'runs' => 0 ); return sizeof($this->jobs); } // callback periodically after $time microseconds public function call_fun_periodic($time, $callback, $args=null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => true, 'runs' => 0 ); return sizeof($this->jobs); } // cancel a previously scheduled callback public function cancel_fun_call($ref) { unset($this->jobs[$ref-1]); } } diff --git a/core/jaxl_exception.php b/core/jaxl_exception.php index d49544d..72d6db1 100644 --- a/core/jaxl_exception.php +++ b/core/jaxl_exception.php @@ -1,92 +1,91 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ error_reporting(E_ALL | E_STRICT); /** * * @author abhinavsingh */ class JAXLException extends Exception { public function __construct($message = null, $code = null, $file = null, $line = null) { _notice("got jaxl exception construct with $message, $code, $file, $line"); if ($code === null) { parent::__construct($message); - } - else { + } else { parent::__construct($message, $code); } if ($file !== null) { $this->file = $file; } if ($line !== null) { $this->line = $line; } } public static function error_handler($errno, $error, $file, $line, $vars) { _debug("error handler called with $errno, $error, $file, $line"); if ($errno === 0 || ($errno & error_reporting()) === 0) { return; } throw new JAXLException($error, $errno, $file, $line); } public static function exception_handler($e) { _debug("exception handler catched ".json_encode($e)); // TODO: Pretty print backtrace //print_r(debug_backtrace()); } public static function shutdown_handler() { try { _debug("got shutdown handler"); if (null !== ($error = error_get_last())) { throw new JAXLException($error['message'], $error['type'], $error['file'], $error['line']); } } catch(Exception $e) { _debug("shutdown handler catched with exception ".json_encode($e)); } } } diff --git a/core/jaxl_fsm.php b/core/jaxl_fsm.php index 7f4c1f5..7b18cce 100644 --- a/core/jaxl_fsm.php +++ b/core/jaxl_fsm.php @@ -1,81 +1,80 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ abstract class JAXLFsm { protected $state = null; // abstract method abstract public function handle_invalid_state($r); public function __construct($state) { $this->state = $state; } // returned value from state callbacks can be: // 1) array() <-- is_callable method // 2) array([0] => 'new_state', [1] => 'return value for current callback') <-- is_not_callable method // 3) array([0] => 'new_state') // 4) 'new_state' // // for case 1) new state will be an array // for other cases new state will be a string public function __call($event, $args) { if ($this->state) { // call state method _debug("calling state handler '".(is_array($this->state) ? $this->state[1] : $this->state)."' for incoming event '".$event."'"); $call = is_callable($this->state) ? $this->state : (method_exists($this, $this->state) ? array(&$this, $this->state): $this->state); $r = call_user_func($call, $event, $args); // 4 cases of possible return value if (is_callable($r)) $this->state = $r; else if (is_array($r) && sizeof($r) == 2) list($this->state, $ret) = $r; else if (is_array($r) && sizeof($r) == 1) $this->state = $r[0]; else if (is_string($r)) $this->state = $r; else $this->handle_invalid_state($r); _debug("current state '".(is_array($this->state) ? $this->state[1] : $this->state)."'"); // return case if (!is_callable($r) && is_array($r) && sizeof($r) == 2) return $ret; - } - else { + } else { _debug("invalid state found, nothing called for event ".$event.""); } } } diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index b58a796..1c3f8f1 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,156 +1,154 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLLoop { public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; private function __construct() {} private function __clone() {} public static function watch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } if (isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function unwatch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; if (isset(self::$read_fds[$fdid])) { unset(self::$read_fds[$fdid]); unset(self::$read_cbs[$fdid]); --self::$active_read_fds; } } if (isset($opts['write'])) { $fdid = (int) $fd; if (isset(self::$write_fds[$fdid])) { unset(self::$write_fds[$fdid]); unset(self::$write_cbs[$fdid]); --self::$active_write_fds; } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function run() { if (!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); while ((self::$active_read_fds + self::$active_write_fds) > 0) self::select(); _debug("no more active fd's to select"); self::$is_running = false; } } private static function select() { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); if ($changed === false) { _error("error in the event loop, shutting down..."); /*foreach (self::$read_fds as $fd) { if (is_resource($fd)) print_r(stream_get_meta_data($fd)); }*/ exit; - } - else if ($changed > 0) { + } else if ($changed > 0) { // read callback foreach ($read as $r) { $fdid = array_search($r, self::$read_fds); if (isset(self::$read_fds[$fdid])) call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); } // write callback foreach ($write as $w) { $fdid = array_search($w, self::$write_fds); if (isset(self::$write_fds[$fdid])) call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); } self::$clock->tick(); - } - else if ($changed === 0) { + } else if ($changed === 0) { //_debug("nothing changed while selecting for read"); self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); } } } diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php index cbad13a..0664a08 100644 --- a/core/jaxl_pipe.php +++ b/core/jaxl_pipe.php @@ -1,112 +1,110 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * bidirectional communication pipes for processes * * This is how this will be (when complete): * $pipe = new JAXLPipe() will return an array of size 2 * $pipe[0] represents the read end of the pipe * $pipe[1] represents the write end of the pipe * * Proposed functionality might even change (currently consider this as experimental) * * @author abhinavsingh * */ class JAXLPipe { protected $perm = 0600; protected $recv_cb = null; protected $fd = null; protected $client = null; public $name = null; public function __construct($name, $read_cb=null) { $pipes_folder = JAXL_CWD.'/.jaxl/pipes'; if (!is_dir($pipes_folder)) mkdir($pipes_folder); $this->ev = new JAXLEvent(); $this->name = $name; $this->read_cb = $read_cb; $pipe_path = $this->get_pipe_file_path(); if (!file_exists($pipe_path)) { posix_mkfifo($pipe_path, $this->perm); $this->fd = fopen($pipe_path, 'r+'); if (!$this->fd) { _error("unable to open pipe"); - } - else { + } else { _debug("pipe opened using path $pipe_path"); _notice("Usage: $ echo 'Hello World!' > $pipe_path"); $this->client = new JAXLSocketClient(); $this->client->connect($this->fd); $this->client->set_callback(array(&$this, 'on_data')); } - } - else { + } else { _error("pipe with name $name already exists"); } } public function __destruct() { @fclose($this->fd); @unlink($this->get_pipe_file_path()); _debug("unlinking pipe file"); } public function get_pipe_file_path() { return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe'; } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function on_data($data) { // callback if ($this->recv_cb) call_user_func($this->recv_cb, $data); } } diff --git a/core/jaxl_sock5.php b/core/jaxl_sock5.php index 93a4f45..8eea396 100644 --- a/core/jaxl_sock5.php +++ b/core/jaxl_sock5.php @@ -1,125 +1,124 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ class JAXLSock5 { private $client = null; protected $transport = null; protected $ip = null; protected $port = null; public function __construct($transport='tcp') { $this->transport = $transport; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } public function __destruct() { } public function connect($ip, $port=1080) { $this->ip = $ip; $this->port = $port; $sock_path = $this->_sock_path(); if ($this->client->connect($sock_path)) { _debug("established connection to $sock_path"); return true; - } - else { + } else { _error("unable to connect $sock_path"); return false; } } // // Three phases of SOCK5 // // Negotiation pkt consists of 3 part: // 0x05 => Sock protocol version // 0x01 => Number of method identifier octet // // Following auth methods are defined: // 0x00 => No authentication required // 0x01 => GSSAPI // 0x02 => USERNAME/PASSWORD // 0x03 to 0x7F => IANA ASSIGNED // 0x80 to 0xFE => RESERVED FOR PRIVATE METHODS // 0xFF => NO ACCEPTABLE METHODS public function negotiate() { $pkt = pack("C3", 0x05, 0x01, 0x00); $this->client->send($pkt); // enter sub-negotiation state } public function relay_request() { // enter wait for reply state } public function send_data() { } // // Socket client callback // public function on_response($raw) { _debug($raw); } // // Private // protected function _sock_path() { return $this->transport.'://'.$this->ip.':'.$this->port; } } diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index 8185e13..ef54dba 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,216 +1,214 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; public function __construct($stream_context=null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ public function connect($socket_path) { if (gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); if (sizeof($path_parts) == 3) $this->port = $path_parts[2]; _info("trying ".$socket_path); if ($this->stream_context) $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); else $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); - } - else { + } else { $this->fd = &$socket_path; } if ($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; - } - else { + } else { _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); $this->disconnect(); return false; } } public function disconnect() { JAXLLoop::unwatch($this->fd, array( 'read' => true, 'write' => true )); @fclose($this->fd); $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); return $ret; } public function send($data) { $this->obuffer .= $data; // add watch for write events if ($this->writing) return; JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if ($bytes === 0) { $meta = stream_get_meta_data($fd); if ($meta['eof'] === TRUE) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); if ($bytes > 0) _debug($raw); // callback if ($this->recv_cb) call_user_func($this->recv_cb, $raw); } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if (strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } } diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index f82abdf..7c447cf 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,255 +1,250 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLSocketServer { public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; public function __construct($path, $accept_cb, $request_cb) { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; $ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog))); if (($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { if (@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); - } - else { + } else { _error("unable to set non block flag"); } - } - else { + } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } public function __destruct() { _info("shutting down socket server"); } public function read($client_id) { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } public function send($client_id, $data) { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } public function close($client_id) { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } public function on_server_accept_ready($server) { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); if (!$client) { _error("unable to accept new client conn"); return; } if (@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do if ($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); } // if no accept callback is registered // close the accepted connection else { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } - } - else { + } else { _error("unable to set non block flag"); } } public function on_client_read_ready($client) { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); if ($bytes === 0) { $meta = stream_get_meta_data($client); if ($meta['eof'] === TRUE) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); @fclose($client); unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; if ($this->request_cb) call_user_func($this->request_cb, $client_id, $total); $this->clients[$client_id]['ibuffer'] = ''; } public function on_client_write_ready($client) { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); if ($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; - } - else if ($written == strlen($total) || $written == $this->send_chunk_size) { + } else if ($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); - } - else { + } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler if (strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } } catch(JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // protected function add_read_cb($client_id) { if ($this->clients[$client_id]['reading']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } protected function add_write_cb($client_id) { if ($this->clients[$client_id]['writing']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } protected function del_read_cb($client_id) { if (!$this->clients[$client_id]['reading']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } protected function del_write_cb($client_id) { if (!$this->clients[$client_id]['writing']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } } diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index 97110a4..ef2604f 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,196 +1,191 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if (is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; - } - else { + } else { $this->ns = $argv[1]; if (is_array($argv[2])) { $this->attrs = $argv[2]; - } - else { + } else { $this->text = $argv[2]; } } break; case 2: if (is_array($argv[1])) { $this->attrs = $argv[1]; - } - else { + } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; foreach ($attrs as $k => $v) { if ($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } public function t($text, $append=FALSE) { if (!$append) { $this->rover->text = $text; - } - else { + } else { if ($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; } return $this; } public function c($name, $ns=null, $attrs=array(), $text=null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { if ($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } public function top() { $this->rover = &$this; return $this; } public function exists($name, $ns=null, $attrs=array()) { foreach ($this->childrens as $child) { if ($ns) { if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; - } - else if ($child->name == $name && $child->match_attrs($attrs)) { + } else if ($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } public function update($name, $ns=null, $attrs=array(), $text=null) { foreach ($this->childrens as $k => $child) { if ($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } public function to_string($parent_ns=null) { $xml = ''; $xml .= '<'.$this->name; if ($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; foreach ($this->attrs as $k => $v) if (!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; foreach ($this->childrens as $child) $xml .= $child->to_string($this->ns); if ($this->text) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } } diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php index 0160c1d..d3b4766 100644 --- a/core/jaxl_xml_stream.php +++ b/core/jaxl_xml_stream.php @@ -1,188 +1,184 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Enter description here ... * @author abhinavsingh * */ class JAXLXmlStream { private $delimiter = '\\'; private $ns; private $parser; private $stanza; private $depth = -1; private $start_cb; private $stanza_cb; private $end_cb; public function __construct() { $this->init_parser(); } private function init_parser() { $this->depth = -1; $this->parser = xml_parser_create_ns("UTF-8", $this->delimiter); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); xml_set_character_data_handler($this->parser, array(&$this, "handle_character")); xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag")); } public function __destruct() { //_debug("cleaning up xml parser..."); @xml_parser_free($this->parser); } public function reset_parser() { $this->parse_final(null); @xml_parser_free($this->parser); $this->parser = null; $this->init_parser(); } public function set_callback($start_cb, $end_cb, $stanza_cb) { $this->start_cb = $start_cb; $this->end_cb = $end_cb; $this->stanza_cb = $stanza_cb; } public function parse($str) { xml_parse($this->parser, $str, false); } public function parse_final($str) { xml_parse($this->parser, $str, true); } protected function handle_start_tag($parser, $name, $attrs) { $name = $this->explode($name); //echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL; // replace ns with prefix foreach ($attrs as $key => $v) { $k = $this->explode($key); // no ns specified if ($k[0] == null) { $attrs[$k[1]] = $v; } // xml ns else if ($k[0] == NS_XML) { unset($attrs[$key]); $attrs['xml:'.$k[1]] = $v; - } - else { + } else { _error("==================> unhandled ns prefix on attribute"); // remove attribute else will cause error with bad stanza format // report to developer if above error message is ever encountered unset($attrs[$key]); } } if ($this->depth <= 0) { $this->depth = 0; $this->ns = $name[1]; if ($this->start_cb) { $stanza = new JAXLXml($name[1], $name[0], $attrs); call_user_func($this->start_cb, $stanza); } - } - else { + } else { if (!$this->stanza) { $stanza = new JAXLXml($name[1], $name[0], $attrs); $this->stanza = &$stanza; - } - else { + } else { $this->stanza->c($name[1], $name[0], $attrs); } } ++$this->depth; } protected function handle_end_tag($parser, $name) { $name = explode($this->delimiter, $name); $name = sizeof($name) == 1 ? array('', $name[0]) : $name; //echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL; if ($this->depth == 1) { if ($this->end_cb) { $stanza = new JAXLXml($name[1], $this->ns); call_user_func($this->end_cb, $stanza); } - } - else if ($this->depth > 1) { + } else if ($this->depth > 1) { if ($this->stanza) $this->stanza->up(); if ($this->depth == 2) { if ($this->stanza_cb) { call_user_func($this->stanza_cb, $this->stanza); $this->stanza = null; } } } --$this->depth; } protected function handle_character($parser, $data) { //echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL; if ($this->stanza) { $this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), TRUE); } } private function implode($data) { return implode($this->delimiter, $data); } private function explode($data) { $data = explode($this->delimiter, $data); $data = sizeof($data) == 1 ? array(null, $data[0]) : $data; return $data; } } diff --git a/docs/users/http_examples.rst b/docs/users/http_examples.rst index 61f1c2c..990fd05 100644 --- a/docs/users/http_examples.rst +++ b/docs/users/http_examples.rst @@ -1,102 +1,99 @@ HTTP Examples ============= Writing HTTP Server ------------------- Intialize an ``HTTPServer`` instance .. code-block:: ruby require_once 'jaxl.php'; require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this. Define a callback method that will accept all incoming ``HTTPRequest`` objects .. code-block:: ruby function on_request($request) { if ($request->method == 'GET') { $body = json_encode($request); $request->ok($body, array('Content-Type' => 'application:json')); - } - else { + } else { $request->not_found(); } } ``on_request`` callback method will receive a ``HTTPRequest`` object instance. For this example, we will simply echo back json encoded ``$request`` object for every http GET request. Start http server: .. code-block:: ruby $http->start('on_request'); We pass ``on_request`` method as first parameter to ``HTTPServer::start/1``. If nothing is passed, requests will fail with a default 404 not found error message Writing REST API Server ----------------------- Intialize an ``HTTPServer`` instance .. code-block:: ruby require_once 'jaxl.php'; require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this. Define our REST resources callback methods: .. code-block:: ruby function index($request) { $request->send_response( 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } function upload($request) { if ($request->method == 'GET') { $request->send_response( 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action=""><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' ); - } - else if ($request->method == 'POST') { + } else if ($request->method == 'POST') { if ($request->body === null && $request->expect) { $request->recv_body(); - } - else { + } else { // got upload body, save it _debug("file upload complete, got ".strlen($request->body)." bytes of data"); $request->close(); } } } Next we need to register dispatch rules for our callbacks above: .. code-block:: ruby $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); $rules = array($index, $upload); $http->dispatch($rules); Start REST api server: .. code-block:: ruby $http->start(); Make an HTTP request -------------------- diff --git a/examples/http_rest_server.php b/examples/http_rest_server.php index 76c924e..7f32dc1 100644 --- a/examples/http_rest_server.php +++ b/examples/http_rest_server.php @@ -1,117 +1,115 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // print usage notice and parse addr/port parameters if passed _colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE); $port = ($argc == 2 ? $argv[1] : 9699); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer($port); // callback method for dispatch rule (see below) function index($request) { $request->send_response( 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } // callback method for dispatch rule (see below) function upload($request) { if ($request->method == 'GET') { $request->ok(array( 'Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' ); - } - else if ($request->method == 'POST') { + } else if ($request->method == 'POST') { if ($request->body === null && $request->expect) { $request->recv_body(); - } - else { + } else { // got upload body, save it _info("file upload complete, got ".strlen($request->body)." bytes of data"); $upload_data = $request->multipart->form_data[0]['body']; $request->ok($upload_data, array('Content-Type' => $request->multipart->form_data[0]['headers']['Content-Type'])); } } } // add dispatch rules with callback method as first argument $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); // some REST CRUD style callback methods // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules function create_event($request) { _info("got event create request"); $request->close(); } function read_event($request, $pk) { _info("got event read request for $pk"); $request->close(); } function update_event($request, $pk) { _info("got event update request for $pk"); $request->close(); } function delete_event($request, $pk) { _info("got event delete request for $pk"); $request->close(); } $event_create = array('create_event', '^/event/create/$', array('PUT')); $event_read = array('read_event', '^/event/(?P<pk>\d+)/$', array('GET', 'HEAD')); $event_update = array('update_event', '^/event/(?P<pk>\d+)/$', array('POST')); $event_delete = array('delete_event', '^/event/(?P<pk>\d+)/$', array('DELETE')); // prepare rule set $rules = array($index, $upload, $event_create, $event_read, $event_update, $event_delete); $http->dispatch($rules); // start http server $http->start(); diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index bcf2f4a..2cebe70 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,144 +1,139 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 5) { echo "Usage: $argv[0] host jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[2], 'pass' => $argv[3], 'host' => $argv[1], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC '0203', // Delayed Delivery '0199' // XMPP Ping )); // // add necessary event callbacks here // $_room_full_jid = $argv[4]."/".$argv[5]; $room_full_jid = new XMPPJid($_room_full_jid); $client->add_cb('on_auth_success', function() { global $client, $room_full_jid; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // join muc room $client->xeps['0045']->join_room($room_full_jid); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_groupchat_message', function($stanza) { global $client; $from = new XMPPJid($stanza->from); $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); if ($from->resource) { echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; - } - else { + } else { $subject = $stanza->exists('subject'); if ($subject) { echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } } }); $client->add_cb('on_presence_stanza', function($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { if (($status = $x->exists('status', null, array('code' => '110'))) !== false) { $item = $x->exists('item'); _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); - } - else { + } else { _info("xmlns #user have no x child element"); } - } - else { + } else { _warning("=======> odd case 1"); } } // stanza from other users received else if (strtolower($from->bare) == strtolower($room_full_jid->bare)) { if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; - } - else { + } else { _warning("=======> odd case 2"); } - } - else { + } else { _warning("=======> odd case 3"); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/register_user.php b/examples/register_user.php index 3c805c0..480cfac 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,167 +1,164 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // $form = array(); function wait_for_register_response($event, $args) { global $client, $form; if ($event == 'stanza_cb') { $stanza = $args[0]; if ($stanza->name == 'iq') { $form['type'] = $stanza->attrs['type']; if ($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; - } - else if ($stanza->attrs['type'] == 'error') { + } else if ($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } } - } - else { + } else { _notice("unhandled event $event rcvd"); } } function wait_for_register_form($event, $args) { global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if ($query) { $instructions = $query->exists('instructions'); if ($instructions) { echo $instructions->text.PHP_EOL; } foreach ($query->childrens as $k => $child) { if ($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; - } - else { + } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // $client->add_cb('on_stream_features', function($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; }); $client->add_cb('on_disconnect', function() { global $form; _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); }); // // finally start configured xmpp stream // $client->start(); // // if registration was successful // try to connect with newly registered account // if ($form['type'] == 'result') { _info("connecting newly registered user account"); $client = new JAXL(array( 'jid' => $form['username'].'@'.$argv[1], 'pass' => $form['password'], 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', function() { global $client; $client->set_status('Available'); }); $client->start(); } echo "done\n"; diff --git a/examples/subscriber.php b/examples/subscriber.php index 3a21966..899278f 100644 --- a/examples/subscriber.php +++ b/examples/subscriber.php @@ -1,97 +1,96 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // create node //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); // subscribe $client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node'); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_headline_message', function($stanza) { global $client; if (($event = $stanza->exists('event', NS_PUBSUB.'#event'))) { _info("got pubsub event"); - } - else { + } else { _warning("unknown headline message rcvd"); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/http/http_client.php b/http/http_client.php index d04576c..5c9aaaa 100644 --- a/http/http_client.php +++ b/http/http_client.php @@ -1,135 +1,134 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ class HTTPClient { private $url = null; private $parts = array(); private $headers = array(); private $data = null; public $method = null; private $client = null; public function __construct($url, $headers=array(), $data=null) { $this->url = $url; $this->headers = $headers; $this->data = $data; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } public function start($method='GET') { $this->method = $method; $this->parts = parse_url($this->url); $transport = $this->_transport(); $ip = $this->_ip(); $port = $this->_port(); $socket_path = $transport.'://'.$ip.':'.$port; if ($this->client->connect($socket_path)) { _debug("connection to $this->url established"); // send request data $this->send_request(); // start main loop JAXLLoop::run(); - } - else { + } else { _debug("unable to open $this->url"); } } public function on_response($raw) { _info("got http response"); } protected function send_request() { $this->client->send($this->_line()."\r\n"); $this->client->send($this->_ua()."\r\n"); $this->client->send($this->_host()."\r\n"); $this->client->send("\r\n"); } // // private methods on uri parts // private function _line() { return $this->method.' '.$this->_uri().' HTTP/1.1'; } private function _ua() { return 'User-Agent: jaxl_http_client/3.x'; } private function _host() { return 'Host: '.$this->parts['host'].':'.$this->_port(); } private function _transport() { return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl'); } private function _ip() { return gethostbyname($this->parts['host']); } private function _port() { return @$this->parts['port'] ? $this->parts['port'] : 80; } private function _uri() { $uri = $this->parts['path']; if (@$this->parts['query']) $uri .= '?'.$this->parts['query']; if (@$this->parts['fragment']) $uri .= '#'.$this->parts['fragment']; return $uri; } } diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php index 4c9a6d4..2829a0d 100644 --- a/http/http_dispatcher.php +++ b/http/http_dispatcher.php @@ -1,117 +1,117 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // // (optionally) set an array of url dispatch rules // each dispatch rule is defined by an array of size 4 like: // array($callback, $pattern, $methods, $extra), where // $callback the method which will be called if this rule matches // $pattern regular expression to match request path // $methods list of allowed methods for this rule // pass boolean true to allow all http methods // if omitted or an empty array() is passed (which actually doesnt make sense) // by default 'GET' will be the method allowed on this rule // $extra reserved for future (you can totally omit this as of now) // class HTTPDispatchRule { // match callback public $cb = null; // regexp to match on request path public $pattern = null; // methods to match upon // add atleast 1 method for this rule to work public $methods = null; // other matching rules public $extra = array(); public function __construct($cb, $pattern, $methods=array('GET'), $extra=array()) { $this->cb = $cb; $this->pattern = $pattern; $this->methods = $methods; $this->extra = $extra; } public function match($path, $method) { if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) { if (in_array($method, $this->methods)) { return $matches; } } return false; } } class HTTPDispatcher { protected $rules = array(); public function __construct() { $this->rules = array(); } public function add_rule($rule) { $s = sizeof($rule); if ($s > 4) { _debug("invalid rule"); return; } // fill up defaults - if ($s == 3) { $rule[] = array(); } - else if ($s == 2) { $rule[] = array('GET'); $rule[] = array(); } - else { _debug("invalid rule"); return; } + if ($s == 3) { $rule[] = array(); + } else if ($s == 2) { $rule[] = array('GET'); $rule[] = array(); + } else { _debug("invalid rule"); return; } $this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]); } public function dispatch($request) { foreach ($this->rules as $rule) { //_debug("matching $request->path with pattern $rule->pattern"); if (($matches = $rule->match($request->path, $request->method)) !== false) { _debug("matching rule found, dispatching"); $params = array($request); // TODO: a bad way to restrict on 'pk', fix me for generalization if (@isset($matches['pk'])) $params[] = $matches['pk']; call_user_func_array($rule->cb, $params); return true; } } return false; } } diff --git a/http/http_multipart.php b/http/http_multipart.php index 245bfcd..7a0b5c5 100644 --- a/http/http_multipart.php +++ b/http/http_multipart.php @@ -1,173 +1,161 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; class HTTPMultiPart extends JAXLFsm { public $boundary = null; public $form_data = array(); public $index = -1; public function handle_invalid_state($r) { _error("got invalid event $r"); } public function __construct($boundary) { $this->boundary = $boundary; parent::__construct('wait_for_boundary_start'); } public function state() { return $this->state; } public function wait_for_boundary_start($event, $data) { if ($event == 'process') { if ($data[0] == '--'.$this->boundary) { $this->index += 1; $this->form_data[$this->index] = array( 'meta' => array(), 'headers' => array(), 'body' => '' ); return array('wait_for_content_disposition', true); - } - else { + } else { _warning("invalid boundary start $data[0] while expecting $this->boundary"); return array('wait_for_boundary_start', false); } - } - else { + } else { _warning("invalid $event rcvd"); return array('wait_for_boundary_start', false); } } public function wait_for_content_disposition($event, $data) { if ($event == 'process') { $disposition = explode(":", $data[0]); if (strtolower(trim($disposition[0])) == 'content-disposition') { $this->form_data[$this->index]['headers'][$disposition[0]] = trim($disposition[1]); $meta = explode(";", $disposition[1]); if (trim(array_shift($meta)) == 'form-data') { foreach ($meta as $k) { list($k, $v) = explode("=", $k); $this->form_data[$this->index]['meta'][$k] = $v; } return array('wait_for_content_type', true); - } - else { + } else { _warning("first part of meta is not form-data"); return array('wait_for_content_disposition', false); } - } - else { + } else { _warning("not a valid content-disposition line"); return array('wait_for_content_disposition', false); } - } - else { + } else { _warning("invalid $event rcvd"); return array('wait_for_content_disposition', false); } } public function wait_for_content_type($event, $data) { if ($event == 'process') { $type = explode(":", $data[0]); if (strtolower(trim($type[0])) == 'content-type') { $this->form_data[$this->index]['headers'][$type[0]] = trim($type[1]); $this->form_data[$this->index]['meta']['type'] = $type[1]; return array('wait_for_content_body', true); - } - else { + } else { _debug("not a valid content-type line"); return array('wait_for_content_type', false); } - } - else { + } else { _warning("invalid $event rcvd"); return array('wait_for_content_type', false); } } public function wait_for_content_body($event, $data) { if ($event == 'process') { if ($data[0] == '--'.$this->boundary) { _debug("start of new multipart/form-data detected"); return array('wait_for_content_disposition', true); - } - else if ($data[0] == '--'.$this->boundary.'--') { + } else if ($data[0] == '--'.$this->boundary.'--') { _debug("end of multipart form data detected"); return array('wait_for_empty_line', true); - } - else { + } else { $this->form_data[$this->index]['body'] .= $data[0]; return array('wait_for_content_body', true); } - } - else { + } else { _warning("invalid $event rcvd"); return array('wait_for_content_body', false); } } public function wait_for_empty_line($event, $data) { if ($event == 'process') { if ($data[0] == '') { return array('done', true); - } - else { + } else { _warning("invalid empty line $data[0] received"); return array('wait_for_empty_line', false); } - } - else { + } else { _warning("got $event in done state with data $data[0]"); return array('wait_for_empty_line', false); } } public function done($event, $data) { _warning("got unhandled event $event with data $data[0]"); return array('done', false); } } diff --git a/http/http_request.php b/http/http_request.php index d023dfc..076a01a 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,488 +1,479 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers=array(), $body=null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if (sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation // public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; if ($this->body === null) $this->body = $rcvd; else $this->body .= $rcvd; if ($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach ($form_data as $data) { //_debug("passing $data to multipart fsm"); if (!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; - } - else { + } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if (!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; - } - else { + } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if (!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; - } - else { + } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { switch($event) { case 'empty_line': return 'headers_received'; break; default: if (substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if (method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; - } - else { + } else { _debug("non-existant method $event called"); return 'headers_received'; } - } - else if (@isset($this->shortcuts[$event])) { + } else if (@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); - } - else { + } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { $k = trim($k); $v = ltrim($v); // is expect header? if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if (strtolower($k) == 'content-type') { $ctype = explode(';', $v); if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if (strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if ($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { if (sizeof($args) == 0) { $body = null; $headers = array(); } if (sizeof($args) == 1) { // http headers or body only received if (is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; - } - else { + } else { // body only $body = $args[0]; $headers = array(); } - } - else if (sizeof($args) == 2) { + } else if (sizeof($args) == 2) { // body and http headers both received if (is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; - } - else { + } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { foreach ($headers as $k => $v) $this->_send_header($k, $v); } protected function _send_body($body) { $this->_send($body); } protected function _send_response($code, $headers=array(), $body=null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set if ($body && !isset($headers['Content-Length'])) $headers['Content-Length'] = strlen($body); // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); if ($body) $this->_send_body(HTTP_CRLF.$body); } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if (sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach ($query as $q) { $q = explode("=", $q); if (sizeof($q) == 1) $q[1] = ""; $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } } diff --git a/http/http_server.php b/http/http_server.php index 67220f6..7b1ceef 100644 --- a/http/http_server.php +++ b/http/http_server.php @@ -1,194 +1,192 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/http/http_dispatcher.php'; require_once JAXL_CWD.'/http/http_request.php'; // carriage return and line feed define('HTTP_CRLF', "\r\n"); // 1xx informational define('HTTP_100', "Continue"); define('HTTP_101', "Switching Protocols"); // 2xx success define('HTTP_200', "OK"); // 3xx redirection define('HTTP_301', 'Moved Permanently'); define('HTTP_304', 'Not Modified'); // 4xx client error define('HTTP_400', 'Bad Request'); define('HTTP_403', 'Forbidden'); define('HTTP_404', 'Not Found'); define('HTTP_405', 'Method Not Allowed'); define('HTTP_499', 'Client Closed Request'); // Nginx // 5xx server error define('HTTP_500', 'Internal Server Error'); define('HTTP_503', 'Service Unavailable'); class HTTPServer { private $server = null; public $cb = null; private $dispatcher = null; private $requests = array(); public function __construct($port=9699, $address="127.0.0.1") { $path = 'tcp://'.$address.':'.$port; $this->server = new JAXLSocketServer( $path, array(&$this, 'on_accept'), array(&$this, 'on_request') ); $this->dispatcher = new HTTPDispatcher(); } public function __destruct() { $this->server = null; } public function dispatch($rules) { foreach ($rules as $rule) { $this->dispatcher->add_rule($rule); } } public function start($cb=null) { $this->cb = $cb; JAXLLoop::run(); } public function on_accept($sock, $addr) { _debug("on_accept for client#$sock, addr:$addr"); // initialize new request obj $request = new HTTPRequest($sock, $addr); // setup sock cb $request->set_sock_cb( array(&$this->server, 'send'), array(&$this->server, 'read'), array(&$this->server, 'close') ); // cache request object $this->requests[$sock] = &$request; // reactive client for further read $this->server->read($sock); } public function on_request($sock, $raw) { _debug("on_request for client#$sock"); $request = $this->requests[$sock]; // 'wait_for_body' state is reached when ever // application calls recv_body() method // on received $request object if ($request->state() == 'wait_for_body') { $request->body($raw); - } - else { + } else { // break on crlf $lines = explode(HTTP_CRLF, $raw); // parse request line if ($request->state() == 'wait_for_request_line') { list($method, $resource, $version) = explode(" ", $lines[0]); $request->line($method, $resource, $version); unset($lines[0]); _info($request->ip." ".$request->method." ".$request->resource." ".$request->version); } // parse headers foreach ($lines as $line) { $line_parts = explode(":", $line); if (sizeof($line_parts) > 1) { if (strlen($line_parts[0]) > 0) { $k = $line_parts[0]; unset($line_parts[0]); $v = implode(":", $line_parts); $request->set_header($k, $v); } - } - else if (strlen(trim($line_parts[0])) == 0) { + } else if (strlen(trim($line_parts[0])) == 0) { $request->empty_line(); } // if exploded line array size is 1 // and thr is something in $line_parts[0] // must be request body else { $request->body($line); } } } // if request has reached 'headers_received' state? if ($request->state() == 'headers_received') { // dispatch to any matching rule found _debug("delegating to dispatcher for further routing"); $dispatched = $this->dispatcher->dispatch($request); // if no dispatch rule matched call generic callback if (!$dispatched && $this->cb) { _debug("no dispatch rule matched, sending to generic callback"); call_user_func($this->cb, $request); } // else if not dispatched and not generic callbacked // send 404 not_found else if (!$dispatched) { // TODO: send 404 if no callback is registered for this request _debug("dropping request since no matching dispatch rule or generic callback was specified"); $request->not_found('404 Not Found'); } } // if state is not 'headers_received' // reactivate client socket for read event else { $this->server->read($sock); } } } diff --git a/jaxl.php b/jaxl.php index a5a9cb2..b35ce90 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,806 +1,795 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger if (isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if (isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if ($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if (!is_dir($this->priv_dir)) mkdir($this->priv_dir); if (!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if (!is_dir($this->pid_dir)) mkdir($this->pid_dir); if (!is_dir($this->log_dir)) mkdir($this->log_dir); if (!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; - } - else { + } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if (!is_array($xeps)) $xeps = array($xeps); foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type' => 'chat', 'to' => $to, 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type' => 'get', 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type' => 'get', 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to' => $to, 'type' => 'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) $this->enable_debug_shell(); if (@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); - } - else { + } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; - } - else { + } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; - } - else { + } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; - } - else { + } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if ($mechanisms) foreach ($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if ($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach ($mechs as $mech => $any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if ($mech == 'X-FACEBOOK-PLATFORM') { if (@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if ($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; - } - else if ($pref_auth == 'CRAM-MD5') { + } else if ($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; - } - else if ($pref_auth == 'SCRAM-SHA-1') { + } else if ($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if (!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach ($query->childrens as $child) { if ($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach ($child->childrens as $group) { if ($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if (!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if (@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if (!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if ($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if ($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; - } - else if ($type == 'unavailable') { + } else if ($type == 'unavailable') { if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if ($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if ($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); - } - else { + } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach ($query->childrens as $k => $child) { if ($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; - } - else if ($child->name == 'x') { + } else if ($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; - } - else if ($child->name == 'feature') { + } else if ($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach ($query->childrens as $k => $child) { if ($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } diff --git a/jaxlctl b/jaxlctl index ee2db17..350c1c0 100755 --- a/jaxlctl +++ b/jaxlctl @@ -1,187 +1,183 @@ #!/usr/bin/env php <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ $params = $argv; $exe = array_shift($params); $command = array_shift($params); require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // TODO: an abstract JAXLCtlCommand class // with seperate class per command // a mechanism to register new commands class JAXLCtl { protected $ipc = null; protected $buffer = ''; protected $buffer_cb = null; protected $cli = null; public $dots = "....... "; protected $symbols = array(); public function __construct($command, $params) { global $exe; if (method_exists($this, $command)) { $r = call_user_func_array(array(&$this, $command), $params); if (sizeof($r) == 2) { list($buffer_cb, $quit_cb) = $r; $this->buffer_cb = $buffer_cb; $this->cli = new JAXLCli(array(&$this, 'on_terminal_input'), $quit_cb); $this->run(); - } - else { + } else { _colorize("oops! internal command error", JAXL_ERROR); exit; } - } - else { + } else { _colorize("error: invalid command '$command' received", JAXL_ERROR); _colorize("type '$exe help' for list of available commands", JAXL_NOTICE); exit; } } public function run() { JAXLCli::prompt(); JAXLLoop::run(); } public function on_terminal_input($raw) { $raw = trim($raw); $last = substr($raw, -1, 1); if ($last == ";") { // dispatch to buffer callback call_user_func($this->buffer_cb, $this->buffer.$raw); $this->buffer = ''; - } - else if ($last == '\\') { + } else if ($last == '\\') { $this->buffer .= substr($raw, 0, -1); echo $this->dots; - } - else { + } else { // buffer command $this->buffer .= $raw."; "; echo $this->dots; } } public static function print_help() { global $exe; _colorize("Usage: $exe command [options...]\n", JAXL_INFO); _colorize("Commands:", JAXL_NOTICE); _colorize(" help This help text", JAXL_DEBUG); _colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG); _colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG); echo "\n"; } protected function help() { JAXLCtl::print_help(); exit; } // // shell command // protected function shell() { return array(array(&$this, 'on_shell_input'), array(&$this, 'on_shell_quit')); } private function _eval($raw, $symbols) { extract($symbols); eval($raw); $g = get_defined_vars(); unset($g['raw']); unset($g['symbols']); return $g; } public function on_shell_input($raw) { $this->symbols = $this->_eval($raw, $this->symbols); JAXLCli::prompt(); } public function on_shell_quit() { exit; } // // debug command // protected function debug($sock_path) { $this->ipc = new JAXLSocketClient(); $this->ipc->set_callback(array(&$this, 'on_debug_response')); $this->ipc->connect('unix://'.$sock_path); return array(array(&$this, 'on_debug_input'), array(&$this, 'on_debug_quit')); } public function on_debug_response($raw) { $ret = unserialize($raw); print_r($ret); echo "\n"; JAXLCli::prompt(); } public function on_debug_input($raw) { $this->ipc->send($this->buffer.$raw); } public function on_debug_quit() { $this->ipc->disconnect(); exit; } } // we atleast need a command argument if ($argc < 2) { JAXLCtl::print_help(); exit; } $ctl = new JAXLCtl($command, $params); echo "done\n"; diff --git a/xep/xep_0114.php b/xep/xep_0114.php index f25e9ec..99ecd8a 100644 --- a/xep/xep_0114.php +++ b/xep/xep_0114.php @@ -1,92 +1,91 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_JABBER_COMPONENT_ACCEPT', 'jabber:component:accept'); class XEP_0114 extends XMPPXep { // // abstract method // public function init() { return array( 'on_connect' => 'start_stream', 'on_stream_start' => 'start_handshake', 'on_handshake_stanza' => 'logged_in', 'on_error_stanza' => 'logged_out' ); } // // event callbacks // public function start_stream() { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" to="'.$this->jaxl->jid->to_string().'" xmlns="'.NS_JABBER_COMPONENT_ACCEPT.'">'; $this->jaxl->send_raw($xml); } public function start_handshake($stanza) { _debug("starting component handshake"); $id = $stanza->id; $hash = strtolower(sha1($id.$this->jaxl->pass)); $stanza = new JAXLXml('handshake', null, $hash); $this->jaxl->send($stanza); } public function logged_in($stanza) { _debug("component handshake complete"); $this->jaxl->handle_auth_success(); return array("logged_in", 1); } public function logged_out($stanza) { if ($stanza->name == "error" && $stanza->ns == NS_XMPP) { $reason = $stanza->childrens[0]->name; $this->jaxl->handle_auth_failure($reason); $this->jaxl->send_end_stream(); return array("logged_out", 0); - } - else { + } else { _debug("uncatched stanza received in logged_out"); } } } diff --git a/xep/xep_0206.php b/xep/xep_0206.php index f39b80d..7bc76a1 100644 --- a/xep/xep_0206.php +++ b/xep/xep_0206.php @@ -1,233 +1,228 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind'); define('NS_BOSH', 'urn:xmpp:xbosh'); class XEP_0206 extends XMPPXep { private $mch = null; public $chs = array(); private $recv_cb = null; public $rid = null; public $sid = null; private $hold = 1; private $wait = 30; private $restarted = false; public $headers = array( 'Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8' ); // // abstract method // public function init() { $this->mch = curl_multi_init(); return array( ); } // // event callbacks // public function send($body) { if (is_object($body)) { $body = $body->to_string(); - } - else { + } else { if (substr($body, 0, 15) == '<stream:stream ') { $this->restarted = true; $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'xmpp:restart' => 'true', 'xmlns:xmpp' => NS_BOSH )); $body = $body->to_string(); - } - else if (substr($body, 0, 16) == '</stream:stream>') { + } else if (substr($body, 0, 16) == '</stream:stream>') { $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'type' => 'terminate' )); $body = $body->to_string(); - } - else { + } else { $body = $this->wrap($body); } } _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body); $this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']); curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers); curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false); curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1); curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body); curl_multi_add_handle($this->mch, $this->chs[$this->rid]); } public function recv() { if ($this->restarted) { $this->restarted = false; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); } _debug("recving for $this->rid"); do { $ret = curl_multi_exec($this->mch, $running); $changed = curl_multi_select($this->mch, 0.1); if ($changed == 0 && $running == 0) { $ch = @$this->chs[$this->rid]; if ($ch) { $data = curl_multi_getcontent($ch); curl_multi_remove_handle($this->mch, $ch); unset($this->chs[$this->rid]); _debug("recvd for $this->rid ".$data); list($body, $stanza) = $this->unwrap($data); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if (@$attrs['type'] == 'terminate') { // fool me again if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); - } - else { + } else { if (!$this->sid) { $this->sid = $attrs['sid']; } if ($this->recv_cb) call_user_func($this->recv_cb, $stanza); } - } - else { + } else { _error("no ch found"); exit; } } } while ($running); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function wrap($stanza) { return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>'; } public function unwrap($body) { // a dirty way but it works efficiently if (substr($body, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); if (isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; else $envelop = "<body/>"; if (isset($m[2][0])) $payload = $m[2][0]; else $payload = ''; return array($envelop, $payload); } public function session_start() { $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000); $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold; $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); $attrs = array( 'content' => 'text/xml; charset=utf-8', 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'], 'secure' => 'true', 'xml:lang' => 'en', 'xmpp:version' => '1.0', 'xmlns:xmpp' => NS_BOSH, 'hold' => $this->hold, 'wait' => $this->wait, 'rid' => $this->rid, 'ver' => '1.10' ); if (@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; $body = new JAXLXml('body', NS_HTTP_BIND, $attrs); $this->send($body); } public function ping() { $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid)); $this->send($body); } public function session_end() { $this->disconnect(); } public function disconnect() { _debug("disconnecting"); } } diff --git a/xmpp/xmpp_jid.php b/xmpp/xmpp_jid.php index a4b10f6..0c8fa53 100644 --- a/xmpp/xmpp_jid.php +++ b/xmpp/xmpp_jid.php @@ -1,80 +1,78 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Xmpp Jid * * @author abhinavsingh * */ class XMPPJid { public $node = null; public $domain = null; public $resource = null; public $bare = null; public function __construct($str) { $tmp = explode("@", $str); if (sizeof($tmp) == 2) { $this->node = $tmp[0]; $tmp = explode("/", $tmp[1]); if (sizeof($tmp) == 2) { $this->domain = $tmp[0]; $this->resource = $tmp[1]; - } - else { + } else { $this->domain = $tmp[0]; } - } - else if (sizeof($tmp) == 1) { + } else if (sizeof($tmp) == 1) { $this->domain = $tmp[0]; } $this->bare = $this->node ? $this->node."@".$this->domain : $this->domain; } public function to_string() { $str = ""; if ($this->node) $str .= $this->node.'@'.$this->domain; else if ($this->domain) $str .= $this->domain; if ($this->resource) $str .= '/'.$this->resource; return $str; } } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index d90a385..0565915 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,668 +1,657 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass=null, $resource=null, $force_tls=false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if (isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; if (isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if (strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if (!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc' => $nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if (isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if (!$msg->id) $msg->id = $this->get_id(); if ($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if (!$pres->id) $pres->id = $this->get_id(); if ($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if (!$iq->id) $iq->id = $this->get_id(); if ($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); - } - else if (strpos(strrev(trim($pair)), '"') === 0 && $key) { + } else if (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach ($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach (array('realm', 'cnonce', 'digest-uri') as $key) if (!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if (isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); - } - else { + } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if ($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; - } - else { + } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } - } - else { + } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; - } - else if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { + } else if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; - } - else if ($stanza->name == 'success' && $stanza->ns == NS_SASL) { + } else if ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; - } - else { + } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; - } - else { + } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if ($stanza->name == 'message') { $this->handle_message($stanza); - } - else if ($stanza->name == 'presence') { + } else if ($stanza->name == 'presence') { $this->handle_presence($stanza); - } - else if ($stanza->name == 'iq') { + } else if ($stanza->name == 'iq') { $this->handle_iq($stanza); - } - else { + } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } }
jaxl/JAXL
c5e24d81186656a19f3af6ac74a4a09ab0572106
Fix PSR: Expected 1 space before and after "=>"
diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php index 97b2c45..d2b380e 100644 --- a/core/jaxl_clock.php +++ b/core/jaxl_clock.php @@ -1,123 +1,123 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class JAXLClock { // current clock time in microseconds private $tick = 0; // current Unix timestamp with microseconds public $time = null; // scheduled jobs public $jobs = array(); public function __construct() { $this->time = microtime(true); } public function __destruct() { _info("shutting down clock server..."); } public function tick($by=null) { // update clock if ($by) { $this->tick += $by; $this->time += $by / pow(10,6); } else { $time = microtime(true); $by = $time - $this->time; $this->tick += $by * pow(10, 6); $this->time = $time; } // run scheduled jobs - foreach ($this->jobs as $ref=>$job) { + foreach ($this->jobs as $ref => $job) { if ($this->tick >= $job['scheduled_on'] + $job['after']) { //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".$job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); call_user_func($job['cb'], $job['args']); if (!$job['is_periodic']) { unset($this->jobs[$ref]); } else { $job['scheduled_on'] = $this->tick; $job['runs']++; $this->jobs[$ref] = $job; } } } } // calculate execution time of callback public function tc($callback, $args=null) { } // callback after $time microseconds public function call_fun_after($time, $callback, $args=null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => false, 'runs' => 0 ); return sizeof($this->jobs); } // callback periodically after $time microseconds public function call_fun_periodic($time, $callback, $args=null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => true, 'runs' => 0 ); return sizeof($this->jobs); } // cancel a previously scheduled callback public function cancel_fun_call($ref) { unset($this->jobs[$ref-1]); } } diff --git a/core/jaxl_fsm.php b/core/jaxl_fsm.php index fe26972..7f4c1f5 100644 --- a/core/jaxl_fsm.php +++ b/core/jaxl_fsm.php @@ -1,81 +1,81 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ abstract class JAXLFsm { protected $state = null; // abstract method abstract public function handle_invalid_state($r); public function __construct($state) { $this->state = $state; } // returned value from state callbacks can be: // 1) array() <-- is_callable method - // 2) array([0]=>'new_state', [1]=>'return value for current callback') <-- is_not_callable method - // 3) array([0]=>'new_state') + // 2) array([0] => 'new_state', [1] => 'return value for current callback') <-- is_not_callable method + // 3) array([0] => 'new_state') // 4) 'new_state' // // for case 1) new state will be an array // for other cases new state will be a string public function __call($event, $args) { if ($this->state) { // call state method _debug("calling state handler '".(is_array($this->state) ? $this->state[1] : $this->state)."' for incoming event '".$event."'"); $call = is_callable($this->state) ? $this->state : (method_exists($this, $this->state) ? array(&$this, $this->state): $this->state); $r = call_user_func($call, $event, $args); // 4 cases of possible return value if (is_callable($r)) $this->state = $r; else if (is_array($r) && sizeof($r) == 2) list($this->state, $ret) = $r; else if (is_array($r) && sizeof($r) == 1) $this->state = $r[0]; else if (is_string($r)) $this->state = $r; else $this->handle_invalid_state($r); _debug("current state '".(is_array($this->state) ? $this->state[1] : $this->state)."'"); // return case if (!is_callable($r) && is_array($r) && sizeof($r) == 2) return $ret; } else { _debug("invalid state found, nothing called for event ".$event.""); } } } diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index 6aef718..f82abdf 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,255 +1,255 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLSocketServer { public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; public function __construct($path, $accept_cb, $request_cb) { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; - $ctx = stream_context_create(array('socket'=>array('backlog'=>$this->backlog))); + $ctx = stream_context_create(array('socket' => array('backlog' => $this->backlog))); if (($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { if (@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); } else { _error("unable to set non block flag"); } } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } public function __destruct() { _info("shutting down socket server"); } public function read($client_id) { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } public function send($client_id, $data) { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } public function close($client_id) { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } public function on_server_accept_ready($server) { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); if (!$client) { _error("unable to accept new client conn"); return; } if (@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do if ($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); } // if no accept callback is registered // close the accepted connection else { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } } else { _error("unable to set non block flag"); } } public function on_client_read_ready($client) { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); if ($bytes === 0) { $meta = stream_get_meta_data($client); if ($meta['eof'] === TRUE) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); @fclose($client); unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; if ($this->request_cb) call_user_func($this->request_cb, $client_id, $total); $this->clients[$client_id]['ibuffer'] = ''; } public function on_client_write_ready($client) { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); if ($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; } else if ($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler if (strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } } catch(JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // protected function add_read_cb($client_id) { if ($this->clients[$client_id]['reading']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } protected function add_write_cb($client_id) { if ($this->clients[$client_id]['writing']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } protected function del_read_cb($client_id) { if (!$this->clients[$client_id]['reading']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } protected function del_write_cb($client_id) { if (!$this->clients[$client_id]['writing']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } } diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index c2ddd79..97110a4 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,196 +1,196 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if (is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if (is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if (is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; - foreach ($attrs as $k=>$v) { + foreach ($attrs as $k => $v) { if ($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } public function t($text, $append=FALSE) { if (!$append) { $this->rover->text = $text; } else { if ($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; } return $this; } public function c($name, $ns=null, $attrs=array(), $text=null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { if ($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } public function top() { $this->rover = &$this; return $this; } public function exists($name, $ns=null, $attrs=array()) { foreach ($this->childrens as $child) { if ($ns) { if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; } else if ($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } public function update($name, $ns=null, $attrs=array(), $text=null) { - foreach ($this->childrens as $k=>$child) { + foreach ($this->childrens as $k => $child) { if ($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } public function to_string($parent_ns=null) { $xml = ''; $xml .= '<'.$this->name; if ($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; - foreach ($this->attrs as $k=>$v) if (!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; + foreach ($this->attrs as $k => $v) if (!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; foreach ($this->childrens as $child) $xml .= $child->to_string($this->ns); if ($this->text) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } } diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php index 7605df3..0160c1d 100644 --- a/core/jaxl_xml_stream.php +++ b/core/jaxl_xml_stream.php @@ -1,188 +1,188 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Enter description here ... * @author abhinavsingh * */ class JAXLXmlStream { private $delimiter = '\\'; private $ns; private $parser; private $stanza; private $depth = -1; private $start_cb; private $stanza_cb; private $end_cb; public function __construct() { $this->init_parser(); } private function init_parser() { $this->depth = -1; $this->parser = xml_parser_create_ns("UTF-8", $this->delimiter); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); xml_set_character_data_handler($this->parser, array(&$this, "handle_character")); xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag")); } public function __destruct() { //_debug("cleaning up xml parser..."); @xml_parser_free($this->parser); } public function reset_parser() { $this->parse_final(null); @xml_parser_free($this->parser); $this->parser = null; $this->init_parser(); } public function set_callback($start_cb, $end_cb, $stanza_cb) { $this->start_cb = $start_cb; $this->end_cb = $end_cb; $this->stanza_cb = $stanza_cb; } public function parse($str) { xml_parse($this->parser, $str, false); } public function parse_final($str) { xml_parse($this->parser, $str, true); } protected function handle_start_tag($parser, $name, $attrs) { $name = $this->explode($name); //echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL; // replace ns with prefix - foreach ($attrs as $key=>$v) { + foreach ($attrs as $key => $v) { $k = $this->explode($key); // no ns specified if ($k[0] == null) { $attrs[$k[1]] = $v; } // xml ns else if ($k[0] == NS_XML) { unset($attrs[$key]); $attrs['xml:'.$k[1]] = $v; } else { _error("==================> unhandled ns prefix on attribute"); // remove attribute else will cause error with bad stanza format // report to developer if above error message is ever encountered unset($attrs[$key]); } } if ($this->depth <= 0) { $this->depth = 0; $this->ns = $name[1]; if ($this->start_cb) { $stanza = new JAXLXml($name[1], $name[0], $attrs); call_user_func($this->start_cb, $stanza); } } else { if (!$this->stanza) { $stanza = new JAXLXml($name[1], $name[0], $attrs); $this->stanza = &$stanza; } else { $this->stanza->c($name[1], $name[0], $attrs); } } ++$this->depth; } protected function handle_end_tag($parser, $name) { $name = explode($this->delimiter, $name); $name = sizeof($name) == 1 ? array('', $name[0]) : $name; //echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL; if ($this->depth == 1) { if ($this->end_cb) { $stanza = new JAXLXml($name[1], $this->ns); call_user_func($this->end_cb, $stanza); } } else if ($this->depth > 1) { if ($this->stanza) $this->stanza->up(); if ($this->depth == 2) { if ($this->stanza_cb) { call_user_func($this->stanza_cb, $this->stanza); $this->stanza = null; } } } --$this->depth; } protected function handle_character($parser, $data) { //echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL; if ($this->stanza) { $this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), TRUE); } } private function implode($data) { return implode($this->delimiter, $data); } private function explode($data) { $data = explode($this->delimiter, $data); $data = sizeof($data) == 1 ? array(null, $data[0]) : $data; return $data; } } diff --git a/docs/users/http_examples.rst b/docs/users/http_examples.rst index f4af5f1..61f1c2c 100644 --- a/docs/users/http_examples.rst +++ b/docs/users/http_examples.rst @@ -1,102 +1,102 @@ HTTP Examples ============= Writing HTTP Server ------------------- Intialize an ``HTTPServer`` instance .. code-block:: ruby require_once 'jaxl.php'; require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this. Define a callback method that will accept all incoming ``HTTPRequest`` objects .. code-block:: ruby function on_request($request) { if ($request->method == 'GET') { $body = json_encode($request); - $request->ok($body, array('Content-Type'=>'application:json')); + $request->ok($body, array('Content-Type' => 'application:json')); } else { $request->not_found(); } } ``on_request`` callback method will receive a ``HTTPRequest`` object instance. For this example, we will simply echo back json encoded ``$request`` object for every http GET request. Start http server: .. code-block:: ruby $http->start('on_request'); We pass ``on_request`` method as first parameter to ``HTTPServer::start/1``. If nothing is passed, requests will fail with a default 404 not found error message Writing REST API Server ----------------------- Intialize an ``HTTPServer`` instance .. code-block:: ruby require_once 'jaxl.php'; require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this. Define our REST resources callback methods: .. code-block:: ruby function index($request) { $request->send_response( - 200, array('Content-Type'=>'text/html'), + 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } function upload($request) { if ($request->method == 'GET') { $request->send_response( - 200, array('Content-Type'=>'text/html'), + 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action=""><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' ); } else if ($request->method == 'POST') { if ($request->body === null && $request->expect) { $request->recv_body(); } else { // got upload body, save it _debug("file upload complete, got ".strlen($request->body)." bytes of data"); $request->close(); } } } Next we need to register dispatch rules for our callbacks above: .. code-block:: ruby $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); $rules = array($index, $upload); $http->dispatch($rules); Start REST api server: .. code-block:: ruby $http->start(); Make an HTTP request -------------------- diff --git a/docs/users/jaxlctl.rst b/docs/users/jaxlctl.rst index 3d55fe2..ac341b2 100644 --- a/docs/users/jaxlctl.rst +++ b/docs/users/jaxlctl.rst @@ -1,50 +1,50 @@ ./jaxlctl ========= Usage: ``./jaxlctl command [options...]`` ``jaxlctl`` is a control script that can be seen as a useful tool for: * debugging daemons running in the background * customize daemons on the fly * monitoring daemons * as a playground for learning XMPP/HTTP and Jaxl library itself Type ``./jaxlctl help`` to see list of available commands. .. note:: Various commands are still experimental. Know what you are doing before using them in production. You have been warned !!! Interactive Shell ------------------ >>> ./jaxlctl shell jaxl 1> jaxl 1> // create a test message object - jaxl 1> $msg = new XMPPMsg(array('to'=>'[email protected]'), 'Hello World!'); + jaxl 1> $msg = new XMPPMsg(array('to' => '[email protected]'), 'Hello World!'); jaxl 2> jaxl 2> // object to string conversion jaxl 2> print_r($msg->to_string()); <message to="[email protected]"><body>Hello World!</body></message> jaxl 3> Debug Running Instances ------------------------ >>> ./jaxlctl attach XXXXX jaxl 1> jaxl 1> // create a message to be sent - jaxl 1> $msg = new XMPPMsg(array('to'=>'[email protected]'), 'Hello World!'); + jaxl 1> $msg = new XMPPMsg(array('to' => '[email protected]'), 'Hello World!'); jaxl 2> jaxl 2> // this client is from the echo bot example jaxl 2> global $client; jaxl 3> jaxl 3> // send the message packet jaxl 3> $client->send($msg); jaxl 4> jaxl 4> // or we can directly do jaxl 4> $client->send_chat_msg('[email protected]', 'Hello World!'); jaxl 5> Where ``XXXXX`` is the pid of running ``JAXL`` instance. diff --git a/docs/users/xml_objects.rst b/docs/users/xml_objects.rst index 8c5a3c2..01b566e 100644 --- a/docs/users/xml_objects.rst +++ b/docs/users/xml_objects.rst @@ -1,121 +1,121 @@ .. _xml-objects: Xml Objects =========== Jaxl library works with custom XML implementation which is similar to inbuild PHP XML functions but is lightweight and easy to work with. JAXLXml ------- ``JAXLXml`` is the base XML object. Open up :ref:`Jaxl interactive shell <jaxl-instance>` and try some xml object creation/manipulation: >>> ./jaxlctl shell jaxl 1> jaxl 1> $xml = new JAXLXml( ....... 'dummy', ....... 'dummy:packet', - ....... array('attr1'=>'[email protected]', 'attr2'=>''), + ....... array('attr1' => '[email protected]', 'attr2' => ''), ....... 'Hello World!' ....... ); jaxl 2> echo $xml->to_string(); <dummy xmlns="dummy:packet" attr1="[email protected]" attr2="">Hello World!</dummy> jaxl 3> ``JAXLXml`` constructor instance accepts following parameters: * ``JAXLXml($name, $ns, $attrs, $text)`` * ``JAXLXml($name, $ns, $attrs)`` * ``JAXLXml($name, $ns, $text)`` * ``JAXLXml($name, $attrs, $text)`` * ``JAXLXml($name, $attrs)`` * ``JAXLXml($name, $ns)`` * ``JAXLXml($name)`` ``JAXLXml`` draws inspiration from StropheJS XML Builder class. Below are available methods for modifying and manipulating an ``JAXLXml`` object: * ``t($text, $append=FALSE)`` update text of current rover * ``c($name, $ns=null, $attrs=array(), $text=null)`` append a child node at current rover * ``cnode($node)`` append a JAXLXml child node at current rover * ``up()`` move rover to one step up the xml tree * ``top()`` move rover back to top element in the xml tree * ``exists($name, $ns=null, $attrs=array())`` checks if a child with $name exists, return child ``JAXLXml`` if found otherwise false. This function returns at first matching child. * ``update($name, $ns=null, $attrs=array(), $text=null)`` update specified child element * ``attrs($attrs)`` merge new attrs with attributes of current rover * ``match_attrs($attrs)`` pass a kv pair of ``$attrs``, return bool if all passed keys matches their respective values in the xml packet * ``to_string()`` get string representation of the object ``JAXLXml`` maintains a rover which points to the current level down the XML tree where manipulation is performed. XMPPStanza ---------- In the world of XMPP where everything incoming and outgoing payload is an ``JAXLXml`` instance code can become nasty, developers can get lost in dirty XML manipulations spreaded all over the application code base and what not. XML structures are not only unreadable for humans but even for machine. While an instance of ``JAXLXml`` provide direct access to XML ``name``, ``ns`` and ``text``, it can become painful and time consuming when trying to retrieve or modify a particular ``attrs`` or ``childrens``. I was fed up of doing ``getAttributeByName``, ``setAttributeByName``, ``getChild`` etc everytime i had to access common XMPP Stanza attributes. ``XMPPStanza`` is a wrapper on top of ``JAXLXml`` objects. Preserving all the functionalities of base ``JAXLXml`` instance it also provide direct access to most common XMPP Stanza attributes like ``to``, ``from``, ``id``, ``type`` etc. It also provides a framework for adding custom access patterns. ``XMPPMsg``, ``XMPPPres`` and ``XMPPIq`` extends ``XMPPStanza`` and also add a few custom access patterns like ``body``, ``thread``, ``subject``, ``status``, ``show`` etc. Here is a list of default access patterns: #. ``name`` #. ``ns`` #. ``text`` #. ``attrs`` #. ``childrens`` #. ``to`` #. ``from`` #. ``id`` #. ``type`` #. ``to_node`` #. ``to_domain`` #. ``to_resource`` #. ``from_node`` #. ``from_domain`` #. ``from_resource`` #. ``status`` #. ``show`` #. ``priority`` #. ``body`` #. ``thread`` #. ``subject`` diff --git a/examples/echo_http_server.php b/examples/echo_http_server.php index c6b7f38..e2c3902 100644 --- a/examples/echo_http_server.php +++ b/examples/echo_http_server.php @@ -1,58 +1,58 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // print usage notice and parse addr/port parameters if passed _colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE); $port = ($argc == 2 ? $argv[1] : 9699); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer($port); // catch all incoming requests here function on_request($request) { $body = json_encode($request); - $request->ok($body, array('Content-Type'=>'application/json')); + $request->ok($body, array('Content-Type' => 'application/json')); } // start http server $http->start('on_request'); diff --git a/examples/http_rest_server.php b/examples/http_rest_server.php index 1adfae8..76c924e 100644 --- a/examples/http_rest_server.php +++ b/examples/http_rest_server.php @@ -1,117 +1,117 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // print usage notice and parse addr/port parameters if passed _colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE); $port = ($argc == 2 ? $argv[1] : 9699); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer($port); // callback method for dispatch rule (see below) function index($request) { $request->send_response( - 200, array('Content-Type'=>'text/html'), + 200, array('Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } // callback method for dispatch rule (see below) function upload($request) { if ($request->method == 'GET') { $request->ok(array( - 'Content-Type'=>'text/html'), + 'Content-Type' => 'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' ); } else if ($request->method == 'POST') { if ($request->body === null && $request->expect) { $request->recv_body(); } else { // got upload body, save it _info("file upload complete, got ".strlen($request->body)." bytes of data"); $upload_data = $request->multipart->form_data[0]['body']; - $request->ok($upload_data, array('Content-Type'=>$request->multipart->form_data[0]['headers']['Content-Type'])); + $request->ok($upload_data, array('Content-Type' => $request->multipart->form_data[0]['headers']['Content-Type'])); } } } // add dispatch rules with callback method as first argument $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); // some REST CRUD style callback methods // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules function create_event($request) { _info("got event create request"); $request->close(); } function read_event($request, $pk) { _info("got event read request for $pk"); $request->close(); } function update_event($request, $pk) { _info("got event update request for $pk"); $request->close(); } function delete_event($request, $pk) { _info("got event delete request for $pk"); $request->close(); } $event_create = array('create_event', '^/event/create/$', array('PUT')); $event_read = array('read_event', '^/event/(?P<pk>\d+)/$', array('GET', 'HEAD')); $event_update = array('update_event', '^/event/(?P<pk>\d+)/$', array('POST')); $event_delete = array('delete_event', '^/event/(?P<pk>\d+)/$', array('DELETE')); // prepare rule set $rules = array($index, $upload, $event_create, $event_read, $event_update, $event_delete); $http->dispatch($rules); // start http server $http->start(); diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index d19eabf..bcf2f4a 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,144 +1,144 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 5) { echo "Usage: $argv[0] host jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[2], 'pass' => $argv[3], 'host' => $argv[1], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC '0203', // Delayed Delivery '0199' // XMPP Ping )); // // add necessary event callbacks here // $_room_full_jid = $argv[4]."/".$argv[5]; $room_full_jid = new XMPPJid($_room_full_jid); $client->add_cb('on_auth_success', function() { global $client, $room_full_jid; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // join muc room $client->xeps['0045']->join_room($room_full_jid); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_groupchat_message', function($stanza) { global $client; $from = new XMPPJid($stanza->from); $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); if ($from->resource) { echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } else { $subject = $stanza->exists('subject'); if ($subject) { echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } } }); $client->add_cb('on_presence_stanza', function($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { - if (($status = $x->exists('status', null, array('code'=>'110'))) !== false) { + if (($status = $x->exists('status', null, array('code' => '110'))) !== false) { $item = $x->exists('item'); _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); } else { _info("xmlns #user have no x child element"); } } else { _warning("=======> odd case 1"); } } // stanza from other users received else if (strtolower($from->bare) == strtolower($room_full_jid->bare)) { if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; } else { _warning("=======> odd case 2"); } } else { _warning("=======> odd case 3"); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/publisher.php b/examples/publisher.php index e4f7f11..bc94b36 100644 --- a/examples/publisher.php +++ b/examples/publisher.php @@ -1,97 +1,97 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // create node //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); // publish - $item = new JAXLXml('item', null, array('id'=>time())); + $item = new JAXLXml('item', null, array('id' => time())); $item->c('entry', 'http://www.w3.org/2005/Atom'); $item->c('title')->t('Soliloquy')->up(); $item->c('summary')->t('To be, or not to be: that is the question')->up(); - $item->c('link', null, array('rel'=>'alternate', 'type'=>'text/html', 'href'=>'http://denmark.lit/2003/12/13/atom03'))->up(); + $item->c('link', null, array('rel' => 'alternate', 'type' => 'text/html', 'href' => 'http://denmark.lit/2003/12/13/atom03'))->up(); $item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up(); $item->c('published')->t('2003-12-13T18:30:02Z')->up(); $item->c('updated')->t('2003-12-13T18:30:02Z')->up(); $client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/register_user.php b/examples/register_user.php index 16b7559..3c805c0 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,167 +1,167 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // $form = array(); function wait_for_register_response($event, $args) { global $client, $form; if ($event == 'stanza_cb') { $stanza = $args[0]; if ($stanza->name == 'iq') { $form['type'] = $stanza->attrs['type']; if ($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } else if ($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } } } else { _notice("unhandled event $event rcvd"); } } function wait_for_register_form($event, $args) { global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if ($query) { $instructions = $query->exists('instructions'); if ($instructions) { echo $instructions->text.PHP_EOL; } - foreach ($query->childrens as $k=>$child) { + foreach ($query->childrens as $k => $child) { if ($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // $client->add_cb('on_stream_features', function($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; }); $client->add_cb('on_disconnect', function() { global $form; _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); }); // // finally start configured xmpp stream // $client->start(); // // if registration was successful // try to connect with newly registered account // if ($form['type'] == 'result') { _info("connecting newly registered user account"); $client = new JAXL(array( 'jid' => $form['username'].'@'.$argv[1], 'pass' => $form['password'], 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', function() { global $client; $client->set_status('Available'); }); $client->start(); } echo "done\n"; diff --git a/http/http_request.php b/http/http_request.php index ffa81be..d023dfc 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,488 +1,488 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers=array(), $body=null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if (sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation // public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; if ($this->body === null) $this->body = $rcvd; else $this->body .= $rcvd; if ($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach ($form_data as $data) { //_debug("passing $data to multipart fsm"); if (!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if (!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if (!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { switch($event) { case 'empty_line': return 'headers_received'; break; default: if (substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if (method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } } else if (@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { $k = trim($k); $v = ltrim($v); // is expect header? if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if (strtolower($k) == 'content-type') { $ctype = explode(';', $v); if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if (strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if ($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { if (sizeof($args) == 0) { $body = null; $headers = array(); } if (sizeof($args) == 1) { // http headers or body only received if (is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } } else if (sizeof($args) == 2) { // body and http headers both received if (is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { - foreach ($headers as $k=>$v) + foreach ($headers as $k => $v) $this->_send_header($k, $v); } protected function _send_body($body) { $this->_send($body); } protected function _send_response($code, $headers=array(), $body=null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set if ($body && !isset($headers['Content-Length'])) $headers['Content-Length'] = strlen($body); // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); if ($body) $this->_send_body(HTTP_CRLF.$body); } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if (sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach ($query as $q) { $q = explode("=", $q); if (sizeof($q) == 1) $q[1] = ""; $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } } diff --git a/jaxl.php b/jaxl.php index c94a689..a5a9cb2 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,806 +1,806 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger if (isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if (isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if ($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if (!is_dir($this->priv_dir)) mkdir($this->priv_dir); if (!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if (!is_dir($this->pid_dir)) mkdir($this->pid_dir); if (!is_dir($this->log_dir)) mkdir($this->log_dir); if (!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { - _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); + _info("strict mode enabled, adding exception handlers. Set 'strict' => TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if (!is_array($xeps)) $xeps = array($xeps); foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events - foreach ($this->xeps[$xep]->init() as $ev=>$cb) { + foreach ($this->xeps[$xep]->init() as $ev => $cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( - 'type'=>'chat', - 'to'=>$to, - 'from'=>$this->full_jid->to_string() + 'type' => 'chat', + 'to' => $to, + 'from' => $this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( - 'type'=>'get', - 'from'=>$this->full_jid->to_string() + 'type' => 'get', + 'from' => $this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( - 'type'=>'get', - 'from'=>$this->full_jid->to_string() + 'type' => 'get', + 'from' => $this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( - array('to'=>$to, 'type'=>'subscribe') + array('to' => $to, 'type' => 'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( - array('to'=>$to, 'type'=>'subscribed') + array('to' => $to, 'type' => 'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( - array('to'=>$to, 'type'=>'unsubscribe') + array('to' => $to, 'type' => 'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( - array('to'=>$to, 'type'=>'unsubscribed') + array('to' => $to, 'type' => 'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for (;;) { // while any of the curl request is pending // keep receiving response while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) $this->enable_debug_shell(); if (@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if ($mechanisms) foreach ($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if ($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { - foreach ($mechs as $mech=>$any) { + foreach ($mechs as $mech => $any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if ($mech == 'X-FACEBOOK-PLATFORM') { if (@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if ($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if ($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if ($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if (!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach ($query->childrens as $child) { if ($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach ($child->childrens as $group) { if ($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if (!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if (@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if (!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if ($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if ($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if ($type == 'unavailable') { if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if ($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if ($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); - foreach ($query->childrens as $k=>$child) { + foreach ($query->childrens as $k => $child) { if ($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if ($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if ($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); - foreach ($query->childrens as $k=>$child) { + foreach ($query->childrens as $k => $child) { if ($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } diff --git a/tests/test_xmpp_msg.php b/tests/test_xmpp_msg.php index 40a8b02..84b8dc6 100644 --- a/tests/test_xmpp_msg.php +++ b/tests/test_xmpp_msg.php @@ -1,67 +1,67 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPMsgTest extends PHPUnit_Framework_TestCase { function test_xmpp_msg() { - $msg = new XMPPMsg(array('to'=>'[email protected]', 'from'=>'[email protected]/~', 'type'=>'chat'), 'hi', 'thread1'); + $msg = new XMPPMsg(array('to' => '[email protected]', 'from' => '[email protected]/~', 'type' => 'chat'), 'hi', 'thread1'); echo $msg->to.PHP_EOL; echo $msg->to_node.PHP_EOL; echo $msg->from.PHP_EOL; echo $msg->to_string().PHP_EOL; $msg->to = '[email protected]/sp'; $msg->body = 'hello world'; $msg->subject = 'some subject'; echo $msg->to.PHP_EOL; echo $msg->to_node.PHP_EOL; echo $msg->from.PHP_EOL; echo $msg->to_string().PHP_EOL; } } diff --git a/tests/test_xmpp_stanza.php b/tests/test_xmpp_stanza.php index 905b22e..06bb11c 100644 --- a/tests/test_xmpp_stanza.php +++ b/tests/test_xmpp_stanza.php @@ -1,75 +1,75 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPStanzaTest extends PHPUnit_Framework_TestCase { function test_xmpp_stanza_nested() { - $stanza = new JAXLXml('message', array('to'=>'[email protected]', 'from'=>'[email protected]')); + $stanza = new JAXLXml('message', array('to' => '[email protected]', 'from' => '[email protected]')); $stanza - ->c('body')->attrs(array('xml:lang'=>'en'))->t('hello')->up() + ->c('body')->attrs(array('xml:lang' => 'en'))->t('hello')->up() ->c('thread')->t('1234')->up() ->c('nested') ->c('nest')->t('nest1')->up() ->c('nest')->t('nest2')->up() ->c('nest')->t('nest3')->up()->up() - ->c('c')->attrs(array('hash'=>'84jsdmnskd')); + ->c('c')->attrs(array('hash' => '84jsdmnskd')); $this->assertEquals( '<message to="[email protected]" from="[email protected]"><body xml:lang="en">hello</body><thread>1234</thread><nested><nest>nest1</nest><nest>nest2</nest><nest>nest3</nest></nested><c hash="84jsdmnskd"></c></message>', $stanza->to_string() ); } function test_xmpp_stanza_from_jaxl_xml() { // xml to stanza test - $xml = new JAXLXml('message', NS_JABBER_CLIENT, array('to'=>'[email protected]', 'from'=>'[email protected]/q')); + $xml = new JAXLXml('message', NS_JABBER_CLIENT, array('to' => '[email protected]', 'from' => '[email protected]/q')); $stanza = new XMPPStanza($xml); $stanza->c('body')->t('hello world'); echo $stanza->to."\n"; echo $stanza->to_string()."\n"; } } diff --git a/xep/xep_0030.php b/xep/xep_0030.php index 9f64d89..b5a7ce2 100644 --- a/xep/xep_0030.php +++ b/xep/xep_0030.php @@ -1,89 +1,89 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DISCO_INFO', 'http://jabber.org/protocol/disco#info'); define('NS_DISCO_ITEMS', 'http://jabber.org/protocol/disco#items'); class XEP_0030 extends XMPPXep { // // abstract method // public function init() { return array( ); } // // api methods // public function get_info_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( - array('type'=>'get', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$entity_jid), + array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid), new JAXLXml('query', NS_DISCO_INFO) ); } public function get_info($entity_jid, $callback=null) { $pkt = $this->get_info_pkt($entity_jid); if ($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } public function get_items_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( - array('type'=>'get', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$entity_jid), + array('type' => 'get', 'from' => $this->jaxl->full_jid->to_string(), 'to' => $entity_jid), new JAXLXml('query', NS_DISCO_ITEMS) ); } public function get_items($entity_jid, $callback=null) { $pkt = $this->get_items_pkt($entity_jid); if ($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } // // event callbacks // } diff --git a/xep/xep_0045.php b/xep/xep_0045.php index 7345ddc..5d748e0 100644 --- a/xep/xep_0045.php +++ b/xep/xep_0045.php @@ -1,111 +1,111 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_MUC', 'http://jabber.org/protocol/muc'); class XEP_0045 extends XMPPXep { // // abstract method // public function init() { return array(); } public function send_groupchat($room_jid, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( - 'type'=>'groupchat', - 'to'=>(($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid), - 'from'=>$this->jaxl->full_jid->to_string() + 'type' => 'groupchat', + 'to' => (($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid), + 'from' => $this->jaxl->full_jid->to_string() ), $body, $thread, $subject ); $this->jaxl->send($msg); } // // api methods (occupant use case) // // room_full_jid simply means room jid with nick name as resource public function get_join_room_pkt($room_full_jid, $options) { $pkt = $this->jaxl->get_pres_pkt( array( - 'from'=>$this->jaxl->full_jid->to_string(), - 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid) + 'from' => $this->jaxl->full_jid->to_string(), + 'to' => (($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid) ) ); $x = $pkt->c('x', NS_MUC); if (isset($options['no_history'])) { $x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0)); } return $x; } public function join_room($room_full_jid, $options = array()) { $pkt = $this->get_join_room_pkt($room_full_jid, $options); $this->jaxl->send($pkt); } public function get_leave_room_pkt($room_full_jid) { return $this->jaxl->get_pres_pkt( - array('type'=>'unavailable', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid)) + array('type' => 'unavailable', 'from' => $this->jaxl->full_jid->to_string(), 'to' => (($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid)) ); } public function leave_room($room_full_jid) { $pkt = $this->get_leave_room_pkt($room_full_jid); $this->jaxl->send($pkt); } // // api methods (moderator use case) // // // event callbacks // } diff --git a/xep/xep_0060.php b/xep/xep_0060.php index dc6dcc4..f824660 100644 --- a/xep/xep_0060.php +++ b/xep/xep_0060.php @@ -1,136 +1,136 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_PUBSUB', 'http://jabber.org/protocol/pubsub'); class XEP_0060 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods (entity use case) // // // api methods (subscriber use case) // public function get_subscribe_pkt($service, $node, $jid=null) { $child = new JAXLXml('pubsub', NS_PUBSUB); - $child->c('subscribe', null, array('node'=>$node, 'jid'=>($jid ? $jid : $this->jaxl->full_jid->to_string()))); + $child->c('subscribe', null, array('node' => $node, 'jid' => ($jid ? $jid : $this->jaxl->full_jid->to_string()))); return $this->get_iq_pkt($service, $child); } public function subscribe($service, $node, $jid=null) { $this->jaxl->send($this->get_subscribe_pkt($service, $node, $jid)); } public function unsubscribe() { } public function get_subscription_options() { } public function set_subscription_options() { } public function get_node_items() { } // // api methods (publisher use case) // public function get_publish_item_pkt($service, $node, $item) { $child = new JAXLXml('pubsub', NS_PUBSUB); - $child->c('publish', null, array('node'=>$node)); + $child->c('publish', null, array('node' => $node)); $child->cnode($item); return $this->get_iq_pkt($service, $child); } public function publish_item($service, $node, $item) { $this->jaxl->send($this->get_publish_item_pkt($service, $node, $item)); } public function delete_item() { } // // api methods (owner use case) // public function get_create_node_pkt($service, $node) { $child = new JAXLXml('pubsub', NS_PUBSUB); - $child->c('create', null, array('node'=>$node)); + $child->c('create', null, array('node' => $node)); return $this->get_iq_pkt($service, $child); } public function create_node($service, $node) { $this->jaxl->send($this->get_create_node_pkt($service, $node)); } // // event callbacks // // // local methods // // this always add attrs protected function get_iq_pkt($service, $child, $type='set') { return $this->jaxl->get_iq_pkt( - array('type'=>$type, 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$service), + array('type' => $type, 'from' => $this->jaxl->full_jid->to_string(), 'to' => $service), $child ); } } diff --git a/xep/xep_0077.php b/xep/xep_0077.php index 68f1cd9..da440fd 100644 --- a/xep/xep_0077.php +++ b/xep/xep_0077.php @@ -1,80 +1,80 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_FEATURE_REGISTER', 'http://jabber.org/features/iq-register'); define('NS_INBAND_REGISTER', 'jabber:iq:register'); class XEP_0077 extends XMPPXep { // // abstract method // public function init() { return array( ); } // // api methods // public function get_form_pkt($domain) { return $this->jaxl->get_iq_pkt( - array('to'=>$domain, 'type'=>'get'), + array('to' => $domain, 'type' => 'get'), new JAXLXml('query', NS_INBAND_REGISTER) ); } public function get_form($domain) { $this->jaxl->send($this->get_form_pkt($domain)); } public function set_form($domain, $form) { $query = new JAXLXml('query', NS_INBAND_REGISTER); - foreach ($form as $k=>$v) $query->c($k, null, array(), $v)->up(); + foreach ($form as $k => $v) $query->c($k, null, array(), $v)->up(); $pkt = $this->jaxl->get_iq_pkt( - array('to'=>$domain, 'type'=>'set'), + array('to' => $domain, 'type' => 'set'), $query ); $this->jaxl->send($pkt); } } diff --git a/xep/xep_0115.php b/xep/xep_0115.php index 3f956c5..d5d38e6 100644 --- a/xep/xep_0115.php +++ b/xep/xep_0115.php @@ -1,70 +1,70 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_CAPS', 'http://jabber.org/protocol/caps'); class XEP_0115 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods // public function get_caps_pkt($cat, $type, $lang, $name, $node, $features) { asort($features); $S = $cat.'/'.$type.'/'.$lang.'/'.$name.'<'; foreach ($features as $feature) $S .= $feature.'<'; $ver = base64_encode(sha1($S, true)); - $stanza = new JAXLXml('c', NS_CAPS, array('hash'=>'sha1', 'node'=>$node, 'ver'=>$ver)); + $stanza = new JAXLXml('c', NS_CAPS, array('hash' => 'sha1', 'node' => $node, 'ver' => $ver)); return $stanza; } // // event callbacks // } diff --git a/xep/xep_0199.php b/xep/xep_0199.php index 377ff9b..01d3c9d 100644 --- a/xep/xep_0199.php +++ b/xep/xep_0199.php @@ -1,57 +1,57 @@ <?php require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_XMPP_PING', 'urn:xmpp:ping'); class XEP_0199 extends XMPPXep { // // abstract method // public function init() { return array( 'on_auth_success' => 'on_auth_success', 'on_get_iq' => 'on_xmpp_ping' ); } // // api methods // public function get_ping_pkt() { $attrs = array( - 'type'=>'get', - 'from'=>$this->jaxl->full_jid->to_string(), - 'to'=>$this->jaxl->full_jid->domain + 'type' => 'get', + 'from' => $this->jaxl->full_jid->to_string(), + 'to' => $this->jaxl->full_jid->domain ); return $this->jaxl->get_iq_pkt( $attrs, new JAXLXml('ping', NS_XMPP_PING) ); } public function ping() { $this->jaxl->send($this->get_ping_pkt()); } // // event callbacks // public function on_auth_success() { JAXLLoop::$clock->call_fun_periodic(30 * pow(10,6), array(&$this, 'ping')); } public function on_xmpp_ping($stanza) { if ($stanza->exists('ping', NS_XMPP_PING)) { $stanza->type = "result"; $stanza->to = $stanza->from; $stanza->from = $this->jaxl->full_jid->to_string(); $this->jaxl->send($stanza); } } } diff --git a/xep/xep_0249.php b/xep/xep_0249.php index 2887265..ba4a59f 100644 --- a/xep/xep_0249.php +++ b/xep/xep_0249.php @@ -1,78 +1,78 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DIRECT_MUC_INVITATION', 'jabber:x:conference'); class XEP_0249 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods // public function get_invite_pkt($to_bare_jid, $room_jid, $password=null, $reason=null, $thread=null, $continue=null) { - $xattrs = array('jid'=>$room_jid); + $xattrs = array('jid' => $room_jid); if ($password) $xattrs['password'] = $password; if ($reason) $xattrs['reason'] = $reason; if ($thread) $xattrs['thread'] = $thread; if ($continue) $xattrs['continue'] = $continue; return $this->jaxl->get_msg_pkt( - array('from'=>$this->jaxl->full_jid->to_string(), 'to'=>$to_bare_jid), + array('from' => $this->jaxl->full_jid->to_string(), 'to' => $to_bare_jid), null, null, null, new JAXLXml('x', NS_DIRECT_MUC_INVITATION, $xattrs) ); } public function invite($to_bare_jid, $room_jid, $password=null, $reason=null, $thread=null, $continue=null) { $this->jaxl->send($this->get_invite_pkt($to_bare_jid, $room_jid, $password, $reason, $thread, $continue)); } // // event callbacks // } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index 7490463..d90a385 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,668 +1,668 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass=null, $resource=null, $force_tls=false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if (isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; if (isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { - $stanza = new JAXLXml('auth', NS_SASL, array('mechanism'=>$mechanism)); + $stanza = new JAXLXml('auth', NS_SASL, array('mechanism' => $mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if (strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if (!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; - $data = array_merge($decoded, array('nc'=>$nc)); + $data = array_merge($decoded, array('nc' => $nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if (isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if (!$msg->id) $msg->id = $this->get_id(); if ($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if (!$pres->id) $pres->id = $this->get_id(); if ($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if (!$iq->id) $iq->id = $this->get_id(); if ($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } else if (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach ($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach (array('realm', 'cnonce', 'digest-uri') as $key) if (!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if (isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if ($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } else if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } else if ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if ($stanza->name == 'message') { $this->handle_message($stanza); } else if ($stanza->name == 'presence') { $this->handle_presence($stanza); } else if ($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } }
jaxl/JAXL
ba41df70ca034c0739a7e1b524eec0438c92d7a3
Fix PSR: Expected "foreach ("; found "foreach("
diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php index 6ecdc11..97b2c45 100644 --- a/core/jaxl_clock.php +++ b/core/jaxl_clock.php @@ -1,123 +1,123 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class JAXLClock { // current clock time in microseconds private $tick = 0; // current Unix timestamp with microseconds public $time = null; // scheduled jobs public $jobs = array(); public function __construct() { $this->time = microtime(true); } public function __destruct() { _info("shutting down clock server..."); } public function tick($by=null) { // update clock if ($by) { $this->tick += $by; $this->time += $by / pow(10,6); } else { $time = microtime(true); $by = $time - $this->time; $this->tick += $by * pow(10, 6); $this->time = $time; } // run scheduled jobs - foreach($this->jobs as $ref=>$job) { + foreach ($this->jobs as $ref=>$job) { if ($this->tick >= $job['scheduled_on'] + $job['after']) { //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".$job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); call_user_func($job['cb'], $job['args']); if (!$job['is_periodic']) { unset($this->jobs[$ref]); } else { $job['scheduled_on'] = $this->tick; $job['runs']++; $this->jobs[$ref] = $job; } } } } // calculate execution time of callback public function tc($callback, $args=null) { } // callback after $time microseconds public function call_fun_after($time, $callback, $args=null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => false, 'runs' => 0 ); return sizeof($this->jobs); } // callback periodically after $time microseconds public function call_fun_periodic($time, $callback, $args=null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => true, 'runs' => 0 ); return sizeof($this->jobs); } // cancel a previously scheduled callback public function cancel_fun_call($ref) { unset($this->jobs[$ref-1]); } } diff --git a/core/jaxl_event.php b/core/jaxl_event.php index 7026563..ee07efc 100644 --- a/core/jaxl_event.php +++ b/core/jaxl_event.php @@ -1,118 +1,118 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * following kind of events are possible: * 1) hook i.e. if a callback for such an event is registered, calling function is responsible for the workflow from their on * 2) filter i.e. calling function will manipulate passed arguments and modified arguments will be passed to next chain of filter * * As a rule of thumb, only 1 hook can be registered for an event, while more than 1 filter is allowed for an event * hook and filter both cannot be applied on an event * * @author abhinavsingh * */ class JAXLEvent { protected $common = array(); public $reg = array(); public function __construct($common) { $this->common = $common; } public function __destruct() { } // add callback on a event // returns a reference to be used while deleting callback // callback'd method must return TRUE to be persistent // if none returned or FALSE, callback will be removed automatically public function add($ev, $cb, $pri) { if (!isset($this->reg[$ev])) $this->reg[$ev] = array(); $ref = sizeof($this->reg[$ev]); $this->reg[$ev][] = array($pri, $cb); return $ev."-".$ref; } // emit event to notify registered callbacks // is a pqueue required here for performance enhancement // in case we have too many cbs on a specific event? public function emit($ev, $data=array()) { $data = array_merge($this->common, $data); $cbs = array(); if (!isset($this->reg[$ev])) return $data; - foreach($this->reg[$ev] as $cb) { + foreach ($this->reg[$ev] as $cb) { if (!isset($cbs[$cb[0]])) $cbs[$cb[0]] = array(); $cbs[$cb[0]][] = $cb[1]; } - foreach($cbs as $pri => $cb) { - foreach($cb as $c) { + foreach ($cbs as $pri => $cb) { + foreach ($cb as $c) { $ret = call_user_func_array($c, $data); // this line is for fixing situation where callback function doesn't return an array type // in such cases next call of call_user_func_array will report error since $data is not an array type as expected // things will change in future, atleast put the callback inside a try/catch block // here we only check if there was a return, if yes we update $data with return value // this is bad design, need more thoughts, should work as of now if ($ret) $data = $ret; } } unset($cbs); return $data; } // remove previous registered callback public function del($ref) { $ref = explode("-", $ref); unset($this->reg[$ref[0]][$ref[1]]); } public function exists($ev) { $ret = isset($this->reg[$ev]); //_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists")); return $ret; } } diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index 030e564..b58a796 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,156 +1,156 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLLoop { public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; private function __construct() {} private function __clone() {} public static function watch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } if (isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function unwatch($fd, $opts) { if (isset($opts['read'])) { $fdid = (int) $fd; if (isset(self::$read_fds[$fdid])) { unset(self::$read_fds[$fdid]); unset(self::$read_cbs[$fdid]); --self::$active_read_fds; } } if (isset($opts['write'])) { $fdid = (int) $fd; if (isset(self::$write_fds[$fdid])) { unset(self::$write_fds[$fdid]); unset(self::$write_cbs[$fdid]); --self::$active_write_fds; } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function run() { if (!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); - while((self::$active_read_fds + self::$active_write_fds) > 0) + while ((self::$active_read_fds + self::$active_write_fds) > 0) self::select(); _debug("no more active fd's to select"); self::$is_running = false; } } private static function select() { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); if ($changed === false) { _error("error in the event loop, shutting down..."); - /*foreach(self::$read_fds as $fd) { + /*foreach (self::$read_fds as $fd) { if (is_resource($fd)) print_r(stream_get_meta_data($fd)); }*/ exit; } else if ($changed > 0) { // read callback - foreach($read as $r) { + foreach ($read as $r) { $fdid = array_search($r, self::$read_fds); if (isset(self::$read_fds[$fdid])) call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); } // write callback - foreach($write as $w) { + foreach ($write as $w) { $fdid = array_search($w, self::$write_fds); if (isset(self::$write_fds[$fdid])) call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); } self::$clock->tick(); } else if ($changed === 0) { //_debug("nothing changed while selecting for read"); self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); } } } diff --git a/core/jaxl_util.php b/core/jaxl_util.php index 5437608..4fd242d 100644 --- a/core/jaxl_util.php +++ b/core/jaxl_util.php @@ -1,64 +1,64 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh * */ class JAXLUtil { public static function get_nonce($binary=true) { $nce = ''; mt_srand((double) microtime()*10000000); - for($i=0; $i<32; $i++) $nce .= chr(mt_rand(0, 255)); + for ($i=0; $i<32; $i++) $nce .= chr(mt_rand(0, 255)); return $binary ? $nce : base64_encode($nce); } public static function get_dns_srv($domain) { $rec = dns_get_record("_xmpp-client._tcp.".$domain, DNS_SRV); if (is_array($rec)) { if (sizeof($rec) == 0) return array($domain, 5222); if (sizeof($rec) > 0) return array($rec[0]['target'], $rec[0]['port']); } } public static function pbkdf2($data, $secret, $iteration, $dkLen=32, $algo='sha1') { return ''; } } diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index e63fef7..c2ddd79 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,196 +1,196 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if (is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if (is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if (is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; - foreach($attrs as $k=>$v) { + foreach ($attrs as $k=>$v) { if ($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } public function t($text, $append=FALSE) { if (!$append) { $this->rover->text = $text; } else { if ($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; } return $this; } public function c($name, $ns=null, $attrs=array(), $text=null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { if ($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } public function top() { $this->rover = &$this; return $this; } public function exists($name, $ns=null, $attrs=array()) { - foreach($this->childrens as $child) { + foreach ($this->childrens as $child) { if ($ns) { if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; } else if ($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } public function update($name, $ns=null, $attrs=array(), $text=null) { - foreach($this->childrens as $k=>$child) { + foreach ($this->childrens as $k=>$child) { if ($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } public function to_string($parent_ns=null) { $xml = ''; $xml .= '<'.$this->name; if ($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; - foreach($this->attrs as $k=>$v) if (!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; + foreach ($this->attrs as $k=>$v) if (!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; - foreach($this->childrens as $child) $xml .= $child->to_string($this->ns); + foreach ($this->childrens as $child) $xml .= $child->to_string($this->ns); if ($this->text) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } } diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php index adca378..7605df3 100644 --- a/core/jaxl_xml_stream.php +++ b/core/jaxl_xml_stream.php @@ -1,188 +1,188 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Enter description here ... * @author abhinavsingh * */ class JAXLXmlStream { private $delimiter = '\\'; private $ns; private $parser; private $stanza; private $depth = -1; private $start_cb; private $stanza_cb; private $end_cb; public function __construct() { $this->init_parser(); } private function init_parser() { $this->depth = -1; $this->parser = xml_parser_create_ns("UTF-8", $this->delimiter); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); xml_set_character_data_handler($this->parser, array(&$this, "handle_character")); xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag")); } public function __destruct() { //_debug("cleaning up xml parser..."); @xml_parser_free($this->parser); } public function reset_parser() { $this->parse_final(null); @xml_parser_free($this->parser); $this->parser = null; $this->init_parser(); } public function set_callback($start_cb, $end_cb, $stanza_cb) { $this->start_cb = $start_cb; $this->end_cb = $end_cb; $this->stanza_cb = $stanza_cb; } public function parse($str) { xml_parse($this->parser, $str, false); } public function parse_final($str) { xml_parse($this->parser, $str, true); } protected function handle_start_tag($parser, $name, $attrs) { $name = $this->explode($name); //echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL; // replace ns with prefix - foreach($attrs as $key=>$v) { + foreach ($attrs as $key=>$v) { $k = $this->explode($key); // no ns specified if ($k[0] == null) { $attrs[$k[1]] = $v; } // xml ns else if ($k[0] == NS_XML) { unset($attrs[$key]); $attrs['xml:'.$k[1]] = $v; } else { _error("==================> unhandled ns prefix on attribute"); // remove attribute else will cause error with bad stanza format // report to developer if above error message is ever encountered unset($attrs[$key]); } } if ($this->depth <= 0) { $this->depth = 0; $this->ns = $name[1]; if ($this->start_cb) { $stanza = new JAXLXml($name[1], $name[0], $attrs); call_user_func($this->start_cb, $stanza); } } else { if (!$this->stanza) { $stanza = new JAXLXml($name[1], $name[0], $attrs); $this->stanza = &$stanza; } else { $this->stanza->c($name[1], $name[0], $attrs); } } ++$this->depth; } protected function handle_end_tag($parser, $name) { $name = explode($this->delimiter, $name); $name = sizeof($name) == 1 ? array('', $name[0]) : $name; //echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL; if ($this->depth == 1) { if ($this->end_cb) { $stanza = new JAXLXml($name[1], $this->ns); call_user_func($this->end_cb, $stanza); } } else if ($this->depth > 1) { if ($this->stanza) $this->stanza->up(); if ($this->depth == 2) { if ($this->stanza_cb) { call_user_func($this->stanza_cb, $this->stanza); $this->stanza = null; } } } --$this->depth; } protected function handle_character($parser, $data) { //echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL; if ($this->stanza) { $this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), TRUE); } } private function implode($data) { return implode($this->delimiter, $data); } private function explode($data) { $data = explode($this->delimiter, $data); $data = sizeof($data) == 1 ? array(null, $data[0]) : $data; return $data; } } diff --git a/examples/multi_client.php b/examples/multi_client.php index cd150c2..4208b51 100644 --- a/examples/multi_client.php +++ b/examples/multi_client.php @@ -1,127 +1,127 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // enable multi client support // this will force 1st parameter of callbacks // as connected client instance define('JAXL_MULTI_CLIENT', true); // input multiple account credentials $accounts = array(); $add_new = TRUE; -while($add_new) { +while ($add_new) { $jid = readline('Enter Jabber Id: '); $pass = readline('Enter Password: '); $accounts[] = array($jid, $pass); $next = readline('Add another account (y/n): '); $add_new = $next == 'y' ? TRUE : FALSE; } // setup jaxl require_once 'jaxl.php'; // // common callbacks // function on_auth_success($client) { _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // fetch roster list $client->get_roster(); // fetch vcard $client->get_vcard(); // set status $client->set_status("available!", "dnd", 10); } function on_auth_failure($client, $reason) { _info("got on_auth_failure cb with reason $reason"); $client->send_end_stream(); } function on_chat_message($client, $stanza) { // echo back incoming chat message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); } function on_presence_stanza($client, $stanza) { global $client; $type = ($stanza->type ? $stanza->type : "available"); $show = ($stanza->show ? $stanza->show : "???"); _info($stanza->from." is now ".$type." ($show)"); if ($type == "available") { // fetch vcard $client->get_vcard($stanza->from); } } function on_disconnect($client) { _info("got on_disconnect cb"); } // // bootstrap all account instances // -foreach($accounts as $account) { +foreach ($accounts as $account) { $client = new JAXL(array( 'jid' => $account[0], 'pass' => $account[1], 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', 'on_auth_success'); $client->add_cb('on_auth_failure', 'on_auth_failure'); $client->add_cb('on_chat_message', 'on_chat_message'); $client->add_cb('on_presence_stanza', 'on_presence_stanza'); $client->add_cb('on_disconnect', 'on_disconnect'); $client->connect($client->get_socket_path()); $client->start_stream(); } // start core loop JAXLLoop::run(); echo "done\n"; diff --git a/examples/register_user.php b/examples/register_user.php index 6c9c03f..16b7559 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,167 +1,167 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if ($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // $form = array(); function wait_for_register_response($event, $args) { global $client, $form; if ($event == 'stanza_cb') { $stanza = $args[0]; if ($stanza->name == 'iq') { $form['type'] = $stanza->attrs['type']; if ($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } else if ($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } } } else { _notice("unhandled event $event rcvd"); } } function wait_for_register_form($event, $args) { global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if ($query) { $instructions = $query->exists('instructions'); if ($instructions) { echo $instructions->text.PHP_EOL; } - foreach($query->childrens as $k=>$child) { + foreach ($query->childrens as $k=>$child) { if ($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // $client->add_cb('on_stream_features', function($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; }); $client->add_cb('on_disconnect', function() { global $form; _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); }); // // finally start configured xmpp stream // $client->start(); // // if registration was successful // try to connect with newly registered account // if ($form['type'] == 'result') { _info("connecting newly registered user account"); $client = new JAXL(array( 'jid' => $form['username'].'@'.$argv[1], 'pass' => $form['password'], 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', function() { global $client; $client->set_status('Available'); }); $client->start(); } echo "done\n"; diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php index 9e4f325..4c9a6d4 100644 --- a/http/http_dispatcher.php +++ b/http/http_dispatcher.php @@ -1,117 +1,117 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // // (optionally) set an array of url dispatch rules // each dispatch rule is defined by an array of size 4 like: // array($callback, $pattern, $methods, $extra), where // $callback the method which will be called if this rule matches // $pattern regular expression to match request path // $methods list of allowed methods for this rule // pass boolean true to allow all http methods // if omitted or an empty array() is passed (which actually doesnt make sense) // by default 'GET' will be the method allowed on this rule // $extra reserved for future (you can totally omit this as of now) // class HTTPDispatchRule { // match callback public $cb = null; // regexp to match on request path public $pattern = null; // methods to match upon // add atleast 1 method for this rule to work public $methods = null; // other matching rules public $extra = array(); public function __construct($cb, $pattern, $methods=array('GET'), $extra=array()) { $this->cb = $cb; $this->pattern = $pattern; $this->methods = $methods; $this->extra = $extra; } public function match($path, $method) { if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) { if (in_array($method, $this->methods)) { return $matches; } } return false; } } class HTTPDispatcher { protected $rules = array(); public function __construct() { $this->rules = array(); } public function add_rule($rule) { $s = sizeof($rule); if ($s > 4) { _debug("invalid rule"); return; } // fill up defaults if ($s == 3) { $rule[] = array(); } else if ($s == 2) { $rule[] = array('GET'); $rule[] = array(); } else { _debug("invalid rule"); return; } $this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]); } public function dispatch($request) { - foreach($this->rules as $rule) { + foreach ($this->rules as $rule) { //_debug("matching $request->path with pattern $rule->pattern"); if (($matches = $rule->match($request->path, $request->method)) !== false) { _debug("matching rule found, dispatching"); $params = array($request); // TODO: a bad way to restrict on 'pk', fix me for generalization if (@isset($matches['pk'])) $params[] = $matches['pk']; call_user_func_array($rule->cb, $params); return true; } } return false; } } diff --git a/http/http_multipart.php b/http/http_multipart.php index ebe4444..245bfcd 100644 --- a/http/http_multipart.php +++ b/http/http_multipart.php @@ -1,173 +1,173 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; class HTTPMultiPart extends JAXLFsm { public $boundary = null; public $form_data = array(); public $index = -1; public function handle_invalid_state($r) { _error("got invalid event $r"); } public function __construct($boundary) { $this->boundary = $boundary; parent::__construct('wait_for_boundary_start'); } public function state() { return $this->state; } public function wait_for_boundary_start($event, $data) { if ($event == 'process') { if ($data[0] == '--'.$this->boundary) { $this->index += 1; $this->form_data[$this->index] = array( 'meta' => array(), 'headers' => array(), 'body' => '' ); return array('wait_for_content_disposition', true); } else { _warning("invalid boundary start $data[0] while expecting $this->boundary"); return array('wait_for_boundary_start', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_boundary_start', false); } } public function wait_for_content_disposition($event, $data) { if ($event == 'process') { $disposition = explode(":", $data[0]); if (strtolower(trim($disposition[0])) == 'content-disposition') { $this->form_data[$this->index]['headers'][$disposition[0]] = trim($disposition[1]); $meta = explode(";", $disposition[1]); if (trim(array_shift($meta)) == 'form-data') { - foreach($meta as $k) { + foreach ($meta as $k) { list($k, $v) = explode("=", $k); $this->form_data[$this->index]['meta'][$k] = $v; } return array('wait_for_content_type', true); } else { _warning("first part of meta is not form-data"); return array('wait_for_content_disposition', false); } } else { _warning("not a valid content-disposition line"); return array('wait_for_content_disposition', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_disposition', false); } } public function wait_for_content_type($event, $data) { if ($event == 'process') { $type = explode(":", $data[0]); if (strtolower(trim($type[0])) == 'content-type') { $this->form_data[$this->index]['headers'][$type[0]] = trim($type[1]); $this->form_data[$this->index]['meta']['type'] = $type[1]; return array('wait_for_content_body', true); } else { _debug("not a valid content-type line"); return array('wait_for_content_type', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_type', false); } } public function wait_for_content_body($event, $data) { if ($event == 'process') { if ($data[0] == '--'.$this->boundary) { _debug("start of new multipart/form-data detected"); return array('wait_for_content_disposition', true); } else if ($data[0] == '--'.$this->boundary.'--') { _debug("end of multipart form data detected"); return array('wait_for_empty_line', true); } else { $this->form_data[$this->index]['body'] .= $data[0]; return array('wait_for_content_body', true); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_body', false); } } public function wait_for_empty_line($event, $data) { if ($event == 'process') { if ($data[0] == '') { return array('done', true); } else { _warning("invalid empty line $data[0] received"); return array('wait_for_empty_line', false); } } else { _warning("got $event in done state with data $data[0]"); return array('wait_for_empty_line', false); } } public function done($event, $data) { _warning("got unhandled event $event with data $data[0]"); return array('done', false); } } diff --git a/http/http_request.php b/http/http_request.php index a6fd0ce..ffa81be 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,488 +1,488 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers=array(), $body=null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if (sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation // public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; if ($this->body === null) $this->body = $rcvd; else $this->body .= $rcvd; if ($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); - foreach($form_data as $data) { + foreach ($form_data as $data) { //_debug("passing $data to multipart fsm"); if (!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if (!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if (!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { switch($event) { case 'empty_line': return 'headers_received'; break; default: if (substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if (method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } } else if (@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { $k = trim($k); $v = ltrim($v); // is expect header? if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if (strtolower($k) == 'content-type') { $ctype = explode(';', $v); if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if (strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if ($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { if (sizeof($args) == 0) { $body = null; $headers = array(); } if (sizeof($args) == 1) { // http headers or body only received if (is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } } else if (sizeof($args) == 2) { // body and http headers both received if (is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { - foreach($headers as $k=>$v) + foreach ($headers as $k=>$v) $this->_send_header($k, $v); } protected function _send_body($body) { $this->_send($body); } protected function _send_response($code, $headers=array(), $body=null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set if ($body && !isset($headers['Content-Length'])) $headers['Content-Length'] = strlen($body); // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); if ($body) $this->_send_body(HTTP_CRLF.$body); } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if (sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); - foreach($query as $q) { + foreach ($query as $q) { $q = explode("=", $q); if (sizeof($q) == 1) $q[1] = ""; $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } } diff --git a/http/http_server.php b/http/http_server.php index 32f7118..67220f6 100644 --- a/http/http_server.php +++ b/http/http_server.php @@ -1,194 +1,194 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/http/http_dispatcher.php'; require_once JAXL_CWD.'/http/http_request.php'; // carriage return and line feed define('HTTP_CRLF', "\r\n"); // 1xx informational define('HTTP_100', "Continue"); define('HTTP_101', "Switching Protocols"); // 2xx success define('HTTP_200', "OK"); // 3xx redirection define('HTTP_301', 'Moved Permanently'); define('HTTP_304', 'Not Modified'); // 4xx client error define('HTTP_400', 'Bad Request'); define('HTTP_403', 'Forbidden'); define('HTTP_404', 'Not Found'); define('HTTP_405', 'Method Not Allowed'); define('HTTP_499', 'Client Closed Request'); // Nginx // 5xx server error define('HTTP_500', 'Internal Server Error'); define('HTTP_503', 'Service Unavailable'); class HTTPServer { private $server = null; public $cb = null; private $dispatcher = null; private $requests = array(); public function __construct($port=9699, $address="127.0.0.1") { $path = 'tcp://'.$address.':'.$port; $this->server = new JAXLSocketServer( $path, array(&$this, 'on_accept'), array(&$this, 'on_request') ); $this->dispatcher = new HTTPDispatcher(); } public function __destruct() { $this->server = null; } public function dispatch($rules) { - foreach($rules as $rule) { + foreach ($rules as $rule) { $this->dispatcher->add_rule($rule); } } public function start($cb=null) { $this->cb = $cb; JAXLLoop::run(); } public function on_accept($sock, $addr) { _debug("on_accept for client#$sock, addr:$addr"); // initialize new request obj $request = new HTTPRequest($sock, $addr); // setup sock cb $request->set_sock_cb( array(&$this->server, 'send'), array(&$this->server, 'read'), array(&$this->server, 'close') ); // cache request object $this->requests[$sock] = &$request; // reactive client for further read $this->server->read($sock); } public function on_request($sock, $raw) { _debug("on_request for client#$sock"); $request = $this->requests[$sock]; // 'wait_for_body' state is reached when ever // application calls recv_body() method // on received $request object if ($request->state() == 'wait_for_body') { $request->body($raw); } else { // break on crlf $lines = explode(HTTP_CRLF, $raw); // parse request line if ($request->state() == 'wait_for_request_line') { list($method, $resource, $version) = explode(" ", $lines[0]); $request->line($method, $resource, $version); unset($lines[0]); _info($request->ip." ".$request->method." ".$request->resource." ".$request->version); } // parse headers - foreach($lines as $line) { + foreach ($lines as $line) { $line_parts = explode(":", $line); if (sizeof($line_parts) > 1) { if (strlen($line_parts[0]) > 0) { $k = $line_parts[0]; unset($line_parts[0]); $v = implode(":", $line_parts); $request->set_header($k, $v); } } else if (strlen(trim($line_parts[0])) == 0) { $request->empty_line(); } // if exploded line array size is 1 // and thr is something in $line_parts[0] // must be request body else { $request->body($line); } } } // if request has reached 'headers_received' state? if ($request->state() == 'headers_received') { // dispatch to any matching rule found _debug("delegating to dispatcher for further routing"); $dispatched = $this->dispatcher->dispatch($request); // if no dispatch rule matched call generic callback if (!$dispatched && $this->cb) { _debug("no dispatch rule matched, sending to generic callback"); call_user_func($this->cb, $request); } // else if not dispatched and not generic callbacked // send 404 not_found else if (!$dispatched) { // TODO: send 404 if no callback is registered for this request _debug("dropping request since no matching dispatch rule or generic callback was specified"); $request->not_found('404 Not Found'); } } // if state is not 'headers_received' // reactivate client socket for read event else { $this->server->read($sock); } } } diff --git a/jaxl.php b/jaxl.php index ff0fd39..c94a689 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,806 +1,806 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger if (isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if (isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if ($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if (!is_dir($this->priv_dir)) mkdir($this->priv_dir); if (!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if (!is_dir($this->pid_dir)) mkdir($this->pid_dir); if (!is_dir($this->log_dir)) mkdir($this->log_dir); if (!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if (!is_array($xeps)) $xeps = array($xeps); - foreach($xeps as $xep) { + foreach ($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events - foreach($this->xeps[$xep]->init() as $ev=>$cb) { + foreach ($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if (@$this->cfg['bosh_url']) { $this->trans->session_start(); - for(;;) { + for (;;) { // while any of the curl request is pending // keep receiving response - while(sizeof($this->trans->chs) != 0) { + while (sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if (!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if (@$opts['--with-debug-shell']) $this->enable_debug_shell(); if (@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); - if ($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; + if ($mechanisms) foreach ($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if ($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { - foreach($mechs as $mech=>$any) { + foreach ($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if ($mech == 'X-FACEBOOK-PLATFORM') { if (@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if ($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if ($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if ($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if (!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { - foreach($query->childrens as $child) { + foreach ($query->childrens as $child) { if ($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); - foreach($child->childrens as $group) { + foreach ($child->childrens as $group) { if ($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if (!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if (@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if (!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if ($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if ($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if ($type == 'unavailable') { if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if ($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if ($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); - foreach($query->childrens as $k=>$child) { + foreach ($query->childrens as $k=>$child) { if ($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if ($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if ($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); - foreach($query->childrens as $k=>$child) { + foreach ($query->childrens as $k=>$child) { if ($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } diff --git a/tests/test_jaxl_socket_client.php b/tests/test_jaxl_socket_client.php index 55f298f..f1fadb8 100644 --- a/tests/test_jaxl_socket_client.php +++ b/tests/test_jaxl_socket_client.php @@ -1,59 +1,59 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLSocketClientTest extends PHPUnit_Framework_TestCase { function test_jaxl_socket_client() { $sock = new JAXLSocketClient("127.0.0.1", 5222); $sock->connect(); $sock->send("<stream:stream>"); - while($sock->fd) { + while ($sock->fd) { $sock->recv(); } } } diff --git a/tests/test_xmpp_stream.php b/tests/test_xmpp_stream.php index 19b2b4b..e078789 100644 --- a/tests/test_xmpp_stream.php +++ b/tests/test_xmpp_stream.php @@ -1,59 +1,59 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPStreamTest extends PHPUnit_Framework_TestCase { function test_xmpp_stream() { $xmpp = new XMPPStream("test@localhost", "password"); $xmpp->connect(); $xmpp->start_stream(); - while($xmpp->sock->fd) { + while ($xmpp->sock->fd) { $xmpp->sock->recv(); } } } diff --git a/xep/xep_0077.php b/xep/xep_0077.php index 9ec3074..68f1cd9 100644 --- a/xep/xep_0077.php +++ b/xep/xep_0077.php @@ -1,80 +1,80 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_FEATURE_REGISTER', 'http://jabber.org/features/iq-register'); define('NS_INBAND_REGISTER', 'jabber:iq:register'); class XEP_0077 extends XMPPXep { // // abstract method // public function init() { return array( ); } // // api methods // public function get_form_pkt($domain) { return $this->jaxl->get_iq_pkt( array('to'=>$domain, 'type'=>'get'), new JAXLXml('query', NS_INBAND_REGISTER) ); } public function get_form($domain) { $this->jaxl->send($this->get_form_pkt($domain)); } public function set_form($domain, $form) { $query = new JAXLXml('query', NS_INBAND_REGISTER); - foreach($form as $k=>$v) $query->c($k, null, array(), $v)->up(); + foreach ($form as $k=>$v) $query->c($k, null, array(), $v)->up(); $pkt = $this->jaxl->get_iq_pkt( array('to'=>$domain, 'type'=>'set'), $query ); $this->jaxl->send($pkt); } } diff --git a/xep/xep_0115.php b/xep/xep_0115.php index 281d620..3f956c5 100644 --- a/xep/xep_0115.php +++ b/xep/xep_0115.php @@ -1,70 +1,70 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_CAPS', 'http://jabber.org/protocol/caps'); class XEP_0115 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods // public function get_caps_pkt($cat, $type, $lang, $name, $node, $features) { asort($features); $S = $cat.'/'.$type.'/'.$lang.'/'.$name.'<'; - foreach($features as $feature) $S .= $feature.'<'; + foreach ($features as $feature) $S .= $feature.'<'; $ver = base64_encode(sha1($S, true)); $stanza = new JAXLXml('c', NS_CAPS, array('hash'=>'sha1', 'node'=>$node, 'ver'=>$ver)); return $stanza; } // // event callbacks // } diff --git a/xep/xep_0206.php b/xep/xep_0206.php index c8f58a5..f39b80d 100644 --- a/xep/xep_0206.php +++ b/xep/xep_0206.php @@ -1,233 +1,233 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind'); define('NS_BOSH', 'urn:xmpp:xbosh'); class XEP_0206 extends XMPPXep { private $mch = null; public $chs = array(); private $recv_cb = null; public $rid = null; public $sid = null; private $hold = 1; private $wait = 30; private $restarted = false; public $headers = array( 'Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8' ); // // abstract method // public function init() { $this->mch = curl_multi_init(); return array( ); } // // event callbacks // public function send($body) { if (is_object($body)) { $body = $body->to_string(); } else { if (substr($body, 0, 15) == '<stream:stream ') { $this->restarted = true; $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'xmpp:restart' => 'true', 'xmlns:xmpp' => NS_BOSH )); $body = $body->to_string(); } else if (substr($body, 0, 16) == '</stream:stream>') { $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'type' => 'terminate' )); $body = $body->to_string(); } else { $body = $this->wrap($body); } } _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body); $this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']); curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers); curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false); curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1); curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body); curl_multi_add_handle($this->mch, $this->chs[$this->rid]); } public function recv() { if ($this->restarted) { $this->restarted = false; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); } _debug("recving for $this->rid"); do { $ret = curl_multi_exec($this->mch, $running); $changed = curl_multi_select($this->mch, 0.1); if ($changed == 0 && $running == 0) { $ch = @$this->chs[$this->rid]; if ($ch) { $data = curl_multi_getcontent($ch); curl_multi_remove_handle($this->mch, $ch); unset($this->chs[$this->rid]); _debug("recvd for $this->rid ".$data); list($body, $stanza) = $this->unwrap($data); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if (@$attrs['type'] == 'terminate') { // fool me again if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); } else { if (!$this->sid) { $this->sid = $attrs['sid']; } if ($this->recv_cb) call_user_func($this->recv_cb, $stanza); } } else { _error("no ch found"); exit; } } - } while($running); + } while ($running); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function wrap($stanza) { return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>'; } public function unwrap($body) { // a dirty way but it works efficiently if (substr($body, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); if (isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; else $envelop = "<body/>"; if (isset($m[2][0])) $payload = $m[2][0]; else $payload = ''; return array($envelop, $payload); } public function session_start() { $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000); $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold; $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); $attrs = array( 'content' => 'text/xml; charset=utf-8', 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'], 'secure' => 'true', 'xml:lang' => 'en', 'xmpp:version' => '1.0', 'xmlns:xmpp' => NS_BOSH, 'hold' => $this->hold, 'wait' => $this->wait, 'rid' => $this->rid, 'ver' => '1.10' ); if (@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; $body = new JAXLXml('body', NS_HTTP_BIND, $attrs); $this->send($body); } public function ping() { $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid)); $this->send($body); } public function session_end() { $this->disconnect(); } public function disconnect() { _debug("disconnecting"); } } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index 77fea57..7490463 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,668 +1,668 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass=null, $resource=null, $force_tls=false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if (isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; if (isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism'=>$mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if (strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if (!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc'=>$nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); - foreach(array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) + foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if (isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if (!$msg->id) $msg->id = $this->get_id(); if ($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if (!$pres->id) $pres->id = $this->get_id(); if ($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if (!$iq->id) $iq->id = $this->get_id(); if ($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; - foreach($data as $pair) { + foreach ($data as $pair) { $dd = strpos($pair, '='); if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } else if (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); - foreach($data as $key => $value) $return[] = $key . '="' . $value . '"'; + foreach ($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { - foreach(array('realm', 'cnonce', 'digest-uri') as $key) + foreach (array('realm', 'cnonce', 'digest-uri') as $key) if (!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if (isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if ($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } else if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } else if ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if ($stanza->name == 'message') { $this->handle_message($stanza); } else if ($stanza->name == 'presence') { $this->handle_presence($stanza); } else if ($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } }
jaxl/JAXL
fa01b37b08a4c7e542e1fee69f23b9334ba08ce0
Fix PSR: Expected "if ("; found "if("
diff --git a/core/jaxl_cli.php b/core/jaxl_cli.php index ad763bd..c49d063 100644 --- a/core/jaxl_cli.php +++ b/core/jaxl_cli.php @@ -1,94 +1,94 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLCli { public static $counter = 0; private $in = null; private $quit_cb = null; private $recv_cb = null; private $recv_chunk_size = 1024; public function __construct($recv_cb=null, $quit_cb=null) { $this->recv_cb = $recv_cb; $this->quit_cb = $quit_cb; // catch read event on stdin $this->in = fopen('php://stdin', 'r'); stream_set_blocking($this->in, false); JAXLLoop::watch($this->in, array( 'read' => array(&$this, 'on_read_ready') )); } public function __destruct() { @fclose($this->in); } public function stop() { JAXLLoop::unwatch($this->in, array( 'read' => true )); } public function on_read_ready($in) { $raw = @fread($in, $this->recv_chunk_size); - if(ord($raw) == 10) { + if (ord($raw) == 10) { // enter key JAXLCli::prompt(false); return; } - else if(trim($raw) == 'quit') { + else if (trim($raw) == 'quit') { $this->stop(); $this->in = null; - if($this->quit_cb) call_user_func($this->quit_cb); + if ($this->quit_cb) call_user_func($this->quit_cb); return; } - if($this->recv_cb) call_user_func($this->recv_cb, $raw); + if ($this->recv_cb) call_user_func($this->recv_cb, $raw); } public static function prompt($inc=true) { - if($inc) ++self::$counter; + if ($inc) ++self::$counter; echo "jaxl ".self::$counter."> "; } } diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php index 22f58b2..6ecdc11 100644 --- a/core/jaxl_clock.php +++ b/core/jaxl_clock.php @@ -1,123 +1,123 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class JAXLClock { // current clock time in microseconds private $tick = 0; // current Unix timestamp with microseconds public $time = null; // scheduled jobs public $jobs = array(); public function __construct() { $this->time = microtime(true); } public function __destruct() { _info("shutting down clock server..."); } public function tick($by=null) { // update clock - if($by) { + if ($by) { $this->tick += $by; $this->time += $by / pow(10,6); } else { $time = microtime(true); $by = $time - $this->time; $this->tick += $by * pow(10, 6); $this->time = $time; } // run scheduled jobs foreach($this->jobs as $ref=>$job) { - if($this->tick >= $job['scheduled_on'] + $job['after']) { + if ($this->tick >= $job['scheduled_on'] + $job['after']) { //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".$job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); call_user_func($job['cb'], $job['args']); - if(!$job['is_periodic']) { + if (!$job['is_periodic']) { unset($this->jobs[$ref]); } else { $job['scheduled_on'] = $this->tick; $job['runs']++; $this->jobs[$ref] = $job; } } } } // calculate execution time of callback public function tc($callback, $args=null) { } // callback after $time microseconds public function call_fun_after($time, $callback, $args=null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => false, 'runs' => 0 ); return sizeof($this->jobs); } // callback periodically after $time microseconds public function call_fun_periodic($time, $callback, $args=null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => true, 'runs' => 0 ); return sizeof($this->jobs); } // cancel a previously scheduled callback public function cancel_fun_call($ref) { unset($this->jobs[$ref-1]); } } diff --git a/core/jaxl_event.php b/core/jaxl_event.php index 72207c3..7026563 100644 --- a/core/jaxl_event.php +++ b/core/jaxl_event.php @@ -1,118 +1,118 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * following kind of events are possible: * 1) hook i.e. if a callback for such an event is registered, calling function is responsible for the workflow from their on * 2) filter i.e. calling function will manipulate passed arguments and modified arguments will be passed to next chain of filter * * As a rule of thumb, only 1 hook can be registered for an event, while more than 1 filter is allowed for an event * hook and filter both cannot be applied on an event * * @author abhinavsingh * */ class JAXLEvent { protected $common = array(); public $reg = array(); public function __construct($common) { $this->common = $common; } public function __destruct() { } // add callback on a event // returns a reference to be used while deleting callback // callback'd method must return TRUE to be persistent // if none returned or FALSE, callback will be removed automatically public function add($ev, $cb, $pri) { - if(!isset($this->reg[$ev])) + if (!isset($this->reg[$ev])) $this->reg[$ev] = array(); $ref = sizeof($this->reg[$ev]); $this->reg[$ev][] = array($pri, $cb); return $ev."-".$ref; } // emit event to notify registered callbacks // is a pqueue required here for performance enhancement // in case we have too many cbs on a specific event? public function emit($ev, $data=array()) { $data = array_merge($this->common, $data); $cbs = array(); - if(!isset($this->reg[$ev])) return $data; + if (!isset($this->reg[$ev])) return $data; foreach($this->reg[$ev] as $cb) { - if(!isset($cbs[$cb[0]])) + if (!isset($cbs[$cb[0]])) $cbs[$cb[0]] = array(); $cbs[$cb[0]][] = $cb[1]; } foreach($cbs as $pri => $cb) { foreach($cb as $c) { $ret = call_user_func_array($c, $data); // this line is for fixing situation where callback function doesn't return an array type // in such cases next call of call_user_func_array will report error since $data is not an array type as expected // things will change in future, atleast put the callback inside a try/catch block // here we only check if there was a return, if yes we update $data with return value // this is bad design, need more thoughts, should work as of now - if($ret) $data = $ret; + if ($ret) $data = $ret; } } unset($cbs); return $data; } // remove previous registered callback public function del($ref) { $ref = explode("-", $ref); unset($this->reg[$ref[0]][$ref[1]]); } public function exists($ev) { $ret = isset($this->reg[$ev]); //_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists")); return $ret; } } diff --git a/core/jaxl_exception.php b/core/jaxl_exception.php index 4d9841f..d49544d 100644 --- a/core/jaxl_exception.php +++ b/core/jaxl_exception.php @@ -1,92 +1,92 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ error_reporting(E_ALL | E_STRICT); /** * * @author abhinavsingh */ class JAXLException extends Exception { public function __construct($message = null, $code = null, $file = null, $line = null) { _notice("got jaxl exception construct with $message, $code, $file, $line"); - if($code === null) { + if ($code === null) { parent::__construct($message); } else { parent::__construct($message, $code); } - if($file !== null) { + if ($file !== null) { $this->file = $file; } - if($line !== null) { + if ($line !== null) { $this->line = $line; } } public static function error_handler($errno, $error, $file, $line, $vars) { _debug("error handler called with $errno, $error, $file, $line"); - if($errno === 0 || ($errno & error_reporting()) === 0) { + if ($errno === 0 || ($errno & error_reporting()) === 0) { return; } throw new JAXLException($error, $errno, $file, $line); } public static function exception_handler($e) { _debug("exception handler catched ".json_encode($e)); // TODO: Pretty print backtrace //print_r(debug_backtrace()); } public static function shutdown_handler() { try { _debug("got shutdown handler"); - if(null !== ($error = error_get_last())) { + if (null !== ($error = error_get_last())) { throw new JAXLException($error['message'], $error['type'], $error['file'], $error['line']); } } catch(Exception $e) { _debug("shutdown handler catched with exception ".json_encode($e)); } } } diff --git a/core/jaxl_fsm.php b/core/jaxl_fsm.php index 03687b5..fe26972 100644 --- a/core/jaxl_fsm.php +++ b/core/jaxl_fsm.php @@ -1,81 +1,81 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ abstract class JAXLFsm { protected $state = null; // abstract method abstract public function handle_invalid_state($r); public function __construct($state) { $this->state = $state; } // returned value from state callbacks can be: // 1) array() <-- is_callable method // 2) array([0]=>'new_state', [1]=>'return value for current callback') <-- is_not_callable method // 3) array([0]=>'new_state') // 4) 'new_state' // // for case 1) new state will be an array // for other cases new state will be a string public function __call($event, $args) { - if($this->state) { + if ($this->state) { // call state method _debug("calling state handler '".(is_array($this->state) ? $this->state[1] : $this->state)."' for incoming event '".$event."'"); $call = is_callable($this->state) ? $this->state : (method_exists($this, $this->state) ? array(&$this, $this->state): $this->state); $r = call_user_func($call, $event, $args); // 4 cases of possible return value - if(is_callable($r)) $this->state = $r; - else if(is_array($r) && sizeof($r) == 2) list($this->state, $ret) = $r; - else if(is_array($r) && sizeof($r) == 1) $this->state = $r[0]; - else if(is_string($r)) $this->state = $r; + if (is_callable($r)) $this->state = $r; + else if (is_array($r) && sizeof($r) == 2) list($this->state, $ret) = $r; + else if (is_array($r) && sizeof($r) == 1) $this->state = $r[0]; + else if (is_string($r)) $this->state = $r; else $this->handle_invalid_state($r); _debug("current state '".(is_array($this->state) ? $this->state[1] : $this->state)."'"); // return case - if(!is_callable($r) && is_array($r) && sizeof($r) == 2) + if (!is_callable($r) && is_array($r) && sizeof($r) == 2) return $ret; } else { _debug("invalid state found, nothing called for event ".$event.""); } } } diff --git a/core/jaxl_logger.php b/core/jaxl_logger.php index e46a79f..04d98de 100644 --- a/core/jaxl_logger.php +++ b/core/jaxl_logger.php @@ -1,89 +1,89 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // log level define('JAXL_ERROR', 1); define('JAXL_WARNING', 2); define('JAXL_NOTICE', 3); define('JAXL_INFO', 4); define('JAXL_DEBUG', 5); // generic global logging shortcuts for different level of verbosity function _error($msg) { JAXLLogger::log($msg, JAXL_ERROR); } function _warning($msg) { JAXLLogger::log($msg, JAXL_WARNING); } function _notice($msg) { JAXLLogger::log($msg, JAXL_NOTICE); } function _info($msg) { JAXLLogger::log($msg, JAXL_INFO); } function _debug($msg) { JAXLLogger::log($msg, JAXL_DEBUG); } // generic global terminal output colorize method // finally sends colorized message to terminal using error_log/1 // this method is mainly to escape $msg from file:line and time // prefix done by _debug, _error, ... methods function _colorize($msg, $verbosity) { error_log(JAXLLogger::colorize($msg, $verbosity)); } class JAXLLogger { public static $level = JAXL_DEBUG; public static $path = null; public static $max_log_size = 1000; protected static $colors = array( 1 => 31, // error: red 2 => 34, // warning: blue 3 => 33, // notice: yellow 4 => 32, // info: green 5 => 37 // debug: white ); public static function log($msg, $verbosity=1) { - if($verbosity <= self::$level) { + if ($verbosity <= self::$level) { $bt = debug_backtrace(); array_shift($bt); $callee = array_shift($bt); $msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg; $size = strlen($msg); - if($size > self::$max_log_size) $msg = substr($msg, 0, self::$max_log_size) . ' ...'; + if ($size > self::$max_log_size) $msg = substr($msg, 0, self::$max_log_size) . ' ...'; - if(isset(self::$path)) error_log($msg . PHP_EOL, 3, self::$path); + if (isset(self::$path)) error_log($msg . PHP_EOL, 3, self::$path); else error_log(self::colorize($msg, $verbosity)); } } public static function colorize($msg, $verbosity) { return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m"; } } diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index b08b605..030e564 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,156 +1,156 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLLoop { public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; private function __construct() {} private function __clone() {} public static function watch($fd, $opts) { - if(isset($opts['read'])) { + if (isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } - if(isset($opts['write'])) { + if (isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function unwatch($fd, $opts) { - if(isset($opts['read'])) { + if (isset($opts['read'])) { $fdid = (int) $fd; - if(isset(self::$read_fds[$fdid])) { + if (isset(self::$read_fds[$fdid])) { unset(self::$read_fds[$fdid]); unset(self::$read_cbs[$fdid]); --self::$active_read_fds; } } - if(isset($opts['write'])) { + if (isset($opts['write'])) { $fdid = (int) $fd; - if(isset(self::$write_fds[$fdid])) { + if (isset(self::$write_fds[$fdid])) { unset(self::$write_fds[$fdid]); unset(self::$write_cbs[$fdid]); --self::$active_write_fds; } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function run() { - if(!self::$is_running) { + if (!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); while((self::$active_read_fds + self::$active_write_fds) > 0) self::select(); _debug("no more active fd's to select"); self::$is_running = false; } } private static function select() { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); - if($changed === false) { + if ($changed === false) { _error("error in the event loop, shutting down..."); /*foreach(self::$read_fds as $fd) { - if(is_resource($fd)) + if (is_resource($fd)) print_r(stream_get_meta_data($fd)); }*/ exit; } - else if($changed > 0) { + else if ($changed > 0) { // read callback foreach($read as $r) { $fdid = array_search($r, self::$read_fds); - if(isset(self::$read_fds[$fdid])) + if (isset(self::$read_fds[$fdid])) call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); } // write callback foreach($write as $w) { $fdid = array_search($w, self::$write_fds); - if(isset(self::$write_fds[$fdid])) + if (isset(self::$write_fds[$fdid])) call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); } self::$clock->tick(); } - else if($changed === 0) { + else if ($changed === 0) { //_debug("nothing changed while selecting for read"); self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); } } } diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php index c354daa..cbad13a 100644 --- a/core/jaxl_pipe.php +++ b/core/jaxl_pipe.php @@ -1,112 +1,112 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * bidirectional communication pipes for processes * * This is how this will be (when complete): * $pipe = new JAXLPipe() will return an array of size 2 * $pipe[0] represents the read end of the pipe * $pipe[1] represents the write end of the pipe * * Proposed functionality might even change (currently consider this as experimental) * * @author abhinavsingh * */ class JAXLPipe { protected $perm = 0600; protected $recv_cb = null; protected $fd = null; protected $client = null; public $name = null; public function __construct($name, $read_cb=null) { $pipes_folder = JAXL_CWD.'/.jaxl/pipes'; - if(!is_dir($pipes_folder)) mkdir($pipes_folder); + if (!is_dir($pipes_folder)) mkdir($pipes_folder); $this->ev = new JAXLEvent(); $this->name = $name; $this->read_cb = $read_cb; $pipe_path = $this->get_pipe_file_path(); - if(!file_exists($pipe_path)) { + if (!file_exists($pipe_path)) { posix_mkfifo($pipe_path, $this->perm); $this->fd = fopen($pipe_path, 'r+'); - if(!$this->fd) { + if (!$this->fd) { _error("unable to open pipe"); } else { _debug("pipe opened using path $pipe_path"); _notice("Usage: $ echo 'Hello World!' > $pipe_path"); $this->client = new JAXLSocketClient(); $this->client->connect($this->fd); $this->client->set_callback(array(&$this, 'on_data')); } } else { _error("pipe with name $name already exists"); } } public function __destruct() { @fclose($this->fd); @unlink($this->get_pipe_file_path()); _debug("unlinking pipe file"); } public function get_pipe_file_path() { return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe'; } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function on_data($data) { // callback - if($this->recv_cb) call_user_func($this->recv_cb, $data); + if ($this->recv_cb) call_user_func($this->recv_cb, $data); } } diff --git a/core/jaxl_sock5.php b/core/jaxl_sock5.php index 97e3b0b..93a4f45 100644 --- a/core/jaxl_sock5.php +++ b/core/jaxl_sock5.php @@ -1,125 +1,125 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ class JAXLSock5 { private $client = null; protected $transport = null; protected $ip = null; protected $port = null; public function __construct($transport='tcp') { $this->transport = $transport; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } public function __destruct() { } public function connect($ip, $port=1080) { $this->ip = $ip; $this->port = $port; $sock_path = $this->_sock_path(); - if($this->client->connect($sock_path)) { + if ($this->client->connect($sock_path)) { _debug("established connection to $sock_path"); return true; } else { _error("unable to connect $sock_path"); return false; } } // // Three phases of SOCK5 // // Negotiation pkt consists of 3 part: // 0x05 => Sock protocol version // 0x01 => Number of method identifier octet // // Following auth methods are defined: // 0x00 => No authentication required // 0x01 => GSSAPI // 0x02 => USERNAME/PASSWORD // 0x03 to 0x7F => IANA ASSIGNED // 0x80 to 0xFE => RESERVED FOR PRIVATE METHODS // 0xFF => NO ACCEPTABLE METHODS public function negotiate() { $pkt = pack("C3", 0x05, 0x01, 0x00); $this->client->send($pkt); // enter sub-negotiation state } public function relay_request() { // enter wait for reply state } public function send_data() { } // // Socket client callback // public function on_response($raw) { _debug($raw); } // // Private // protected function _sock_path() { return $this->transport.'://'.$this->ip.':'.$this->port; } } diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index 2ad366f..8185e13 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,216 +1,216 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; public function __construct($stream_context=null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ public function connect($socket_path) { - if(gettype($socket_path) == "string") { + if (gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); - if(sizeof($path_parts) == 3) $this->port = $path_parts[2]; + if (sizeof($path_parts) == 3) $this->port = $path_parts[2]; _info("trying ".$socket_path); - if($this->stream_context) $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); + if ($this->stream_context) $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); else $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); } else { $this->fd = &$socket_path; } - if($this->fd) { + if ($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); $this->disconnect(); return false; } } public function disconnect() { JAXLLoop::unwatch($this->fd, array( 'read' => true, 'write' => true )); @fclose($this->fd); $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); - if($ret == false) { + if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); - if($ret == false) { + if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); - if($ret == false) { + if ($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); return $ret; } public function send($data) { $this->obuffer .= $data; // add watch for write events - if($this->writing) return; + if ($this->writing) return; JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); - if($bytes === 0) { + if ($bytes === 0) { $meta = stream_get_meta_data($fd); - if($meta['eof'] === TRUE) { + if ($meta['eof'] === TRUE) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); - if($bytes > 0) _debug($raw); + if ($bytes > 0) _debug($raw); // callback - if($this->recv_cb) call_user_func($this->recv_cb, $raw); + if ($this->recv_cb) call_user_func($this->recv_cb, $raw); } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty - if(strlen($this->obuffer) === 0) { + if (strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } } diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index c2497ab..6aef718 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,255 +1,255 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLSocketServer { public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; public function __construct($path, $accept_cb, $request_cb) { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; $ctx = stream_context_create(array('socket'=>array('backlog'=>$this->backlog))); - if(($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { - if(@stream_set_blocking($this->fd, $this->blocking)) { + if (($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { + if (@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); } else { _error("unable to set non block flag"); } } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } public function __destruct() { _info("shutting down socket server"); } public function read($client_id) { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } public function send($client_id, $data) { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } public function close($client_id) { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } public function on_server_accept_ready($server) { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); - if(!$client) { + if (!$client) { _error("unable to accept new client conn"); return; } - if(@stream_set_blocking($client, $this->blocking)) { + if (@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do - if($this->accept_cb) { + if ($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); } // if no accept callback is registered // close the accepted connection else { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } } else { _error("unable to set non block flag"); } } public function on_client_read_ready($client) { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); - if($bytes === 0) { + if ($bytes === 0) { $meta = stream_get_meta_data($client); - if($meta['eof'] === TRUE) { + if ($meta['eof'] === TRUE) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); @fclose($client); unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; - if($this->request_cb) + if ($this->request_cb) call_user_func($this->request_cb, $client_id, $total); $this->clients[$client_id]['ibuffer'] = ''; } public function on_client_write_ready($client) { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); - if($written === false) { + if ($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; } - else if($written == strlen($total) || $written == $this->send_chunk_size) { + else if ($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler - if(strlen($this->clients[$client_id]['obuffer']) === 0) { + if (strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up - if($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { + if ($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } } catch(JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // protected function add_read_cb($client_id) { - if($this->clients[$client_id]['reading']) + if ($this->clients[$client_id]['reading']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } protected function add_write_cb($client_id) { - if($this->clients[$client_id]['writing']) + if ($this->clients[$client_id]['writing']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } protected function del_read_cb($client_id) { - if(!$this->clients[$client_id]['reading']) + if (!$this->clients[$client_id]['reading']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } protected function del_write_cb($client_id) { - if(!$this->clients[$client_id]['writing']) + if (!$this->clients[$client_id]['writing']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } } diff --git a/core/jaxl_util.php b/core/jaxl_util.php index f0fff8f..5437608 100644 --- a/core/jaxl_util.php +++ b/core/jaxl_util.php @@ -1,64 +1,64 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh * */ class JAXLUtil { public static function get_nonce($binary=true) { $nce = ''; mt_srand((double) microtime()*10000000); for($i=0; $i<32; $i++) $nce .= chr(mt_rand(0, 255)); return $binary ? $nce : base64_encode($nce); } public static function get_dns_srv($domain) { $rec = dns_get_record("_xmpp-client._tcp.".$domain, DNS_SRV); - if(is_array($rec)) { - if(sizeof($rec) == 0) return array($domain, 5222); - if(sizeof($rec) > 0) return array($rec[0]['target'], $rec[0]['port']); + if (is_array($rec)) { + if (sizeof($rec) == 0) return array($domain, 5222); + if (sizeof($rec) > 0) return array($rec[0]['target'], $rec[0]['port']); } } public static function pbkdf2($data, $secret, $iteration, $dkLen=32, $algo='sha1') { return ''; } } diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index 687d596..e63fef7 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,196 +1,196 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: - if(is_array($argv[1])) { + if (is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; - if(is_array($argv[2])) { + if (is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: - if(is_array($argv[1])) { + if (is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; foreach($attrs as $k=>$v) { - if($this->attrs[$k] !== $v) { + if ($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } public function t($text, $append=FALSE) { - if(!$append) { + if (!$append) { $this->rover->text = $text; } else { - if($this->rover->text === null) + if ($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; } return $this; } public function c($name, $ns=null, $attrs=array(), $text=null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { - if($this->rover->parent) $this->rover = &$this->rover->parent; + if ($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } public function top() { $this->rover = &$this; return $this; } public function exists($name, $ns=null, $attrs=array()) { foreach($this->childrens as $child) { - if($ns) { - if($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) + if ($ns) { + if ($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; } - else if($child->name == $name && $child->match_attrs($attrs)) { + else if ($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } public function update($name, $ns=null, $attrs=array(), $text=null) { foreach($this->childrens as $k=>$child) { - if($child->name == $name) { + if ($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } public function to_string($parent_ns=null) { $xml = ''; $xml .= '<'.$this->name; - if($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; - foreach($this->attrs as $k=>$v) if(!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; + if ($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; + foreach($this->attrs as $k=>$v) if (!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; foreach($this->childrens as $child) $xml .= $child->to_string($this->ns); - if($this->text) $xml .= htmlspecialchars($this->text); + if ($this->text) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } } diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php index 01d4a84..adca378 100644 --- a/core/jaxl_xml_stream.php +++ b/core/jaxl_xml_stream.php @@ -1,188 +1,188 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Enter description here ... * @author abhinavsingh * */ class JAXLXmlStream { private $delimiter = '\\'; private $ns; private $parser; private $stanza; private $depth = -1; private $start_cb; private $stanza_cb; private $end_cb; public function __construct() { $this->init_parser(); } private function init_parser() { $this->depth = -1; $this->parser = xml_parser_create_ns("UTF-8", $this->delimiter); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); xml_set_character_data_handler($this->parser, array(&$this, "handle_character")); xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag")); } public function __destruct() { //_debug("cleaning up xml parser..."); @xml_parser_free($this->parser); } public function reset_parser() { $this->parse_final(null); @xml_parser_free($this->parser); $this->parser = null; $this->init_parser(); } public function set_callback($start_cb, $end_cb, $stanza_cb) { $this->start_cb = $start_cb; $this->end_cb = $end_cb; $this->stanza_cb = $stanza_cb; } public function parse($str) { xml_parse($this->parser, $str, false); } public function parse_final($str) { xml_parse($this->parser, $str, true); } protected function handle_start_tag($parser, $name, $attrs) { $name = $this->explode($name); //echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL; // replace ns with prefix foreach($attrs as $key=>$v) { $k = $this->explode($key); // no ns specified - if($k[0] == null) { + if ($k[0] == null) { $attrs[$k[1]] = $v; } // xml ns - else if($k[0] == NS_XML) { + else if ($k[0] == NS_XML) { unset($attrs[$key]); $attrs['xml:'.$k[1]] = $v; } else { _error("==================> unhandled ns prefix on attribute"); // remove attribute else will cause error with bad stanza format // report to developer if above error message is ever encountered unset($attrs[$key]); } } - if($this->depth <= 0) { + if ($this->depth <= 0) { $this->depth = 0; $this->ns = $name[1]; - if($this->start_cb) { + if ($this->start_cb) { $stanza = new JAXLXml($name[1], $name[0], $attrs); call_user_func($this->start_cb, $stanza); } } else { - if(!$this->stanza) { + if (!$this->stanza) { $stanza = new JAXLXml($name[1], $name[0], $attrs); $this->stanza = &$stanza; } else { $this->stanza->c($name[1], $name[0], $attrs); } } ++$this->depth; } protected function handle_end_tag($parser, $name) { $name = explode($this->delimiter, $name); $name = sizeof($name) == 1 ? array('', $name[0]) : $name; //echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL; - if($this->depth == 1) { - if($this->end_cb) { + if ($this->depth == 1) { + if ($this->end_cb) { $stanza = new JAXLXml($name[1], $this->ns); call_user_func($this->end_cb, $stanza); } } - else if($this->depth > 1) { - if($this->stanza) $this->stanza->up(); + else if ($this->depth > 1) { + if ($this->stanza) $this->stanza->up(); - if($this->depth == 2) { - if($this->stanza_cb) { + if ($this->depth == 2) { + if ($this->stanza_cb) { call_user_func($this->stanza_cb, $this->stanza); $this->stanza = null; } } } --$this->depth; } protected function handle_character($parser, $data) { //echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL; - if($this->stanza) { + if ($this->stanza) { $this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), TRUE); } } private function implode($data) { return implode($this->delimiter, $data); } private function explode($data) { $data = explode($this->delimiter, $data); $data = sizeof($data) == 1 ? array(null, $data[0]) : $data; return $data; } } diff --git a/docs/users/http_examples.rst b/docs/users/http_examples.rst index 3bcf121..f4af5f1 100644 --- a/docs/users/http_examples.rst +++ b/docs/users/http_examples.rst @@ -1,102 +1,102 @@ HTTP Examples ============= Writing HTTP Server ------------------- Intialize an ``HTTPServer`` instance .. code-block:: ruby require_once 'jaxl.php'; require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this. Define a callback method that will accept all incoming ``HTTPRequest`` objects .. code-block:: ruby function on_request($request) { - if($request->method == 'GET') { + if ($request->method == 'GET') { $body = json_encode($request); $request->ok($body, array('Content-Type'=>'application:json')); } else { $request->not_found(); } } ``on_request`` callback method will receive a ``HTTPRequest`` object instance. For this example, we will simply echo back json encoded ``$request`` object for every http GET request. Start http server: .. code-block:: ruby $http->start('on_request'); We pass ``on_request`` method as first parameter to ``HTTPServer::start/1``. If nothing is passed, requests will fail with a default 404 not found error message Writing REST API Server ----------------------- Intialize an ``HTTPServer`` instance .. code-block:: ruby require_once 'jaxl.php'; require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); By default ``HTTPServer`` will listen on port 9699. You can pass a port number as first parameter to change this. Define our REST resources callback methods: .. code-block:: ruby function index($request) { $request->send_response( 200, array('Content-Type'=>'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } function upload($request) { - if($request->method == 'GET') { + if ($request->method == 'GET') { $request->send_response( 200, array('Content-Type'=>'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action=""><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' ); } - else if($request->method == 'POST') { - if($request->body === null && $request->expect) { + else if ($request->method == 'POST') { + if ($request->body === null && $request->expect) { $request->recv_body(); } else { // got upload body, save it _debug("file upload complete, got ".strlen($request->body)." bytes of data"); $request->close(); } } } Next we need to register dispatch rules for our callbacks above: .. code-block:: ruby $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); $rules = array($index, $upload); $http->dispatch($rules); Start REST api server: .. code-block:: ruby $http->start(); Make an HTTP request -------------------- diff --git a/examples/curl.php b/examples/curl.php index c0c3570..45c1ceb 100644 --- a/examples/curl.php +++ b/examples/curl.php @@ -1,49 +1,49 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -if($argc < 2) { +if ($argc < 2) { echo "Usage: $argv[0] url\n"; exit; } require_once 'jaxl.php'; JAXLLogger::$level = JAXL_DEBUG; require_once JAXL_CWD.'/http/http_client.php'; $request = new HTTPClient($argv[1]); $request->start(); diff --git a/examples/echo_bosh_bot.php b/examples/echo_bosh_bot.php index 4cd4c86..cf0b58d 100644 --- a/examples/echo_bosh_bot.php +++ b/examples/echo_bosh_bot.php @@ -1,106 +1,106 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -if($argc < 3) { +if ($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // (required) 'bosh_url' => 'http://localhost:5280/http-bind', // (optional) srv lookup is done if not provided // for bosh client 'host' value is used for 'route' attribute //'host' => 'xmpp.domain.tld', // (optional) result from srv lookup used by default // for bosh client 'port' value is used for 'route' attribute //'port' => 5222, // (optional) //'resource' => 'resource', // (optional) defaults to PLAIN if supported, else other methods will be automatically tried 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN', 'log_level' => JAXL_INFO )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); $client->set_status("available!", "dnd", 10); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/echo_bot.php b/examples/echo_bot.php index a2c4a09..39ed641 100644 --- a/examples/echo_bot.php +++ b/examples/echo_bot.php @@ -1,147 +1,147 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // Run as: // php examples/echo_bot.php root@localhost password // php examples/echo_bot.php root@localhost password DIGEST-MD5 // php examples/echo_bot.php localhost "" ANONYMOUS -if($argc < 3) { +if ($argc < 3) { echo "Usage: $argv[0] jid pass auth_type\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // (optional) srv lookup is done if not provided //'host' => 'xmpp.domain.tld', // (optional) result from srv lookup used by default //'port' => 5222, // (optional) defaults to false //'force_tls' => true, // (optional) //'resource' => 'resource', // (optional) defaults to PLAIN if supported, else other methods will be automatically tried 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN', 'log_level' => JAXL_INFO )); // // required XEP's // $client->require_xep(array( '0199' // XMPP Ping )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // fetch roster list $client->get_roster(); // fetch vcard $client->get_vcard(); // set status $client->set_status("available!", "dnd", 10); }); // by default JAXL instance catches incoming roster list results and updates // roster list is parsed/cached and an event 'on_roster_update' is emitted $client->add_cb('on_roster_update', function() { //global $client; //print_r($client->roster); }); $client->add_cb('on_auth_failure', function($reason) { global $client; _info("got on_auth_failure cb with reason $reason"); $client->send_end_stream(); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming chat message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_presence_stanza', function($stanza) { global $client; $type = ($stanza->type ? $stanza->type : "available"); $show = ($stanza->show ? $stanza->show : "???"); _info($stanza->from." is now ".$type." ($show)"); - if($type == "available") { + if ($type == "available") { // fetch vcard $client->get_vcard($stanza->from); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(array( '--with-debug-shell' => true, '--with-unix-sock' => true )); echo "done\n"; diff --git a/examples/echo_component_bot.php b/examples/echo_component_bot.php index a42f9d6..b7bf013 100644 --- a/examples/echo_component_bot.php +++ b/examples/echo_component_bot.php @@ -1,98 +1,98 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -if($argc != 5) { +if ($argc != 5) { echo "Usage: $argv[0] jid pass host port\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $comp = new JAXL(array( // (required) component host and secret 'jid' => $argv[1], 'pass' => $argv[2], // (required) 'host' => @$argv[3], 'port' => $argv[4], 'log_level' => JAXL_INFO )); // // XEP's required (required) // $comp->require_xep(array( '0114' // jabber component protocol )); // // add necessary event callbacks here // $comp->add_cb('on_auth_success', function() { _info("got on_auth_success cb"); }); $comp->add_cb('on_auth_failure', function($reason) { global $comp; $comp->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $comp->add_cb('on_chat_message', function($stanza) { global $comp; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $comp->jid->to_string(); $comp->send($stanza); }); $comp->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $comp->start(); echo "done\n"; diff --git a/examples/echo_unix_sock_server.php b/examples/echo_unix_sock_server.php index 22990be..0b939a5 100644 --- a/examples/echo_unix_sock_server.php +++ b/examples/echo_unix_sock_server.php @@ -1,59 +1,59 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -if($argc < 2) { +if ($argc < 2) { echo "Usage: $argv[0] /path/to/server.sock\n"; exit; } require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; $server = null; function on_request($client, $raw) { global $server; $server->send($client, $raw); _info("got client callback ".$raw); } @unlink($argv[1]); $server = new JAXLSocketServer('unix://'.$argv[1], NULL, 'on_request'); JAXLLoop::run(); echo "done\n"; diff --git a/examples/http_bind.php b/examples/http_bind.php index 4a53527..d75ade8 100644 --- a/examples/http_bind.php +++ b/examples/http_bind.php @@ -1,64 +1,64 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -if(!isset($_GET['jid']) || !isset($_GET['pass'])) { +if (!isset($_GET['jid']) || !isset($_GET['pass'])) { echo "invalid input"; exit; } // // initialize JAXL object with initial config // require_once '../jaxl.php'; $client = new JAXL(array( 'jid' => $_GET['jid'], 'pass' => $_GET['pass'], 'bosh_url' => 'http://localhost:5280/http-bind', 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php index be1677a..acaea62 100644 --- a/examples/http_pre_bind.php +++ b/examples/http_pre_bind.php @@ -1,89 +1,89 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // http pre bind php script $body = file_get_contents("php://input"); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); -if(!@$attrs['to'] && !@$attrs['rid'] && !@$attrs['wait'] && !@$attrs['hold']) { +if (!@$attrs['to'] && !@$attrs['rid'] && !@$attrs['wait'] && !@$attrs['hold']) { echo "invalid input"; exit; } // // initialize JAXL object with initial config // require_once '../jaxl.php'; $to = (string)$attrs['to']; $rid = (int)$attrs['rid']; $wait = (int)$attrs['wait']; $hold = (int)$attrs['hold']; list($host, $port) = JAXLUtil::get_dns_srv($to); $client = new JAXL(array( 'domain' => $to, 'host' => $host, 'port' => $port, 'bosh_url' => 'http://localhost:5280/http-bind', 'bosh_rid' => $rid, 'bosh_wait' => $wait, 'bosh_hold' => $hold, 'auth_type' => 'ANONYMOUS', 'log_level' => JAXL_INFO )); $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); echo '<body xmlns="'.NS_HTTP_BIND.'" sid="'.$client->xeps['0206']->sid.'" rid="'.$client->xeps['0206']->rid.'" jid="'.$client->full_jid->to_string().'"/>'; exit; }); $client->add_cb('on_auth_failure', function($reason) { global $client; _info("got on_auth_failure cb with reason $reason"); $client->send_end_stream(); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/http_rest_server.php b/examples/http_rest_server.php index ab7155a..1adfae8 100644 --- a/examples/http_rest_server.php +++ b/examples/http_rest_server.php @@ -1,117 +1,117 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // print usage notice and parse addr/port parameters if passed _colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE); $port = ($argc == 2 ? $argv[1] : 9699); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer($port); // callback method for dispatch rule (see below) function index($request) { $request->send_response( 200, array('Content-Type'=>'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } // callback method for dispatch rule (see below) function upload($request) { - if($request->method == 'GET') { + if ($request->method == 'GET') { $request->ok(array( 'Content-Type'=>'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' ); } - else if($request->method == 'POST') { - if($request->body === null && $request->expect) { + else if ($request->method == 'POST') { + if ($request->body === null && $request->expect) { $request->recv_body(); } else { // got upload body, save it _info("file upload complete, got ".strlen($request->body)." bytes of data"); $upload_data = $request->multipart->form_data[0]['body']; $request->ok($upload_data, array('Content-Type'=>$request->multipart->form_data[0]['headers']['Content-Type'])); } } } // add dispatch rules with callback method as first argument $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); // some REST CRUD style callback methods // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules function create_event($request) { _info("got event create request"); $request->close(); } function read_event($request, $pk) { _info("got event read request for $pk"); $request->close(); } function update_event($request, $pk) { _info("got event update request for $pk"); $request->close(); } function delete_event($request, $pk) { _info("got event delete request for $pk"); $request->close(); } $event_create = array('create_event', '^/event/create/$', array('PUT')); $event_read = array('read_event', '^/event/(?P<pk>\d+)/$', array('GET', 'HEAD')); $event_update = array('update_event', '^/event/(?P<pk>\d+)/$', array('POST')); $event_delete = array('delete_event', '^/event/(?P<pk>\d+)/$', array('DELETE')); // prepare rule set $rules = array($index, $upload, $event_create, $event_read, $event_update, $event_delete); $http->dispatch($rules); // start http server $http->start(); diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index 3ec9dbe..d19eabf 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,144 +1,144 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -if($argc < 5) { +if ($argc < 5) { echo "Usage: $argv[0] host jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[2], 'pass' => $argv[3], 'host' => $argv[1], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC '0203', // Delayed Delivery '0199' // XMPP Ping )); // // add necessary event callbacks here // $_room_full_jid = $argv[4]."/".$argv[5]; $room_full_jid = new XMPPJid($_room_full_jid); $client->add_cb('on_auth_success', function() { global $client, $room_full_jid; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // join muc room $client->xeps['0045']->join_room($room_full_jid); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_groupchat_message', function($stanza) { global $client; $from = new XMPPJid($stanza->from); $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); - if($from->resource) { + if ($from->resource) { echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } else { $subject = $stanza->exists('subject'); - if($subject) { + if ($subject) { echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } } }); $client->add_cb('on_presence_stanza', function($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster - if(strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { - if(($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { - if(($status = $x->exists('status', null, array('code'=>'110'))) !== false) { + if (strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { + if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { + if (($status = $x->exists('status', null, array('code'=>'110'))) !== false) { $item = $x->exists('item'); _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); } else { _info("xmlns #user have no x child element"); } } else { _warning("=======> odd case 1"); } } // stanza from other users received - else if(strtolower($from->bare) == strtolower($room_full_jid->bare)) { - if(($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { + else if (strtolower($from->bare) == strtolower($room_full_jid->bare)) { + if (($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; } else { _warning("=======> odd case 2"); } } else { _warning("=======> odd case 3"); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/multi_client.php b/examples/multi_client.php index 1b14aeb..cd150c2 100644 --- a/examples/multi_client.php +++ b/examples/multi_client.php @@ -1,127 +1,127 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // enable multi client support // this will force 1st parameter of callbacks // as connected client instance define('JAXL_MULTI_CLIENT', true); // input multiple account credentials $accounts = array(); $add_new = TRUE; while($add_new) { $jid = readline('Enter Jabber Id: '); $pass = readline('Enter Password: '); $accounts[] = array($jid, $pass); $next = readline('Add another account (y/n): '); $add_new = $next == 'y' ? TRUE : FALSE; } // setup jaxl require_once 'jaxl.php'; // // common callbacks // function on_auth_success($client) { _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // fetch roster list $client->get_roster(); // fetch vcard $client->get_vcard(); // set status $client->set_status("available!", "dnd", 10); } function on_auth_failure($client, $reason) { _info("got on_auth_failure cb with reason $reason"); $client->send_end_stream(); } function on_chat_message($client, $stanza) { // echo back incoming chat message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); } function on_presence_stanza($client, $stanza) { global $client; $type = ($stanza->type ? $stanza->type : "available"); $show = ($stanza->show ? $stanza->show : "???"); _info($stanza->from." is now ".$type." ($show)"); - if($type == "available") { + if ($type == "available") { // fetch vcard $client->get_vcard($stanza->from); } } function on_disconnect($client) { _info("got on_disconnect cb"); } // // bootstrap all account instances // foreach($accounts as $account) { $client = new JAXL(array( 'jid' => $account[0], 'pass' => $account[1], 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', 'on_auth_success'); $client->add_cb('on_auth_failure', 'on_auth_failure'); $client->add_cb('on_chat_message', 'on_chat_message'); $client->add_cb('on_presence_stanza', 'on_presence_stanza'); $client->add_cb('on_disconnect', 'on_disconnect'); $client->connect($client->get_socket_path()); $client->start_stream(); } // start core loop JAXLLoop::run(); echo "done\n"; diff --git a/examples/publisher.php b/examples/publisher.php index 8adbd91..e4f7f11 100644 --- a/examples/publisher.php +++ b/examples/publisher.php @@ -1,97 +1,97 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -if($argc < 3) { +if ($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // create node //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); // publish $item = new JAXLXml('item', null, array('id'=>time())); $item->c('entry', 'http://www.w3.org/2005/Atom'); $item->c('title')->t('Soliloquy')->up(); $item->c('summary')->t('To be, or not to be: that is the question')->up(); $item->c('link', null, array('rel'=>'alternate', 'type'=>'text/html', 'href'=>'http://denmark.lit/2003/12/13/atom03'))->up(); $item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up(); $item->c('published')->t('2003-12-13T18:30:02Z')->up(); $item->c('updated')->t('2003-12-13T18:30:02Z')->up(); $client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/register_user.php b/examples/register_user.php index c79546d..6c9c03f 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,167 +1,167 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -if($argc < 2) { +if ($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // $form = array(); function wait_for_register_response($event, $args) { global $client, $form; - if($event == 'stanza_cb') { + if ($event == 'stanza_cb') { $stanza = $args[0]; - if($stanza->name == 'iq') { + if ($stanza->name == 'iq') { $form['type'] = $stanza->attrs['type']; - if($stanza->attrs['type'] == 'result') { + if ($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } - else if($stanza->attrs['type'] == 'error') { + else if ($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } } } else { _notice("unhandled event $event rcvd"); } } function wait_for_register_form($event, $args) { global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); - if($query) { + if ($query) { $instructions = $query->exists('instructions'); - if($instructions) { + if ($instructions) { echo $instructions->text.PHP_EOL; } foreach($query->childrens as $k=>$child) { - if($child->name != 'instructions') { + if ($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // $client->add_cb('on_stream_features', function($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; }); $client->add_cb('on_disconnect', function() { global $form; _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); }); // // finally start configured xmpp stream // $client->start(); // // if registration was successful // try to connect with newly registered account // -if($form['type'] == 'result') { +if ($form['type'] == 'result') { _info("connecting newly registered user account"); $client = new JAXL(array( 'jid' => $form['username'].'@'.$argv[1], 'pass' => $form['password'], 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', function() { global $client; $client->set_status('Available'); }); $client->start(); } echo "done\n"; diff --git a/examples/subscriber.php b/examples/subscriber.php index 8ebf293..3a21966 100644 --- a/examples/subscriber.php +++ b/examples/subscriber.php @@ -1,97 +1,97 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -if($argc < 3) { +if ($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // create node //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); // subscribe $client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node'); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_headline_message', function($stanza) { global $client; - if(($event = $stanza->exists('event', NS_PUBSUB.'#event'))) { + if (($event = $stanza->exists('event', NS_PUBSUB.'#event'))) { _info("got pubsub event"); } else { _warning("unknown headline message rcvd"); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/xfacebook_platform_client.php b/examples/xfacebook_platform_client.php index e9b0f19..00c5ce9 100644 --- a/examples/xfacebook_platform_client.php +++ b/examples/xfacebook_platform_client.php @@ -1,98 +1,98 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -if($argc != 4) { +if ($argc != 4) { echo "Usage: $argv[0] fb_user_id_or_username fb_app_key fb_access_token\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1].'@chat.facebook.com', 'fb_app_key' => $argv[2], 'fb_access_token' => $argv[3], // force tls (facebook require this now) 'force_tls' => true, // (required) force facebook oauth 'auth_type' => 'X-FACEBOOK-PLATFORM', // (optional) //'resource' => 'resource', 'log_level' => JAXL_INFO )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); $client->set_status("available!", "dnd", 10); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/examples/xmpp_rest.php b/examples/xmpp_rest.php index 9cab9b3..18cdcb4 100644 --- a/examples/xmpp_rest.php +++ b/examples/xmpp_rest.php @@ -1,75 +1,75 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // View explanation for this example here: // https://groups.google.com/d/msg/jaxl/QaGjZP4A2gY/n6SYutrBVxsJ -if($argc < 3) { +if ($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // initialize xmpp client require_once 'jaxl.php'; $xmpp = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); // register callbacks on required xmpp events $xmpp->add_cb('on_auth_success', function() { global $xmpp; _info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string()); }); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); // add generic callback // you can also dispatch REST style callback // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules $http->cb = function($request) { // For demo purposes we simply return xmpp client full jid global $xmpp; $request->ok($xmpp->full_jid->to_string()); }; // This will start main JAXLLoop, // hence we don't need to call $http->start() explicitly $xmpp->start(); diff --git a/examples/xoauth2_gtalk_client.php b/examples/xoauth2_gtalk_client.php index 6b2c108..81e90b5 100644 --- a/examples/xoauth2_gtalk_client.php +++ b/examples/xoauth2_gtalk_client.php @@ -1,97 +1,97 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -if($argc != 3) { +if ($argc != 3) { echo "Usage: $argv[0] jid access_token\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // force tls 'force_tls' => true, // (required) perform X-OAUTH2 'auth_type' => 'X-OAUTH2', // (optional) //'resource' => 'resource', 'log_level' => JAXL_DEBUG )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); $client->set_status("available!", "dnd", 10); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; diff --git a/http/http_client.php b/http/http_client.php index 5ec2c31..d04576c 100644 --- a/http/http_client.php +++ b/http/http_client.php @@ -1,135 +1,135 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ class HTTPClient { private $url = null; private $parts = array(); private $headers = array(); private $data = null; public $method = null; private $client = null; public function __construct($url, $headers=array(), $data=null) { $this->url = $url; $this->headers = $headers; $this->data = $data; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } public function start($method='GET') { $this->method = $method; $this->parts = parse_url($this->url); $transport = $this->_transport(); $ip = $this->_ip(); $port = $this->_port(); $socket_path = $transport.'://'.$ip.':'.$port; - if($this->client->connect($socket_path)) { + if ($this->client->connect($socket_path)) { _debug("connection to $this->url established"); // send request data $this->send_request(); // start main loop JAXLLoop::run(); } else { _debug("unable to open $this->url"); } } public function on_response($raw) { _info("got http response"); } protected function send_request() { $this->client->send($this->_line()."\r\n"); $this->client->send($this->_ua()."\r\n"); $this->client->send($this->_host()."\r\n"); $this->client->send("\r\n"); } // // private methods on uri parts // private function _line() { return $this->method.' '.$this->_uri().' HTTP/1.1'; } private function _ua() { return 'User-Agent: jaxl_http_client/3.x'; } private function _host() { return 'Host: '.$this->parts['host'].':'.$this->_port(); } private function _transport() { return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl'); } private function _ip() { return gethostbyname($this->parts['host']); } private function _port() { return @$this->parts['port'] ? $this->parts['port'] : 80; } private function _uri() { $uri = $this->parts['path']; - if(@$this->parts['query']) $uri .= '?'.$this->parts['query']; - if(@$this->parts['fragment']) $uri .= '#'.$this->parts['fragment']; + if (@$this->parts['query']) $uri .= '?'.$this->parts['query']; + if (@$this->parts['fragment']) $uri .= '#'.$this->parts['fragment']; return $uri; } } diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php index fccf563..9e4f325 100644 --- a/http/http_dispatcher.php +++ b/http/http_dispatcher.php @@ -1,117 +1,117 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // // (optionally) set an array of url dispatch rules // each dispatch rule is defined by an array of size 4 like: // array($callback, $pattern, $methods, $extra), where // $callback the method which will be called if this rule matches // $pattern regular expression to match request path // $methods list of allowed methods for this rule // pass boolean true to allow all http methods // if omitted or an empty array() is passed (which actually doesnt make sense) // by default 'GET' will be the method allowed on this rule // $extra reserved for future (you can totally omit this as of now) // class HTTPDispatchRule { // match callback public $cb = null; // regexp to match on request path public $pattern = null; // methods to match upon // add atleast 1 method for this rule to work public $methods = null; // other matching rules public $extra = array(); public function __construct($cb, $pattern, $methods=array('GET'), $extra=array()) { $this->cb = $cb; $this->pattern = $pattern; $this->methods = $methods; $this->extra = $extra; } public function match($path, $method) { - if(preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) { - if(in_array($method, $this->methods)) { + if (preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) { + if (in_array($method, $this->methods)) { return $matches; } } return false; } } class HTTPDispatcher { protected $rules = array(); public function __construct() { $this->rules = array(); } public function add_rule($rule) { $s = sizeof($rule); - if($s > 4) { _debug("invalid rule"); return; } + if ($s > 4) { _debug("invalid rule"); return; } // fill up defaults - if($s == 3) { $rule[] = array(); } - else if($s == 2) { $rule[] = array('GET'); $rule[] = array(); } + if ($s == 3) { $rule[] = array(); } + else if ($s == 2) { $rule[] = array('GET'); $rule[] = array(); } else { _debug("invalid rule"); return; } $this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]); } public function dispatch($request) { foreach($this->rules as $rule) { //_debug("matching $request->path with pattern $rule->pattern"); - if(($matches = $rule->match($request->path, $request->method)) !== false) { + if (($matches = $rule->match($request->path, $request->method)) !== false) { _debug("matching rule found, dispatching"); $params = array($request); // TODO: a bad way to restrict on 'pk', fix me for generalization - if(@isset($matches['pk'])) $params[] = $matches['pk']; + if (@isset($matches['pk'])) $params[] = $matches['pk']; call_user_func_array($rule->cb, $params); return true; } } return false; } } diff --git a/http/http_multipart.php b/http/http_multipart.php index 6624c9a..ebe4444 100644 --- a/http/http_multipart.php +++ b/http/http_multipart.php @@ -1,173 +1,173 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; class HTTPMultiPart extends JAXLFsm { public $boundary = null; public $form_data = array(); public $index = -1; public function handle_invalid_state($r) { _error("got invalid event $r"); } public function __construct($boundary) { $this->boundary = $boundary; parent::__construct('wait_for_boundary_start'); } public function state() { return $this->state; } public function wait_for_boundary_start($event, $data) { - if($event == 'process') { - if($data[0] == '--'.$this->boundary) { + if ($event == 'process') { + if ($data[0] == '--'.$this->boundary) { $this->index += 1; $this->form_data[$this->index] = array( 'meta' => array(), 'headers' => array(), 'body' => '' ); return array('wait_for_content_disposition', true); } else { _warning("invalid boundary start $data[0] while expecting $this->boundary"); return array('wait_for_boundary_start', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_boundary_start', false); } } public function wait_for_content_disposition($event, $data) { - if($event == 'process') { + if ($event == 'process') { $disposition = explode(":", $data[0]); - if(strtolower(trim($disposition[0])) == 'content-disposition') { + if (strtolower(trim($disposition[0])) == 'content-disposition') { $this->form_data[$this->index]['headers'][$disposition[0]] = trim($disposition[1]); $meta = explode(";", $disposition[1]); - if(trim(array_shift($meta)) == 'form-data') { + if (trim(array_shift($meta)) == 'form-data') { foreach($meta as $k) { list($k, $v) = explode("=", $k); $this->form_data[$this->index]['meta'][$k] = $v; } return array('wait_for_content_type', true); } else { _warning("first part of meta is not form-data"); return array('wait_for_content_disposition', false); } } else { _warning("not a valid content-disposition line"); return array('wait_for_content_disposition', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_disposition', false); } } public function wait_for_content_type($event, $data) { - if($event == 'process') { + if ($event == 'process') { $type = explode(":", $data[0]); - if(strtolower(trim($type[0])) == 'content-type') { + if (strtolower(trim($type[0])) == 'content-type') { $this->form_data[$this->index]['headers'][$type[0]] = trim($type[1]); $this->form_data[$this->index]['meta']['type'] = $type[1]; return array('wait_for_content_body', true); } else { _debug("not a valid content-type line"); return array('wait_for_content_type', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_type', false); } } public function wait_for_content_body($event, $data) { - if($event == 'process') { - if($data[0] == '--'.$this->boundary) { + if ($event == 'process') { + if ($data[0] == '--'.$this->boundary) { _debug("start of new multipart/form-data detected"); return array('wait_for_content_disposition', true); } - else if($data[0] == '--'.$this->boundary.'--') { + else if ($data[0] == '--'.$this->boundary.'--') { _debug("end of multipart form data detected"); return array('wait_for_empty_line', true); } else { $this->form_data[$this->index]['body'] .= $data[0]; return array('wait_for_content_body', true); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_body', false); } } public function wait_for_empty_line($event, $data) { - if($event == 'process') { - if($data[0] == '') { + if ($event == 'process') { + if ($data[0] == '') { return array('done', true); } else { _warning("invalid empty line $data[0] received"); return array('wait_for_empty_line', false); } } else { _warning("got $event in done state with data $data[0]"); return array('wait_for_empty_line', false); } } public function done($event, $data) { _warning("got unhandled event $event with data $data[0]"); return array('done', false); } } diff --git a/http/http_request.php b/http/http_request.php index b57430f..a6fd0ce 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,488 +1,488 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers=array(), $body=null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; - if(sizeof($addr) == 2) { + if (sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation // public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; - if($this->body === null) $this->body = $rcvd; + if ($this->body === null) $this->body = $rcvd; else $this->body .= $rcvd; - if($this->multipart) { + if ($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach($form_data as $data) { //_debug("passing $data to multipart fsm"); - if(!$this->multipart->process($data)) { + if (!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } - if($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { + if ($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; - if(!$this->multipart->process($body)) { + if (!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } - if($this->recvd_body_len < $content_length) { + if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; - if(!$this->multipart->process('')) { + if (!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } - if($this->recvd_body_len < $content_length) { + if ($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { switch($event) { case 'empty_line': return 'headers_received'; break; default: - if(substr($event, 0, 5) == 'send_') { + if (substr($event, 0, 5) == 'send_') { $protected = '_'.$event; - if(method_exists($this, $protected)) { + if (method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } } - else if(@isset($this->shortcuts[$event])) { + else if (@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { $k = trim($k); $v = ltrim($v); // is expect header? - if(strtolower($k) == 'expect' && strtolower($v) == '100-continue') { + if (strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? - if(strtolower($k) == 'content-type') { + if (strtolower($k) == 'content-type') { $ctype = explode(';', $v); - if(sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { + if (sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); - if(strtolower(trim($boundary[0])) == 'boundary') { + if (strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required - if($this->expect) { + if ($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { - if(sizeof($args) == 0) { + if (sizeof($args) == 0) { $body = null; $headers = array(); } - if(sizeof($args) == 1) { + if (sizeof($args) == 1) { // http headers or body only received - if(is_array($args[0])) { + if (is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } } - else if(sizeof($args) == 2) { + else if (sizeof($args) == 2) { // body and http headers both received - if(is_array($args[0])) { + if (is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { foreach($headers as $k=>$v) $this->_send_header($k, $v); } protected function _send_body($body) { $this->_send($body); } protected function _send_response($code, $headers=array(), $body=null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set - if($body && !isset($headers['Content-Length'])) + if ($body && !isset($headers['Content-Length'])) $headers['Content-Length'] = strlen($body); // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); - if($body) + if ($body) $this->_send_body(HTTP_CRLF.$body); } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; - if(sizeof($resource) == 2) { + if (sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach($query as $q) { $q = explode("=", $q); - if(sizeof($q) == 1) $q[1] = ""; + if (sizeof($q) == 1) $q[1] = ""; $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } } diff --git a/http/http_server.php b/http/http_server.php index 1831364..32f7118 100644 --- a/http/http_server.php +++ b/http/http_server.php @@ -1,194 +1,194 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/http/http_dispatcher.php'; require_once JAXL_CWD.'/http/http_request.php'; // carriage return and line feed define('HTTP_CRLF', "\r\n"); // 1xx informational define('HTTP_100', "Continue"); define('HTTP_101', "Switching Protocols"); // 2xx success define('HTTP_200', "OK"); // 3xx redirection define('HTTP_301', 'Moved Permanently'); define('HTTP_304', 'Not Modified'); // 4xx client error define('HTTP_400', 'Bad Request'); define('HTTP_403', 'Forbidden'); define('HTTP_404', 'Not Found'); define('HTTP_405', 'Method Not Allowed'); define('HTTP_499', 'Client Closed Request'); // Nginx // 5xx server error define('HTTP_500', 'Internal Server Error'); define('HTTP_503', 'Service Unavailable'); class HTTPServer { private $server = null; public $cb = null; private $dispatcher = null; private $requests = array(); public function __construct($port=9699, $address="127.0.0.1") { $path = 'tcp://'.$address.':'.$port; $this->server = new JAXLSocketServer( $path, array(&$this, 'on_accept'), array(&$this, 'on_request') ); $this->dispatcher = new HTTPDispatcher(); } public function __destruct() { $this->server = null; } public function dispatch($rules) { foreach($rules as $rule) { $this->dispatcher->add_rule($rule); } } public function start($cb=null) { $this->cb = $cb; JAXLLoop::run(); } public function on_accept($sock, $addr) { _debug("on_accept for client#$sock, addr:$addr"); // initialize new request obj $request = new HTTPRequest($sock, $addr); // setup sock cb $request->set_sock_cb( array(&$this->server, 'send'), array(&$this->server, 'read'), array(&$this->server, 'close') ); // cache request object $this->requests[$sock] = &$request; // reactive client for further read $this->server->read($sock); } public function on_request($sock, $raw) { _debug("on_request for client#$sock"); $request = $this->requests[$sock]; // 'wait_for_body' state is reached when ever // application calls recv_body() method // on received $request object - if($request->state() == 'wait_for_body') { + if ($request->state() == 'wait_for_body') { $request->body($raw); } else { // break on crlf $lines = explode(HTTP_CRLF, $raw); // parse request line - if($request->state() == 'wait_for_request_line') { + if ($request->state() == 'wait_for_request_line') { list($method, $resource, $version) = explode(" ", $lines[0]); $request->line($method, $resource, $version); unset($lines[0]); _info($request->ip." ".$request->method." ".$request->resource." ".$request->version); } // parse headers foreach($lines as $line) { $line_parts = explode(":", $line); - if(sizeof($line_parts) > 1) { - if(strlen($line_parts[0]) > 0) { + if (sizeof($line_parts) > 1) { + if (strlen($line_parts[0]) > 0) { $k = $line_parts[0]; unset($line_parts[0]); $v = implode(":", $line_parts); $request->set_header($k, $v); } } - else if(strlen(trim($line_parts[0])) == 0) { + else if (strlen(trim($line_parts[0])) == 0) { $request->empty_line(); } // if exploded line array size is 1 // and thr is something in $line_parts[0] // must be request body else { $request->body($line); } } } // if request has reached 'headers_received' state? - if($request->state() == 'headers_received') { + if ($request->state() == 'headers_received') { // dispatch to any matching rule found _debug("delegating to dispatcher for further routing"); $dispatched = $this->dispatcher->dispatch($request); // if no dispatch rule matched call generic callback - if(!$dispatched && $this->cb) { + if (!$dispatched && $this->cb) { _debug("no dispatch rule matched, sending to generic callback"); call_user_func($this->cb, $request); } // else if not dispatched and not generic callbacked // send 404 not_found - else if(!$dispatched) { + else if (!$dispatched) { // TODO: send 404 if no callback is registered for this request _debug("dropping request since no matching dispatch rule or generic callback was specified"); $request->not_found('404 Not Found'); } } // if state is not 'headers_received' // reactivate client socket for read event else { $this->server->read($sock); } } } diff --git a/jaxl.php b/jaxl.php index 2453f6f..ff0fd39 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,806 +1,806 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger - if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; + if (isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; - if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; + if (isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; - if($strict) $this->add_exception_handlers(); + if ($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals - if(extension_loaded('pcntl')) { + if (extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; - if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); - if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); - if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); - if(!is_dir($this->log_dir)) mkdir($this->log_dir); - if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); + if (!is_dir($this->priv_dir)) mkdir($this->priv_dir); + if (!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); + if (!is_dir($this->pid_dir)) mkdir($this->pid_dir); + if (!is_dir($this->log_dir)) mkdir($this->log_dir); + if (!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file - if($this->mode == "cli") { + if ($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; - if((!$host || !$port) && $jid) { + if ((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 - if(@$this->cfg['bosh_url']) { + if (@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { - if(!is_array($xeps)) + if (!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); - if($jid) { + if ($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); - if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); + if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); - if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); + if ($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? - if(@$this->cfg['bosh_url']) { + if (@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode - if(!$this->ev->exists('on_connect')) + if (!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port - if($this->connect($this->get_socket_path())) { + if ($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts - if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); - if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); + if (@$opts['--with-debug-shell']) $this->enable_debug_shell(); + if (@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { - if($this->trans->errno == 61 + if ($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; - if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { + if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; - if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { + if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; - if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { + if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { - if($this->ev->exists('on_stream_features')) { + if ($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); - if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; + if ($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it - if($pref_auth_exists) { + if ($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available - if($mech == 'X-FACEBOOK-PLATFORM') { - if(@$this->cfg['fb_access_token']) { + if ($mech == 'X-FACEBOOK-PLATFORM') { + if (@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); - if($pref_auth == 'X-FACEBOOK-PLATFORM') { + if ($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } - else if($pref_auth == 'CRAM-MD5') { + else if ($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } - else if($pref_auth == 'SCRAM-SHA-1') { + else if ($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component - /*if(!@$this->xeps['0114']) { + /*if (!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; - if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { + if ($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list - if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { + if ($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { - if($child->name == 'item') { + if ($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { - if($group->name == 'group') { + if ($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above - if(!$emited) + if (!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results - if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { - if(@$this->roster[$stanza->from]) + if ($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { + if (@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on - if(!$emited) + if (!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza - if($this->manage_roster) { + if ($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); - if($type == 'available') { + if ($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } - else if($type == 'unavailable') { - if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) + else if ($type == 'unavailable') { + if (@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here - if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { + if ($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); - if($this->manage_subscribe == "mutual") + if ($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; - if($this->ev->exists($ev)) { + if ($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { - if($child->name == 'identity') { + if ($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } - else if($child->name == 'x') { + else if ($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } - else if($child->name == 'feature') { + else if ($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { - if($child->name == 'item') { + if ($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } diff --git a/jaxlctl b/jaxlctl index 6746360..ee2db17 100755 --- a/jaxlctl +++ b/jaxlctl @@ -1,187 +1,187 @@ #!/usr/bin/env php <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ $params = $argv; $exe = array_shift($params); $command = array_shift($params); require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // TODO: an abstract JAXLCtlCommand class // with seperate class per command // a mechanism to register new commands class JAXLCtl { protected $ipc = null; protected $buffer = ''; protected $buffer_cb = null; protected $cli = null; public $dots = "....... "; protected $symbols = array(); public function __construct($command, $params) { global $exe; - if(method_exists($this, $command)) { + if (method_exists($this, $command)) { $r = call_user_func_array(array(&$this, $command), $params); - if(sizeof($r) == 2) { + if (sizeof($r) == 2) { list($buffer_cb, $quit_cb) = $r; $this->buffer_cb = $buffer_cb; $this->cli = new JAXLCli(array(&$this, 'on_terminal_input'), $quit_cb); $this->run(); } else { _colorize("oops! internal command error", JAXL_ERROR); exit; } } else { _colorize("error: invalid command '$command' received", JAXL_ERROR); _colorize("type '$exe help' for list of available commands", JAXL_NOTICE); exit; } } public function run() { JAXLCli::prompt(); JAXLLoop::run(); } public function on_terminal_input($raw) { $raw = trim($raw); $last = substr($raw, -1, 1); - if($last == ";") { + if ($last == ";") { // dispatch to buffer callback call_user_func($this->buffer_cb, $this->buffer.$raw); $this->buffer = ''; } - else if($last == '\\') { + else if ($last == '\\') { $this->buffer .= substr($raw, 0, -1); echo $this->dots; } else { // buffer command $this->buffer .= $raw."; "; echo $this->dots; } } public static function print_help() { global $exe; _colorize("Usage: $exe command [options...]\n", JAXL_INFO); _colorize("Commands:", JAXL_NOTICE); _colorize(" help This help text", JAXL_DEBUG); _colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG); _colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG); echo "\n"; } protected function help() { JAXLCtl::print_help(); exit; } // // shell command // protected function shell() { return array(array(&$this, 'on_shell_input'), array(&$this, 'on_shell_quit')); } private function _eval($raw, $symbols) { extract($symbols); eval($raw); $g = get_defined_vars(); unset($g['raw']); unset($g['symbols']); return $g; } public function on_shell_input($raw) { $this->symbols = $this->_eval($raw, $this->symbols); JAXLCli::prompt(); } public function on_shell_quit() { exit; } // // debug command // protected function debug($sock_path) { $this->ipc = new JAXLSocketClient(); $this->ipc->set_callback(array(&$this, 'on_debug_response')); $this->ipc->connect('unix://'.$sock_path); return array(array(&$this, 'on_debug_input'), array(&$this, 'on_debug_quit')); } public function on_debug_response($raw) { $ret = unserialize($raw); print_r($ret); echo "\n"; JAXLCli::prompt(); } public function on_debug_input($raw) { $this->ipc->send($this->buffer.$raw); } public function on_debug_quit() { $this->ipc->disconnect(); exit; } } // we atleast need a command argument -if($argc < 2) { +if ($argc < 2) { JAXLCtl::print_help(); exit; } $ctl = new JAXLCtl($command, $params); echo "done\n"; diff --git a/xep/xep_0030.php b/xep/xep_0030.php index 3c0d07d..9f64d89 100644 --- a/xep/xep_0030.php +++ b/xep/xep_0030.php @@ -1,89 +1,89 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DISCO_INFO', 'http://jabber.org/protocol/disco#info'); define('NS_DISCO_ITEMS', 'http://jabber.org/protocol/disco#items'); class XEP_0030 extends XMPPXep { // // abstract method // public function init() { return array( ); } // // api methods // public function get_info_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( array('type'=>'get', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$entity_jid), new JAXLXml('query', NS_DISCO_INFO) ); } public function get_info($entity_jid, $callback=null) { $pkt = $this->get_info_pkt($entity_jid); - if($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); + if ($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } public function get_items_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( array('type'=>'get', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$entity_jid), new JAXLXml('query', NS_DISCO_ITEMS) ); } public function get_items($entity_jid, $callback=null) { $pkt = $this->get_items_pkt($entity_jid); - if($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); + if ($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } // // event callbacks // } diff --git a/xep/xep_0114.php b/xep/xep_0114.php index 7651225..f25e9ec 100644 --- a/xep/xep_0114.php +++ b/xep/xep_0114.php @@ -1,92 +1,92 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_JABBER_COMPONENT_ACCEPT', 'jabber:component:accept'); class XEP_0114 extends XMPPXep { // // abstract method // public function init() { return array( 'on_connect' => 'start_stream', 'on_stream_start' => 'start_handshake', 'on_handshake_stanza' => 'logged_in', 'on_error_stanza' => 'logged_out' ); } // // event callbacks // public function start_stream() { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" to="'.$this->jaxl->jid->to_string().'" xmlns="'.NS_JABBER_COMPONENT_ACCEPT.'">'; $this->jaxl->send_raw($xml); } public function start_handshake($stanza) { _debug("starting component handshake"); $id = $stanza->id; $hash = strtolower(sha1($id.$this->jaxl->pass)); $stanza = new JAXLXml('handshake', null, $hash); $this->jaxl->send($stanza); } public function logged_in($stanza) { _debug("component handshake complete"); $this->jaxl->handle_auth_success(); return array("logged_in", 1); } public function logged_out($stanza) { - if($stanza->name == "error" && $stanza->ns == NS_XMPP) { + if ($stanza->name == "error" && $stanza->ns == NS_XMPP) { $reason = $stanza->childrens[0]->name; $this->jaxl->handle_auth_failure($reason); $this->jaxl->send_end_stream(); return array("logged_out", 0); } else { _debug("uncatched stanza received in logged_out"); } } } diff --git a/xep/xep_0199.php b/xep/xep_0199.php index c33e60d..377ff9b 100644 --- a/xep/xep_0199.php +++ b/xep/xep_0199.php @@ -1,57 +1,57 @@ <?php require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_XMPP_PING', 'urn:xmpp:ping'); class XEP_0199 extends XMPPXep { // // abstract method // public function init() { return array( 'on_auth_success' => 'on_auth_success', 'on_get_iq' => 'on_xmpp_ping' ); } // // api methods // public function get_ping_pkt() { $attrs = array( 'type'=>'get', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$this->jaxl->full_jid->domain ); return $this->jaxl->get_iq_pkt( $attrs, new JAXLXml('ping', NS_XMPP_PING) ); } public function ping() { $this->jaxl->send($this->get_ping_pkt()); } // // event callbacks // public function on_auth_success() { JAXLLoop::$clock->call_fun_periodic(30 * pow(10,6), array(&$this, 'ping')); } public function on_xmpp_ping($stanza) { - if($stanza->exists('ping', NS_XMPP_PING)) { + if ($stanza->exists('ping', NS_XMPP_PING)) { $stanza->type = "result"; $stanza->to = $stanza->from; $stanza->from = $this->jaxl->full_jid->to_string(); $this->jaxl->send($stanza); } } } diff --git a/xep/xep_0206.php b/xep/xep_0206.php index 07d3636..c8f58a5 100644 --- a/xep/xep_0206.php +++ b/xep/xep_0206.php @@ -1,233 +1,233 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind'); define('NS_BOSH', 'urn:xmpp:xbosh'); class XEP_0206 extends XMPPXep { private $mch = null; public $chs = array(); private $recv_cb = null; public $rid = null; public $sid = null; private $hold = 1; private $wait = 30; private $restarted = false; public $headers = array( 'Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8' ); // // abstract method // public function init() { $this->mch = curl_multi_init(); return array( ); } // // event callbacks // public function send($body) { - if(is_object($body)) { + if (is_object($body)) { $body = $body->to_string(); } else { - if(substr($body, 0, 15) == '<stream:stream ') { + if (substr($body, 0, 15) == '<stream:stream ') { $this->restarted = true; $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'xmpp:restart' => 'true', 'xmlns:xmpp' => NS_BOSH )); $body = $body->to_string(); } - else if(substr($body, 0, 16) == '</stream:stream>') { + else if (substr($body, 0, 16) == '</stream:stream>') { $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'type' => 'terminate' )); $body = $body->to_string(); } else { $body = $this->wrap($body); } } _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body); $this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']); curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers); curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false); curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1); curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body); curl_multi_add_handle($this->mch, $this->chs[$this->rid]); } public function recv() { - if($this->restarted) { + if ($this->restarted) { $this->restarted = false; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state - if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); + if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); } _debug("recving for $this->rid"); do { $ret = curl_multi_exec($this->mch, $running); $changed = curl_multi_select($this->mch, 0.1); - if($changed == 0 && $running == 0) { + if ($changed == 0 && $running == 0) { $ch = @$this->chs[$this->rid]; - if($ch) { + if ($ch) { $data = curl_multi_getcontent($ch); curl_multi_remove_handle($this->mch, $ch); unset($this->chs[$this->rid]); _debug("recvd for $this->rid ".$data); list($body, $stanza) = $this->unwrap($data); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); - if(@$attrs['type'] == 'terminate') { + if (@$attrs['type'] == 'terminate') { // fool me again - if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); + if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); } else { - if(!$this->sid) { + if (!$this->sid) { $this->sid = $attrs['sid']; } - if($this->recv_cb) call_user_func($this->recv_cb, $stanza); + if ($this->recv_cb) call_user_func($this->recv_cb, $stanza); } } else { _error("no ch found"); exit; } } } while($running); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function wrap($stanza) { return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>'; } public function unwrap($body) { // a dirty way but it works efficiently - if(substr($body, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); + if (substr($body, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); - if(isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; + if (isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; else $envelop = "<body/>"; - if(isset($m[2][0])) $payload = $m[2][0]; + if (isset($m[2][0])) $payload = $m[2][0]; else $payload = ''; return array($envelop, $payload); } public function session_start() { $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000); $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold; $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state - if($this->recv_cb) + if ($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); $attrs = array( 'content' => 'text/xml; charset=utf-8', 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'], 'secure' => 'true', 'xml:lang' => 'en', 'xmpp:version' => '1.0', 'xmlns:xmpp' => NS_BOSH, 'hold' => $this->hold, 'wait' => $this->wait, 'rid' => $this->rid, 'ver' => '1.10' ); - if(@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; + if (@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; $body = new JAXLXml('body', NS_HTTP_BIND, $attrs); $this->send($body); } public function ping() { $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid)); $this->send($body); } public function session_end() { $this->disconnect(); } public function disconnect() { _debug("disconnecting"); } } diff --git a/xep/xep_0249.php b/xep/xep_0249.php index 8108ab8..2887265 100644 --- a/xep/xep_0249.php +++ b/xep/xep_0249.php @@ -1,78 +1,78 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DIRECT_MUC_INVITATION', 'jabber:x:conference'); class XEP_0249 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods // public function get_invite_pkt($to_bare_jid, $room_jid, $password=null, $reason=null, $thread=null, $continue=null) { $xattrs = array('jid'=>$room_jid); - if($password) $xattrs['password'] = $password; - if($reason) $xattrs['reason'] = $reason; - if($thread) $xattrs['thread'] = $thread; - if($continue) $xattrs['continue'] = $continue; + if ($password) $xattrs['password'] = $password; + if ($reason) $xattrs['reason'] = $reason; + if ($thread) $xattrs['thread'] = $thread; + if ($continue) $xattrs['continue'] = $continue; return $this->jaxl->get_msg_pkt( array('from'=>$this->jaxl->full_jid->to_string(), 'to'=>$to_bare_jid), null, null, null, new JAXLXml('x', NS_DIRECT_MUC_INVITATION, $xattrs) ); } public function invite($to_bare_jid, $room_jid, $password=null, $reason=null, $thread=null, $continue=null) { $this->jaxl->send($this->get_invite_pkt($to_bare_jid, $room_jid, $password, $reason, $thread, $continue)); } // // event callbacks // } diff --git a/xmpp/xmpp_jid.php b/xmpp/xmpp_jid.php index c122a5f..a4b10f6 100644 --- a/xmpp/xmpp_jid.php +++ b/xmpp/xmpp_jid.php @@ -1,80 +1,80 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Xmpp Jid * * @author abhinavsingh * */ class XMPPJid { public $node = null; public $domain = null; public $resource = null; public $bare = null; public function __construct($str) { $tmp = explode("@", $str); - if(sizeof($tmp) == 2) { + if (sizeof($tmp) == 2) { $this->node = $tmp[0]; $tmp = explode("/", $tmp[1]); - if(sizeof($tmp) == 2) { + if (sizeof($tmp) == 2) { $this->domain = $tmp[0]; $this->resource = $tmp[1]; } else { $this->domain = $tmp[0]; } } - else if(sizeof($tmp) == 1) { + else if (sizeof($tmp) == 1) { $this->domain = $tmp[0]; } $this->bare = $this->node ? $this->node."@".$this->domain : $this->domain; } public function to_string() { $str = ""; - if($this->node) $str .= $this->node.'@'.$this->domain; - else if($this->domain) $str .= $this->domain; - if($this->resource) $str .= '/'.$this->resource; + if ($this->node) $str .= $this->node.'@'.$this->domain; + else if ($this->domain) $str .= $this->domain; + if ($this->resource) $str .= '/'.$this->resource; return $str; } } diff --git a/xmpp/xmpp_msg.php b/xmpp/xmpp_msg.php index 1a190dd..16c588a 100644 --- a/xmpp/xmpp_msg.php +++ b/xmpp/xmpp_msg.php @@ -1,50 +1,50 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; class XMPPMsg extends XMPPStanza { public function __construct($attrs, $body=null, $thread=null, $subject=null) { parent::__construct('message', $attrs); - if($body) $this->c('body')->t($body)->up(); - if($thread) $this->c('thread')->t($thread)->up(); - if($subject) $this->c('subject')->t($subject)->up(); + if ($body) $this->c('body')->t($body)->up(); + if ($thread) $this->c('thread')->t($thread)->up(); + if ($subject) $this->c('subject')->t($subject)->up(); } } diff --git a/xmpp/xmpp_pres.php b/xmpp/xmpp_pres.php index 92420d2..411a746 100644 --- a/xmpp/xmpp_pres.php +++ b/xmpp/xmpp_pres.php @@ -1,50 +1,50 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; class XMPPPres extends XMPPStanza { public function __construct($attrs, $status=null, $show=null, $priority=null) { parent::__construct('presence', $attrs); - if($status) $this->c('status')->t($status)->up(); - if($show) $this->c('show')->t($show)->up(); - if($priority) $this->c('priority')->t($priority)->up(); + if ($status) $this->c('status')->t($status)->up(); + if ($show) $this->c('show')->t($show)->up(); + if ($priority) $this->c('priority')->t($priority)->up(); } } diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php index dfbeefd..d6abcaf 100644 --- a/xmpp/xmpp_stanza.php +++ b/xmpp/xmpp_stanza.php @@ -1,173 +1,173 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; /** * Generic xmpp stanza object which provide convinient access pattern over xml objects * Also to be able to convert an existing xml object into stanza object (to get access patterns going) * this class doesn't extend xml, but infact works on a reference of xml object * If not provided during constructor, new xml object is created and saved as reference * * @author abhinavsingh * */ class XMPPStanza { private $xml; public function __construct($name, $attrs=array(), $ns=NS_JABBER_CLIENT) { - if($name instanceof JAXLXml) $this->xml = $name; + if ($name instanceof JAXLXml) $this->xml = $name; else $this->xml = new JAXLXml($name, $ns, $attrs); } public function __call($method, $args) { return call_user_func_array(array($this->xml, $method), $args); } public function __get($prop) { switch($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': return @$this->xml->attrs[$prop] ? $this->xml->attrs[$prop] : null; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val = @$this->xml->attrs[$attr] ? $this->xml->attrs[$attr] : null; - if(!$val) return null; + if (!$val) return null; $val = new XMPPJid($val); return $val->$key; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val = $this->xml->exists($prop); - if(!$val) return null; + if (!$val) return null; return $val->text; break; default: return null; break; } } public function __set($prop, $val) { switch($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop = $val; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': $this->xml->attrs[$prop] = $val; return true; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val1 = @$this->xml->attrs[$attr]; - if(!$val1) $val1 = ''; + if (!$val1) $val1 = ''; $val1 = new XMPPJid($val1); $val1->$key = $val; $this->xml->attrs[$attr] = $val1->to_string(); return true; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val1 = $this->xml->exists($prop); - if(!$val1) $this->xml->c($prop)->t($val)->up(); + if (!$val1) $this->xml->c($prop)->t($val)->up(); else $this->xml->update($prop, $val1->ns, $val1->attrs, $val); return true; break; default: return null; break; } } } diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index dddaca7..77fea57 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,668 +1,668 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass=null, $resource=null, $force_tls=false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; - //if(isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; - if(isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; + //if (isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; + if (isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism'=>$mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. - if(strlen($pass) == 0) + if (strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); - if(!isset($decoded['rspauth'])) { + if (!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; - if(!isset($decoded['digest-uri'])) + if (!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); - if(isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) + if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc'=>$nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach(array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) - if(isset($decoded[$key])) + if (isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); - if(!$msg->id) $msg->id = $this->get_id(); - if($payload) $msg->cnode($payload); + if (!$msg->id) $msg->id = $this->get_id(); + if ($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null) { $pres = new XMPPPres($attrs, $status, $show, $priority); - if(!$pres->id) $pres->id = $this->get_id(); - if($payload) $pres->cnode($payload); + if (!$pres->id) $pres->id = $this->get_id(); + if ($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); - if(!$iq->id) $iq->id = $this->get_id(); - if($payload) $iq->cnode($payload); + if (!$iq->id) $iq->id = $this->get_id(); + if ($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach($data as $pair) { $dd = strpos($pair, '='); - if($dd) { + if ($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } - else if(strpos(strrev(trim($pair)), '"') === 0 && $key) { + else if (strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach(array('realm', 'cnonce', 'digest-uri') as $key) - if(!isset($data[$key])) + if (!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); - if(isset($data['authzid'])) + if (isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; - if($this->trans->connect($socket_path)) { + if ($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; - if($starttls && $required) { + if ($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); - if($mechs) { + if ($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; - if($bind) { + if ($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters - else if($comp) { + else if ($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; - if($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { - if($this->trans->crypt()) { + if ($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { + if ($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; - if($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { + if ($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; - if($stanza->name == 'failure' && $stanza->ns == NS_SASL) { + if ($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } - else if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { + else if ($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } - else if($stanza->name == 'success' && $stanza->ns == NS_SASL) { + else if ($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id - if($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' + if ($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract - if($stanza->name == 'message') { + if ($stanza->name == 'message') { $this->handle_message($stanza); } - else if($stanza->name == 'presence') { + else if ($stanza->name == 'presence') { $this->handle_presence($stanza); } - else if($stanza->name == 'iq') { + else if ($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } }
jaxl/JAXL
99cf4ce04dd6c8a420fd6173d95f47fcfe77fa0c
Fix PSR: Proper class and file endings
diff --git a/core/jaxl_cli.php b/core/jaxl_cli.php index 4b48d1a..ad763bd 100644 --- a/core/jaxl_cli.php +++ b/core/jaxl_cli.php @@ -1,97 +1,94 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLCli { public static $counter = 0; private $in = null; private $quit_cb = null; private $recv_cb = null; private $recv_chunk_size = 1024; public function __construct($recv_cb=null, $quit_cb=null) { $this->recv_cb = $recv_cb; $this->quit_cb = $quit_cb; // catch read event on stdin $this->in = fopen('php://stdin', 'r'); stream_set_blocking($this->in, false); JAXLLoop::watch($this->in, array( 'read' => array(&$this, 'on_read_ready') )); } public function __destruct() { @fclose($this->in); } public function stop() { JAXLLoop::unwatch($this->in, array( 'read' => true )); } public function on_read_ready($in) { $raw = @fread($in, $this->recv_chunk_size); if(ord($raw) == 10) { // enter key JAXLCli::prompt(false); return; } else if(trim($raw) == 'quit') { $this->stop(); $this->in = null; if($this->quit_cb) call_user_func($this->quit_cb); return; } if($this->recv_cb) call_user_func($this->recv_cb, $raw); } public static function prompt($inc=true) { if($inc) ++self::$counter; echo "jaxl ".self::$counter."> "; } - } - -?> diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php index c08ad6a..22f58b2 100644 --- a/core/jaxl_clock.php +++ b/core/jaxl_clock.php @@ -1,126 +1,123 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class JAXLClock { // current clock time in microseconds private $tick = 0; // current Unix timestamp with microseconds public $time = null; // scheduled jobs public $jobs = array(); public function __construct() { $this->time = microtime(true); } public function __destruct() { _info("shutting down clock server..."); } public function tick($by=null) { // update clock if($by) { $this->tick += $by; $this->time += $by / pow(10,6); } else { $time = microtime(true); $by = $time - $this->time; $this->tick += $by * pow(10, 6); $this->time = $time; } // run scheduled jobs foreach($this->jobs as $ref=>$job) { if($this->tick >= $job['scheduled_on'] + $job['after']) { //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".$job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); call_user_func($job['cb'], $job['args']); if(!$job['is_periodic']) { unset($this->jobs[$ref]); } else { $job['scheduled_on'] = $this->tick; $job['runs']++; $this->jobs[$ref] = $job; } } } } // calculate execution time of callback public function tc($callback, $args=null) { } // callback after $time microseconds public function call_fun_after($time, $callback, $args=null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => false, 'runs' => 0 ); return sizeof($this->jobs); } // callback periodically after $time microseconds public function call_fun_periodic($time, $callback, $args=null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => true, 'runs' => 0 ); return sizeof($this->jobs); } // cancel a previously scheduled callback public function cancel_fun_call($ref) { unset($this->jobs[$ref-1]); } - } - -?> diff --git a/core/jaxl_event.php b/core/jaxl_event.php index 3f3bf72..72207c3 100644 --- a/core/jaxl_event.php +++ b/core/jaxl_event.php @@ -1,121 +1,118 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * following kind of events are possible: * 1) hook i.e. if a callback for such an event is registered, calling function is responsible for the workflow from their on * 2) filter i.e. calling function will manipulate passed arguments and modified arguments will be passed to next chain of filter * * As a rule of thumb, only 1 hook can be registered for an event, while more than 1 filter is allowed for an event * hook and filter both cannot be applied on an event * * @author abhinavsingh * */ class JAXLEvent { protected $common = array(); public $reg = array(); public function __construct($common) { $this->common = $common; } public function __destruct() { } // add callback on a event // returns a reference to be used while deleting callback // callback'd method must return TRUE to be persistent // if none returned or FALSE, callback will be removed automatically public function add($ev, $cb, $pri) { if(!isset($this->reg[$ev])) $this->reg[$ev] = array(); $ref = sizeof($this->reg[$ev]); $this->reg[$ev][] = array($pri, $cb); return $ev."-".$ref; } // emit event to notify registered callbacks // is a pqueue required here for performance enhancement // in case we have too many cbs on a specific event? public function emit($ev, $data=array()) { $data = array_merge($this->common, $data); $cbs = array(); if(!isset($this->reg[$ev])) return $data; foreach($this->reg[$ev] as $cb) { if(!isset($cbs[$cb[0]])) $cbs[$cb[0]] = array(); $cbs[$cb[0]][] = $cb[1]; } foreach($cbs as $pri => $cb) { foreach($cb as $c) { $ret = call_user_func_array($c, $data); // this line is for fixing situation where callback function doesn't return an array type // in such cases next call of call_user_func_array will report error since $data is not an array type as expected // things will change in future, atleast put the callback inside a try/catch block // here we only check if there was a return, if yes we update $data with return value // this is bad design, need more thoughts, should work as of now if($ret) $data = $ret; } } unset($cbs); return $data; } // remove previous registered callback public function del($ref) { $ref = explode("-", $ref); unset($this->reg[$ref[0]][$ref[1]]); } public function exists($ev) { $ret = isset($this->reg[$ev]); //_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists")); return $ret; } - } - -?> diff --git a/core/jaxl_exception.php b/core/jaxl_exception.php index 86c2784..4d9841f 100644 --- a/core/jaxl_exception.php +++ b/core/jaxl_exception.php @@ -1,94 +1,92 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ error_reporting(E_ALL | E_STRICT); /** * * @author abhinavsingh */ class JAXLException extends Exception { public function __construct($message = null, $code = null, $file = null, $line = null) { _notice("got jaxl exception construct with $message, $code, $file, $line"); if($code === null) { parent::__construct($message); } else { parent::__construct($message, $code); } if($file !== null) { $this->file = $file; } if($line !== null) { $this->line = $line; } } public static function error_handler($errno, $error, $file, $line, $vars) { _debug("error handler called with $errno, $error, $file, $line"); if($errno === 0 || ($errno & error_reporting()) === 0) { return; } throw new JAXLException($error, $errno, $file, $line); } public static function exception_handler($e) { _debug("exception handler catched ".json_encode($e)); // TODO: Pretty print backtrace //print_r(debug_backtrace()); } public static function shutdown_handler() { try { _debug("got shutdown handler"); if(null !== ($error = error_get_last())) { throw new JAXLException($error['message'], $error['type'], $error['file'], $error['line']); } } catch(Exception $e) { _debug("shutdown handler catched with exception ".json_encode($e)); } } } - -?> diff --git a/core/jaxl_fsm.php b/core/jaxl_fsm.php index 4b89196..03687b5 100644 --- a/core/jaxl_fsm.php +++ b/core/jaxl_fsm.php @@ -1,84 +1,81 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ abstract class JAXLFsm { protected $state = null; // abstract method abstract public function handle_invalid_state($r); public function __construct($state) { $this->state = $state; } // returned value from state callbacks can be: // 1) array() <-- is_callable method // 2) array([0]=>'new_state', [1]=>'return value for current callback') <-- is_not_callable method // 3) array([0]=>'new_state') // 4) 'new_state' // // for case 1) new state will be an array // for other cases new state will be a string public function __call($event, $args) { if($this->state) { // call state method _debug("calling state handler '".(is_array($this->state) ? $this->state[1] : $this->state)."' for incoming event '".$event."'"); $call = is_callable($this->state) ? $this->state : (method_exists($this, $this->state) ? array(&$this, $this->state): $this->state); $r = call_user_func($call, $event, $args); // 4 cases of possible return value if(is_callable($r)) $this->state = $r; else if(is_array($r) && sizeof($r) == 2) list($this->state, $ret) = $r; else if(is_array($r) && sizeof($r) == 1) $this->state = $r[0]; else if(is_string($r)) $this->state = $r; else $this->handle_invalid_state($r); _debug("current state '".(is_array($this->state) ? $this->state[1] : $this->state)."'"); // return case if(!is_callable($r) && is_array($r) && sizeof($r) == 2) return $ret; } else { _debug("invalid state found, nothing called for event ".$event.""); } } - } - -?> diff --git a/core/jaxl_logger.php b/core/jaxl_logger.php index e49b5cd..e46a79f 100644 --- a/core/jaxl_logger.php +++ b/core/jaxl_logger.php @@ -1,92 +1,89 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // log level define('JAXL_ERROR', 1); define('JAXL_WARNING', 2); define('JAXL_NOTICE', 3); define('JAXL_INFO', 4); define('JAXL_DEBUG', 5); // generic global logging shortcuts for different level of verbosity function _error($msg) { JAXLLogger::log($msg, JAXL_ERROR); } function _warning($msg) { JAXLLogger::log($msg, JAXL_WARNING); } function _notice($msg) { JAXLLogger::log($msg, JAXL_NOTICE); } function _info($msg) { JAXLLogger::log($msg, JAXL_INFO); } function _debug($msg) { JAXLLogger::log($msg, JAXL_DEBUG); } // generic global terminal output colorize method // finally sends colorized message to terminal using error_log/1 // this method is mainly to escape $msg from file:line and time // prefix done by _debug, _error, ... methods function _colorize($msg, $verbosity) { error_log(JAXLLogger::colorize($msg, $verbosity)); } class JAXLLogger { public static $level = JAXL_DEBUG; public static $path = null; public static $max_log_size = 1000; protected static $colors = array( 1 => 31, // error: red 2 => 34, // warning: blue 3 => 33, // notice: yellow 4 => 32, // info: green 5 => 37 // debug: white ); public static function log($msg, $verbosity=1) { if($verbosity <= self::$level) { $bt = debug_backtrace(); array_shift($bt); $callee = array_shift($bt); $msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg; $size = strlen($msg); if($size > self::$max_log_size) $msg = substr($msg, 0, self::$max_log_size) . ' ...'; if(isset(self::$path)) error_log($msg . PHP_EOL, 3, self::$path); else error_log(self::colorize($msg, $verbosity)); } } public static function colorize($msg, $verbosity) { return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m"; } - } - -?> diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index 72d0ced..b08b605 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,159 +1,156 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLLoop { public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; private function __construct() {} private function __clone() {} public static function watch($fd, $opts) { if(isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } if(isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function unwatch($fd, $opts) { if(isset($opts['read'])) { $fdid = (int) $fd; if(isset(self::$read_fds[$fdid])) { unset(self::$read_fds[$fdid]); unset(self::$read_cbs[$fdid]); --self::$active_read_fds; } } if(isset($opts['write'])) { $fdid = (int) $fd; if(isset(self::$write_fds[$fdid])) { unset(self::$write_fds[$fdid]); unset(self::$write_cbs[$fdid]); --self::$active_write_fds; } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function run() { if(!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); while((self::$active_read_fds + self::$active_write_fds) > 0) self::select(); _debug("no more active fd's to select"); self::$is_running = false; } } private static function select() { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); if($changed === false) { _error("error in the event loop, shutting down..."); /*foreach(self::$read_fds as $fd) { if(is_resource($fd)) print_r(stream_get_meta_data($fd)); }*/ exit; } else if($changed > 0) { // read callback foreach($read as $r) { $fdid = array_search($r, self::$read_fds); if(isset(self::$read_fds[$fdid])) call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); } // write callback foreach($write as $w) { $fdid = array_search($w, self::$write_fds); if(isset(self::$write_fds[$fdid])) call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); } self::$clock->tick(); } else if($changed === 0) { //_debug("nothing changed while selecting for read"); self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); } } - } - -?> diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php index 2f251f1..c354daa 100644 --- a/core/jaxl_pipe.php +++ b/core/jaxl_pipe.php @@ -1,115 +1,112 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * bidirectional communication pipes for processes * * This is how this will be (when complete): * $pipe = new JAXLPipe() will return an array of size 2 * $pipe[0] represents the read end of the pipe * $pipe[1] represents the write end of the pipe * * Proposed functionality might even change (currently consider this as experimental) * * @author abhinavsingh * */ class JAXLPipe { protected $perm = 0600; protected $recv_cb = null; protected $fd = null; protected $client = null; public $name = null; public function __construct($name, $read_cb=null) { $pipes_folder = JAXL_CWD.'/.jaxl/pipes'; if(!is_dir($pipes_folder)) mkdir($pipes_folder); $this->ev = new JAXLEvent(); $this->name = $name; $this->read_cb = $read_cb; $pipe_path = $this->get_pipe_file_path(); if(!file_exists($pipe_path)) { posix_mkfifo($pipe_path, $this->perm); $this->fd = fopen($pipe_path, 'r+'); if(!$this->fd) { _error("unable to open pipe"); } else { _debug("pipe opened using path $pipe_path"); _notice("Usage: $ echo 'Hello World!' > $pipe_path"); $this->client = new JAXLSocketClient(); $this->client->connect($this->fd); $this->client->set_callback(array(&$this, 'on_data')); } } else { _error("pipe with name $name already exists"); } } public function __destruct() { @fclose($this->fd); @unlink($this->get_pipe_file_path()); _debug("unlinking pipe file"); } public function get_pipe_file_path() { return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe'; } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function on_data($data) { // callback if($this->recv_cb) call_user_func($this->recv_cb, $data); } - } - -?> diff --git a/core/jaxl_sock5.php b/core/jaxl_sock5.php index a4fad87..97e3b0b 100644 --- a/core/jaxl_sock5.php +++ b/core/jaxl_sock5.php @@ -1,128 +1,125 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ class JAXLSock5 { private $client = null; protected $transport = null; protected $ip = null; protected $port = null; public function __construct($transport='tcp') { $this->transport = $transport; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } public function __destruct() { } public function connect($ip, $port=1080) { $this->ip = $ip; $this->port = $port; $sock_path = $this->_sock_path(); if($this->client->connect($sock_path)) { _debug("established connection to $sock_path"); return true; } else { _error("unable to connect $sock_path"); return false; } } // // Three phases of SOCK5 // // Negotiation pkt consists of 3 part: // 0x05 => Sock protocol version // 0x01 => Number of method identifier octet // // Following auth methods are defined: // 0x00 => No authentication required // 0x01 => GSSAPI // 0x02 => USERNAME/PASSWORD // 0x03 to 0x7F => IANA ASSIGNED // 0x80 to 0xFE => RESERVED FOR PRIVATE METHODS // 0xFF => NO ACCEPTABLE METHODS public function negotiate() { $pkt = pack("C3", 0x05, 0x01, 0x00); $this->client->send($pkt); // enter sub-negotiation state } public function relay_request() { // enter wait for reply state } public function send_data() { } // // Socket client callback // public function on_response($raw) { _debug($raw); } // // Private // protected function _sock_path() { return $this->transport.'://'.$this->ip.':'.$this->port; } - } - -?> diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index 747bf5f..2ad366f 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,219 +1,216 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; public function __construct($stream_context=null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ public function connect($socket_path) { if(gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); if(sizeof($path_parts) == 3) $this->port = $path_parts[2]; _info("trying ".$socket_path); if($this->stream_context) $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); else $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); } else { $this->fd = &$socket_path; } if($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); $this->disconnect(); return false; } } public function disconnect() { JAXLLoop::unwatch($this->fd, array( 'read' => true, 'write' => true )); @fclose($this->fd); $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); return $ret; } public function send($data) { $this->obuffer .= $data; // add watch for write events if($this->writing) return; JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if($bytes === 0) { $meta = stream_get_meta_data($fd); if($meta['eof'] === TRUE) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); if($bytes > 0) _debug($raw); // callback if($this->recv_cb) call_user_func($this->recv_cb, $raw); } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if(strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } - } - -?> diff --git a/core/jaxl_socket_server.php b/core/jaxl_socket_server.php index b928560..c2497ab 100644 --- a/core/jaxl_socket_server.php +++ b/core/jaxl_socket_server.php @@ -1,258 +1,255 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; class JAXLSocketServer { public $fd = null; private $clients = array(); private $recv_chunk_size = 1024; private $send_chunk_size = 8092; private $accept_cb = null; private $request_cb = null; private $blocking = false; private $backlog = 200; public function __construct($path, $accept_cb, $request_cb) { $this->accept_cb = $accept_cb; $this->request_cb = $request_cb; $ctx = stream_context_create(array('socket'=>array('backlog'=>$this->backlog))); if(($this->fd = @stream_socket_server($path, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx)) !== false) { if(@stream_set_blocking($this->fd, $this->blocking)) { JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_server_accept_ready') )); _info("socket ready to accept on path ".$path); } else { _error("unable to set non block flag"); } } else { _error("unable to establish socket server, errno: ".$errno.", errstr: ".$errstr); } } public function __destruct() { _info("shutting down socket server"); } public function read($client_id) { //_debug("reactivating read on client sock"); $this->add_read_cb($client_id); } public function send($client_id, $data) { $this->clients[$client_id]['obuffer'] .= $data; $this->add_write_cb($client_id); } public function close($client_id) { $this->clients[$client_id]['close'] = true; $this->add_write_cb($client_id); } public function on_server_accept_ready($server) { //_debug("got server accept"); $client = @stream_socket_accept($server, 0, $addr); if(!$client) { _error("unable to accept new client conn"); return; } if(@stream_set_blocking($client, $this->blocking)) { $client_id = (int) $client; $this->clients[$client_id] = array( 'fd' => $client, 'ibuffer' => '', 'obuffer' => '', 'addr' => trim($addr), 'close' => false, 'closed' => false, 'reading' => false, 'writing' => false ); _debug("accepted connection from client#".$client_id.", addr:".$addr); // if accept callback is registered // callback and let user land take further control of what to do if($this->accept_cb) { call_user_func($this->accept_cb, $client_id, $this->clients[$client_id]['addr']); } // if no accept callback is registered // close the accepted connection else { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); } } else { _error("unable to set non block flag"); } } public function on_client_read_ready($client) { // deactive socket for read $client_id = (int) $client; //_debug("client#$client_id is read ready"); $this->del_read_cb($client_id); $raw = fread($client, $this->recv_chunk_size); $bytes = strlen($raw); _debug("recv $bytes bytes from client#$client_id"); //_debug($raw); if($bytes === 0) { $meta = stream_get_meta_data($client); if($meta['eof'] === TRUE) { _debug("socket eof client#".$client_id.", closing"); $this->del_read_cb($client_id); @fclose($client); unset($this->clients[$client_id]); return; } } $total = $this->clients[$client_id]['ibuffer'] . $raw; if($this->request_cb) call_user_func($this->request_cb, $client_id, $total); $this->clients[$client_id]['ibuffer'] = ''; } public function on_client_write_ready($client) { $client_id = (int) $client; _debug("client#$client_id is write ready"); try { // send in chunks $total = $this->clients[$client_id]['obuffer']; $written = @fwrite($client, substr($total, 0, $this->send_chunk_size)); if($written === false) { // fwrite failed _warning("====> fwrite failed"); $this->clients[$client_id]['obuffer'] = $total; } else if($written == strlen($total) || $written == $this->send_chunk_size) { // full chunk written //_debug("full chunk written"); $this->clients[$client_id]['obuffer'] = substr($total, $this->send_chunk_size); } else { // partial chunk written //_debug("partial chunk $written written"); $this->clients[$client_id]['obuffer'] = substr($total, $written); } // if no more stuff to write, remove write handler if(strlen($this->clients[$client_id]['obuffer']) === 0) { $this->del_write_cb($client_id); // if scheduled for close and not closed do it and clean up if($this->clients[$client_id]['close'] && !$this->clients[$client_id]['closed']) { @fclose($client); $this->clients[$client_id]['closed'] = true; unset($this->clients[$client_id]); _debug("closed client#".$client_id); } } } catch(JAXLException $e) { _debug("====> got fwrite exception"); } } // // client sock event register utils // protected function add_read_cb($client_id) { if($this->clients[$client_id]['reading']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'read' => array(&$this, 'on_client_read_ready') )); $this->clients[$client_id]['reading'] = true; } protected function add_write_cb($client_id) { if($this->clients[$client_id]['writing']) return; JAXLLoop::watch($this->clients[$client_id]['fd'], array( 'write' => array(&$this, 'on_client_write_ready') )); $this->clients[$client_id]['writing'] = true; } protected function del_read_cb($client_id) { if(!$this->clients[$client_id]['reading']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'read' => true )); $this->clients[$client_id]['reading'] = false; } protected function del_write_cb($client_id) { if(!$this->clients[$client_id]['writing']) return; JAXLLoop::unwatch($this->clients[$client_id]['fd'], array( 'write' => true )); $this->clients[$client_id]['writing'] = false; } - } - -?> diff --git a/core/jaxl_util.php b/core/jaxl_util.php index 2d1facd..f0fff8f 100644 --- a/core/jaxl_util.php +++ b/core/jaxl_util.php @@ -1,67 +1,64 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh * */ class JAXLUtil { public static function get_nonce($binary=true) { $nce = ''; mt_srand((double) microtime()*10000000); for($i=0; $i<32; $i++) $nce .= chr(mt_rand(0, 255)); return $binary ? $nce : base64_encode($nce); } public static function get_dns_srv($domain) { $rec = dns_get_record("_xmpp-client._tcp.".$domain, DNS_SRV); if(is_array($rec)) { if(sizeof($rec) == 0) return array($domain, 5222); if(sizeof($rec) > 0) return array($rec[0]['target'], $rec[0]['port']); } } public static function pbkdf2($data, $secret, $iteration, $dkLen=32, $algo='sha1') { return ''; } - } - -?> diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index 0a6a914..687d596 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,199 +1,196 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Details: http://abhinavsingh.com/blog/2012/09/jaxlxml-strophe-style-xml-builder-working-with-jaxl-a-networking-library-in-php-part-2/ * Doc: http://jaxl.readthedocs.org/en/latest/users/xml_objects.html#jaxlxml * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if(is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if(is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if(is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } public function match_attrs($attrs) { $matches = true; foreach($attrs as $k=>$v) { if($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } public function t($text, $append=FALSE) { if(!$append) { $this->rover->text = $text; } else { if($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; } return $this; } public function c($name, $ns=null, $attrs=array(), $text=null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } public function up() { if($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } public function top() { $this->rover = &$this; return $this; } public function exists($name, $ns=null, $attrs=array()) { foreach($this->childrens as $child) { if($ns) { if($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; } else if($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } public function update($name, $ns=null, $attrs=array(), $text=null) { foreach($this->childrens as $k=>$child) { if($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } public function to_string($parent_ns=null) { $xml = ''; $xml .= '<'.$this->name; if($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; foreach($this->attrs as $k=>$v) if(!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; foreach($this->childrens as $child) $xml .= $child->to_string($this->ns); if($this->text) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } - } - -?> diff --git a/core/jaxl_xml_stream.php b/core/jaxl_xml_stream.php index ede0d8b..01d4a84 100644 --- a/core/jaxl_xml_stream.php +++ b/core/jaxl_xml_stream.php @@ -1,191 +1,188 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Enter description here ... * @author abhinavsingh * */ class JAXLXmlStream { private $delimiter = '\\'; private $ns; private $parser; private $stanza; private $depth = -1; private $start_cb; private $stanza_cb; private $end_cb; public function __construct() { $this->init_parser(); } private function init_parser() { $this->depth = -1; $this->parser = xml_parser_create_ns("UTF-8", $this->delimiter); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); xml_set_character_data_handler($this->parser, array(&$this, "handle_character")); xml_set_element_handler($this->parser, array(&$this, "handle_start_tag"), array(&$this, "handle_end_tag")); } public function __destruct() { //_debug("cleaning up xml parser..."); @xml_parser_free($this->parser); } public function reset_parser() { $this->parse_final(null); @xml_parser_free($this->parser); $this->parser = null; $this->init_parser(); } public function set_callback($start_cb, $end_cb, $stanza_cb) { $this->start_cb = $start_cb; $this->end_cb = $end_cb; $this->stanza_cb = $stanza_cb; } public function parse($str) { xml_parse($this->parser, $str, false); } public function parse_final($str) { xml_parse($this->parser, $str, true); } protected function handle_start_tag($parser, $name, $attrs) { $name = $this->explode($name); //echo "start of tag ".$name[1]." with ns ".$name[0].PHP_EOL; // replace ns with prefix foreach($attrs as $key=>$v) { $k = $this->explode($key); // no ns specified if($k[0] == null) { $attrs[$k[1]] = $v; } // xml ns else if($k[0] == NS_XML) { unset($attrs[$key]); $attrs['xml:'.$k[1]] = $v; } else { _error("==================> unhandled ns prefix on attribute"); // remove attribute else will cause error with bad stanza format // report to developer if above error message is ever encountered unset($attrs[$key]); } } if($this->depth <= 0) { $this->depth = 0; $this->ns = $name[1]; if($this->start_cb) { $stanza = new JAXLXml($name[1], $name[0], $attrs); call_user_func($this->start_cb, $stanza); } } else { if(!$this->stanza) { $stanza = new JAXLXml($name[1], $name[0], $attrs); $this->stanza = &$stanza; } else { $this->stanza->c($name[1], $name[0], $attrs); } } ++$this->depth; } protected function handle_end_tag($parser, $name) { $name = explode($this->delimiter, $name); $name = sizeof($name) == 1 ? array('', $name[0]) : $name; //echo "depth ".$this->depth.", $name[1] tag ended".PHP_EOL.PHP_EOL; if($this->depth == 1) { if($this->end_cb) { $stanza = new JAXLXml($name[1], $this->ns); call_user_func($this->end_cb, $stanza); } } else if($this->depth > 1) { if($this->stanza) $this->stanza->up(); if($this->depth == 2) { if($this->stanza_cb) { call_user_func($this->stanza_cb, $this->stanza); $this->stanza = null; } } } --$this->depth; } protected function handle_character($parser, $data) { //echo "depth ".$this->depth.", character ".$data." for stanza ".$this->stanza->name.PHP_EOL; if($this->stanza) { $this->stanza->t(htmlentities($data, ENT_COMPAT, "UTF-8"), TRUE); } } private function implode($data) { return implode($this->delimiter, $data); } private function explode($data) { $data = explode($this->delimiter, $data); $data = sizeof($data) == 1 ? array(null, $data[0]) : $data; return $data; } - } - -?> diff --git a/examples/curl.php b/examples/curl.php index f19efb3..c0c3570 100644 --- a/examples/curl.php +++ b/examples/curl.php @@ -1,51 +1,49 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 2) { echo "Usage: $argv[0] url\n"; exit; } require_once 'jaxl.php'; JAXLLogger::$level = JAXL_DEBUG; require_once JAXL_CWD.'/http/http_client.php'; $request = new HTTPClient($argv[1]); $request->start(); - -?> diff --git a/examples/echo_bosh_bot.php b/examples/echo_bosh_bot.php index b23665f..4cd4c86 100644 --- a/examples/echo_bosh_bot.php +++ b/examples/echo_bosh_bot.php @@ -1,108 +1,106 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // (required) 'bosh_url' => 'http://localhost:5280/http-bind', // (optional) srv lookup is done if not provided // for bosh client 'host' value is used for 'route' attribute //'host' => 'xmpp.domain.tld', // (optional) result from srv lookup used by default // for bosh client 'port' value is used for 'route' attribute //'port' => 5222, // (optional) //'resource' => 'resource', // (optional) defaults to PLAIN if supported, else other methods will be automatically tried 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN', 'log_level' => JAXL_INFO )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); $client->set_status("available!", "dnd", 10); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; - -?> diff --git a/examples/echo_bot.php b/examples/echo_bot.php index e9437f3..a2c4a09 100644 --- a/examples/echo_bot.php +++ b/examples/echo_bot.php @@ -1,149 +1,147 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // Run as: // php examples/echo_bot.php root@localhost password // php examples/echo_bot.php root@localhost password DIGEST-MD5 // php examples/echo_bot.php localhost "" ANONYMOUS if($argc < 3) { echo "Usage: $argv[0] jid pass auth_type\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // (optional) srv lookup is done if not provided //'host' => 'xmpp.domain.tld', // (optional) result from srv lookup used by default //'port' => 5222, // (optional) defaults to false //'force_tls' => true, // (optional) //'resource' => 'resource', // (optional) defaults to PLAIN if supported, else other methods will be automatically tried 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN', 'log_level' => JAXL_INFO )); // // required XEP's // $client->require_xep(array( '0199' // XMPP Ping )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // fetch roster list $client->get_roster(); // fetch vcard $client->get_vcard(); // set status $client->set_status("available!", "dnd", 10); }); // by default JAXL instance catches incoming roster list results and updates // roster list is parsed/cached and an event 'on_roster_update' is emitted $client->add_cb('on_roster_update', function() { //global $client; //print_r($client->roster); }); $client->add_cb('on_auth_failure', function($reason) { global $client; _info("got on_auth_failure cb with reason $reason"); $client->send_end_stream(); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming chat message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_presence_stanza', function($stanza) { global $client; $type = ($stanza->type ? $stanza->type : "available"); $show = ($stanza->show ? $stanza->show : "???"); _info($stanza->from." is now ".$type." ($show)"); if($type == "available") { // fetch vcard $client->get_vcard($stanza->from); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(array( '--with-debug-shell' => true, '--with-unix-sock' => true )); echo "done\n"; - -?> diff --git a/examples/echo_component_bot.php b/examples/echo_component_bot.php index c37cb52..a42f9d6 100644 --- a/examples/echo_component_bot.php +++ b/examples/echo_component_bot.php @@ -1,100 +1,98 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc != 5) { echo "Usage: $argv[0] jid pass host port\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $comp = new JAXL(array( // (required) component host and secret 'jid' => $argv[1], 'pass' => $argv[2], // (required) 'host' => @$argv[3], 'port' => $argv[4], 'log_level' => JAXL_INFO )); // // XEP's required (required) // $comp->require_xep(array( '0114' // jabber component protocol )); // // add necessary event callbacks here // $comp->add_cb('on_auth_success', function() { _info("got on_auth_success cb"); }); $comp->add_cb('on_auth_failure', function($reason) { global $comp; $comp->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $comp->add_cb('on_chat_message', function($stanza) { global $comp; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $comp->jid->to_string(); $comp->send($stanza); }); $comp->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $comp->start(); echo "done\n"; - -?> diff --git a/examples/echo_http_server.php b/examples/echo_http_server.php index c308439..c6b7f38 100644 --- a/examples/echo_http_server.php +++ b/examples/echo_http_server.php @@ -1,60 +1,58 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // print usage notice and parse addr/port parameters if passed _colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE); $port = ($argc == 2 ? $argv[1] : 9699); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer($port); // catch all incoming requests here function on_request($request) { $body = json_encode($request); $request->ok($body, array('Content-Type'=>'application/json')); } // start http server $http->start('on_request'); - -?> diff --git a/examples/echo_unix_sock_server.php b/examples/echo_unix_sock_server.php index d67890b..22990be 100644 --- a/examples/echo_unix_sock_server.php +++ b/examples/echo_unix_sock_server.php @@ -1,61 +1,59 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 2) { echo "Usage: $argv[0] /path/to/server.sock\n"; exit; } require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; $server = null; function on_request($client, $raw) { global $server; $server->send($client, $raw); _info("got client callback ".$raw); } @unlink($argv[1]); $server = new JAXLSocketServer('unix://'.$argv[1], NULL, 'on_request'); JAXLLoop::run(); echo "done\n"; - -?> diff --git a/examples/http_bind.php b/examples/http_bind.php index edfcffa..4a53527 100644 --- a/examples/http_bind.php +++ b/examples/http_bind.php @@ -1,66 +1,64 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if(!isset($_GET['jid']) || !isset($_GET['pass'])) { echo "invalid input"; exit; } // // initialize JAXL object with initial config // require_once '../jaxl.php'; $client = new JAXL(array( 'jid' => $_GET['jid'], 'pass' => $_GET['pass'], 'bosh_url' => 'http://localhost:5280/http-bind', 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; - -?> diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php index 66f163d..be1677a 100644 --- a/examples/http_pre_bind.php +++ b/examples/http_pre_bind.php @@ -1,91 +1,89 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // http pre bind php script $body = file_get_contents("php://input"); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if(!@$attrs['to'] && !@$attrs['rid'] && !@$attrs['wait'] && !@$attrs['hold']) { echo "invalid input"; exit; } // // initialize JAXL object with initial config // require_once '../jaxl.php'; $to = (string)$attrs['to']; $rid = (int)$attrs['rid']; $wait = (int)$attrs['wait']; $hold = (int)$attrs['hold']; list($host, $port) = JAXLUtil::get_dns_srv($to); $client = new JAXL(array( 'domain' => $to, 'host' => $host, 'port' => $port, 'bosh_url' => 'http://localhost:5280/http-bind', 'bosh_rid' => $rid, 'bosh_wait' => $wait, 'bosh_hold' => $hold, 'auth_type' => 'ANONYMOUS', 'log_level' => JAXL_INFO )); $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); echo '<body xmlns="'.NS_HTTP_BIND.'" sid="'.$client->xeps['0206']->sid.'" rid="'.$client->xeps['0206']->rid.'" jid="'.$client->full_jid->to_string().'"/>'; exit; }); $client->add_cb('on_auth_failure', function($reason) { global $client; _info("got on_auth_failure cb with reason $reason"); $client->send_end_stream(); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; - -?> diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index a4b192b..3ec9dbe 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,146 +1,144 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 5) { echo "Usage: $argv[0] host jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[2], 'pass' => $argv[3], 'host' => $argv[1], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC '0203', // Delayed Delivery '0199' // XMPP Ping )); // // add necessary event callbacks here // $_room_full_jid = $argv[4]."/".$argv[5]; $room_full_jid = new XMPPJid($_room_full_jid); $client->add_cb('on_auth_success', function() { global $client, $room_full_jid; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // join muc room $client->xeps['0045']->join_room($room_full_jid); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_groupchat_message', function($stanza) { global $client; $from = new XMPPJid($stanza->from); $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); if($from->resource) { echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } else { $subject = $stanza->exists('subject'); if($subject) { echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } } }); $client->add_cb('on_presence_stanza', function($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster if(strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { if(($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { if(($status = $x->exists('status', null, array('code'=>'110'))) !== false) { $item = $x->exists('item'); _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); } else { _info("xmlns #user have no x child element"); } } else { _warning("=======> odd case 1"); } } // stanza from other users received else if(strtolower($from->bare) == strtolower($room_full_jid->bare)) { if(($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; } else { _warning("=======> odd case 2"); } } else { _warning("=======> odd case 3"); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; - -?> diff --git a/examples/multi_client.php b/examples/multi_client.php index 1e0872a..1b14aeb 100644 --- a/examples/multi_client.php +++ b/examples/multi_client.php @@ -1,129 +1,127 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // enable multi client support // this will force 1st parameter of callbacks // as connected client instance define('JAXL_MULTI_CLIENT', true); // input multiple account credentials $accounts = array(); $add_new = TRUE; while($add_new) { $jid = readline('Enter Jabber Id: '); $pass = readline('Enter Password: '); $accounts[] = array($jid, $pass); $next = readline('Add another account (y/n): '); $add_new = $next == 'y' ? TRUE : FALSE; } // setup jaxl require_once 'jaxl.php'; // // common callbacks // function on_auth_success($client) { _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // fetch roster list $client->get_roster(); // fetch vcard $client->get_vcard(); // set status $client->set_status("available!", "dnd", 10); } function on_auth_failure($client, $reason) { _info("got on_auth_failure cb with reason $reason"); $client->send_end_stream(); } function on_chat_message($client, $stanza) { // echo back incoming chat message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); } function on_presence_stanza($client, $stanza) { global $client; $type = ($stanza->type ? $stanza->type : "available"); $show = ($stanza->show ? $stanza->show : "???"); _info($stanza->from." is now ".$type." ($show)"); if($type == "available") { // fetch vcard $client->get_vcard($stanza->from); } } function on_disconnect($client) { _info("got on_disconnect cb"); } // // bootstrap all account instances // foreach($accounts as $account) { $client = new JAXL(array( 'jid' => $account[0], 'pass' => $account[1], 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', 'on_auth_success'); $client->add_cb('on_auth_failure', 'on_auth_failure'); $client->add_cb('on_chat_message', 'on_chat_message'); $client->add_cb('on_presence_stanza', 'on_presence_stanza'); $client->add_cb('on_disconnect', 'on_disconnect'); $client->connect($client->get_socket_path()); $client->start_stream(); } // start core loop JAXLLoop::run(); echo "done\n"; - -?> diff --git a/examples/pipes.php b/examples/pipes.php index 3607333..8fa44dc 100644 --- a/examples/pipes.php +++ b/examples/pipes.php @@ -1,59 +1,57 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // include jaxl pipes require_once JAXL_CWD.'/core/jaxl_pipe.php'; // initialize $pipe_name = getmypid(); $pipe = new JAXLPipe($pipe_name); // add read event callback $pipe->set_callback(function($data) { global $pipe; _info("read ".trim($data)." from pipe"); }); JAXLLoop::run(); echo "done\n"; - -?> diff --git a/examples/publisher.php b/examples/publisher.php index 9e9beeb..8adbd91 100644 --- a/examples/publisher.php +++ b/examples/publisher.php @@ -1,99 +1,97 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // create node //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); // publish $item = new JAXLXml('item', null, array('id'=>time())); $item->c('entry', 'http://www.w3.org/2005/Atom'); $item->c('title')->t('Soliloquy')->up(); $item->c('summary')->t('To be, or not to be: that is the question')->up(); $item->c('link', null, array('rel'=>'alternate', 'type'=>'text/html', 'href'=>'http://denmark.lit/2003/12/13/atom03'))->up(); $item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up(); $item->c('published')->t('2003-12-13T18:30:02Z')->up(); $item->c('updated')->t('2003-12-13T18:30:02Z')->up(); $client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; - -?> diff --git a/examples/register_user.php b/examples/register_user.php index 947dc76..c79546d 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,169 +1,167 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // $form = array(); function wait_for_register_response($event, $args) { global $client, $form; if($event == 'stanza_cb') { $stanza = $args[0]; if($stanza->name == 'iq') { $form['type'] = $stanza->attrs['type']; if($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } else if($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } } } else { _notice("unhandled event $event rcvd"); } } function wait_for_register_form($event, $args) { global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if($query) { $instructions = $query->exists('instructions'); if($instructions) { echo $instructions->text.PHP_EOL; } foreach($query->childrens as $k=>$child) { if($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // $client->add_cb('on_stream_features', function($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; }); $client->add_cb('on_disconnect', function() { global $form; _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); }); // // finally start configured xmpp stream // $client->start(); // // if registration was successful // try to connect with newly registered account // if($form['type'] == 'result') { _info("connecting newly registered user account"); $client = new JAXL(array( 'jid' => $form['username'].'@'.$argv[1], 'pass' => $form['password'], 'log_level' => JAXL_DEBUG )); $client->add_cb('on_auth_success', function() { global $client; $client->set_status('Available'); }); $client->start(); } echo "done\n"; - -?> diff --git a/examples/subscriber.php b/examples/subscriber.php index 69a3345..8ebf293 100644 --- a/examples/subscriber.php +++ b/examples/subscriber.php @@ -1,99 +1,97 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // create node //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); // subscribe $client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node'); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_headline_message', function($stanza) { global $client; if(($event = $stanza->exists('event', NS_PUBSUB.'#event'))) { _info("got pubsub event"); } else { _warning("unknown headline message rcvd"); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; - -?> diff --git a/examples/xfacebook_platform_client.php b/examples/xfacebook_platform_client.php index 76ae7e3..e9b0f19 100644 --- a/examples/xfacebook_platform_client.php +++ b/examples/xfacebook_platform_client.php @@ -1,100 +1,98 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc != 4) { echo "Usage: $argv[0] fb_user_id_or_username fb_app_key fb_access_token\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1].'@chat.facebook.com', 'fb_app_key' => $argv[2], 'fb_access_token' => $argv[3], // force tls (facebook require this now) 'force_tls' => true, // (required) force facebook oauth 'auth_type' => 'X-FACEBOOK-PLATFORM', // (optional) //'resource' => 'resource', 'log_level' => JAXL_INFO )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); $client->set_status("available!", "dnd", 10); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; - -?> diff --git a/examples/xmpp_rest.php b/examples/xmpp_rest.php index 0e052c6..9cab9b3 100644 --- a/examples/xmpp_rest.php +++ b/examples/xmpp_rest.php @@ -1,77 +1,75 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // View explanation for this example here: // https://groups.google.com/d/msg/jaxl/QaGjZP4A2gY/n6SYutrBVxsJ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // initialize xmpp client require_once 'jaxl.php'; $xmpp = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); // register callbacks on required xmpp events $xmpp->add_cb('on_auth_success', function() { global $xmpp; _info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string()); }); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); // add generic callback // you can also dispatch REST style callback // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules $http->cb = function($request) { // For demo purposes we simply return xmpp client full jid global $xmpp; $request->ok($xmpp->full_jid->to_string()); }; // This will start main JAXLLoop, // hence we don't need to call $http->start() explicitly $xmpp->start(); - -?> diff --git a/examples/xoauth2_gtalk_client.php b/examples/xoauth2_gtalk_client.php index 8a5d6cb..6b2c108 100644 --- a/examples/xoauth2_gtalk_client.php +++ b/examples/xoauth2_gtalk_client.php @@ -1,99 +1,97 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc != 3) { echo "Usage: $argv[0] jid access_token\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // force tls 'force_tls' => true, // (required) perform X-OAUTH2 'auth_type' => 'X-OAUTH2', // (optional) //'resource' => 'resource', 'log_level' => JAXL_DEBUG )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); $client->set_status("available!", "dnd", 10); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; - -?> diff --git a/http/http_client.php b/http/http_client.php index dd31674..5ec2c31 100644 --- a/http/http_client.php +++ b/http/http_client.php @@ -1,138 +1,135 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; /** * TODO: convert into a finite state machine * * @author abhinavsingh * */ class HTTPClient { private $url = null; private $parts = array(); private $headers = array(); private $data = null; public $method = null; private $client = null; public function __construct($url, $headers=array(), $data=null) { $this->url = $url; $this->headers = $headers; $this->data = $data; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } public function start($method='GET') { $this->method = $method; $this->parts = parse_url($this->url); $transport = $this->_transport(); $ip = $this->_ip(); $port = $this->_port(); $socket_path = $transport.'://'.$ip.':'.$port; if($this->client->connect($socket_path)) { _debug("connection to $this->url established"); // send request data $this->send_request(); // start main loop JAXLLoop::run(); } else { _debug("unable to open $this->url"); } } public function on_response($raw) { _info("got http response"); } protected function send_request() { $this->client->send($this->_line()."\r\n"); $this->client->send($this->_ua()."\r\n"); $this->client->send($this->_host()."\r\n"); $this->client->send("\r\n"); } // // private methods on uri parts // private function _line() { return $this->method.' '.$this->_uri().' HTTP/1.1'; } private function _ua() { return 'User-Agent: jaxl_http_client/3.x'; } private function _host() { return 'Host: '.$this->parts['host'].':'.$this->_port(); } private function _transport() { return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl'); } private function _ip() { return gethostbyname($this->parts['host']); } private function _port() { return @$this->parts['port'] ? $this->parts['port'] : 80; } private function _uri() { $uri = $this->parts['path']; if(@$this->parts['query']) $uri .= '?'.$this->parts['query']; if(@$this->parts['fragment']) $uri .= '#'.$this->parts['fragment']; return $uri; } - } - -?> diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php index efc9b17..fccf563 100644 --- a/http/http_dispatcher.php +++ b/http/http_dispatcher.php @@ -1,121 +1,117 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // // (optionally) set an array of url dispatch rules // each dispatch rule is defined by an array of size 4 like: // array($callback, $pattern, $methods, $extra), where // $callback the method which will be called if this rule matches // $pattern regular expression to match request path // $methods list of allowed methods for this rule // pass boolean true to allow all http methods // if omitted or an empty array() is passed (which actually doesnt make sense) // by default 'GET' will be the method allowed on this rule // $extra reserved for future (you can totally omit this as of now) // class HTTPDispatchRule { // match callback public $cb = null; // regexp to match on request path public $pattern = null; // methods to match upon // add atleast 1 method for this rule to work public $methods = null; // other matching rules public $extra = array(); public function __construct($cb, $pattern, $methods=array('GET'), $extra=array()) { $this->cb = $cb; $this->pattern = $pattern; $this->methods = $methods; $this->extra = $extra; } public function match($path, $method) { if(preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) { if(in_array($method, $this->methods)) { return $matches; } } return false; } - } class HTTPDispatcher { protected $rules = array(); public function __construct() { $this->rules = array(); } public function add_rule($rule) { $s = sizeof($rule); if($s > 4) { _debug("invalid rule"); return; } // fill up defaults if($s == 3) { $rule[] = array(); } else if($s == 2) { $rule[] = array('GET'); $rule[] = array(); } else { _debug("invalid rule"); return; } $this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]); } public function dispatch($request) { foreach($this->rules as $rule) { //_debug("matching $request->path with pattern $rule->pattern"); if(($matches = $rule->match($request->path, $request->method)) !== false) { _debug("matching rule found, dispatching"); $params = array($request); // TODO: a bad way to restrict on 'pk', fix me for generalization if(@isset($matches['pk'])) $params[] = $matches['pk']; call_user_func_array($rule->cb, $params); return true; } } return false; } - } - -?> diff --git a/http/http_multipart.php b/http/http_multipart.php index 5387e57..6624c9a 100644 --- a/http/http_multipart.php +++ b/http/http_multipart.php @@ -1,176 +1,173 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; class HTTPMultiPart extends JAXLFsm { public $boundary = null; public $form_data = array(); public $index = -1; public function handle_invalid_state($r) { _error("got invalid event $r"); } public function __construct($boundary) { $this->boundary = $boundary; parent::__construct('wait_for_boundary_start'); } public function state() { return $this->state; } public function wait_for_boundary_start($event, $data) { if($event == 'process') { if($data[0] == '--'.$this->boundary) { $this->index += 1; $this->form_data[$this->index] = array( 'meta' => array(), 'headers' => array(), 'body' => '' ); return array('wait_for_content_disposition', true); } else { _warning("invalid boundary start $data[0] while expecting $this->boundary"); return array('wait_for_boundary_start', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_boundary_start', false); } } public function wait_for_content_disposition($event, $data) { if($event == 'process') { $disposition = explode(":", $data[0]); if(strtolower(trim($disposition[0])) == 'content-disposition') { $this->form_data[$this->index]['headers'][$disposition[0]] = trim($disposition[1]); $meta = explode(";", $disposition[1]); if(trim(array_shift($meta)) == 'form-data') { foreach($meta as $k) { list($k, $v) = explode("=", $k); $this->form_data[$this->index]['meta'][$k] = $v; } return array('wait_for_content_type', true); } else { _warning("first part of meta is not form-data"); return array('wait_for_content_disposition', false); } } else { _warning("not a valid content-disposition line"); return array('wait_for_content_disposition', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_disposition', false); } } public function wait_for_content_type($event, $data) { if($event == 'process') { $type = explode(":", $data[0]); if(strtolower(trim($type[0])) == 'content-type') { $this->form_data[$this->index]['headers'][$type[0]] = trim($type[1]); $this->form_data[$this->index]['meta']['type'] = $type[1]; return array('wait_for_content_body', true); } else { _debug("not a valid content-type line"); return array('wait_for_content_type', false); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_type', false); } } public function wait_for_content_body($event, $data) { if($event == 'process') { if($data[0] == '--'.$this->boundary) { _debug("start of new multipart/form-data detected"); return array('wait_for_content_disposition', true); } else if($data[0] == '--'.$this->boundary.'--') { _debug("end of multipart form data detected"); return array('wait_for_empty_line', true); } else { $this->form_data[$this->index]['body'] .= $data[0]; return array('wait_for_content_body', true); } } else { _warning("invalid $event rcvd"); return array('wait_for_content_body', false); } } public function wait_for_empty_line($event, $data) { if($event == 'process') { if($data[0] == '') { return array('done', true); } else { _warning("invalid empty line $data[0] received"); return array('wait_for_empty_line', false); } } else { _warning("got $event in done state with data $data[0]"); return array('wait_for_empty_line', false); } } public function done($event, $data) { _warning("got unhandled event $event with data $data[0]"); return array('done', false); } - } - -?> diff --git a/http/http_request.php b/http/http_request.php index ef5afb4..b57430f 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,492 +1,488 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers=array(), $body=null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if(sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation // public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; if($this->body === null) $this->body = $rcvd; else $this->body .= $rcvd; if($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach($form_data as $data) { //_debug("passing $data to multipart fsm"); if(!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if(!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if(!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { switch($event) { case 'empty_line': return 'headers_received'; break; default: if(substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if(method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } } else if(@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { $k = trim($k); $v = ltrim($v); // is expect header? if(strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if(strtolower($k) == 'content-type') { $ctype = explode(';', $v); if(sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if(strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { if(sizeof($args) == 0) { $body = null; $headers = array(); } if(sizeof($args) == 1) { // http headers or body only received if(is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } } else if(sizeof($args) == 2) { // body and http headers both received if(is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { foreach($headers as $k=>$v) $this->_send_header($k, $v); } protected function _send_body($body) { $this->_send($body); } protected function _send_response($code, $headers=array(), $body=null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set if($body && !isset($headers['Content-Length'])) $headers['Content-Length'] = strlen($body); // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); if($body) $this->_send_body(HTTP_CRLF.$body); } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if(sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach($query as $q) { $q = explode("=", $q); if(sizeof($q) == 1) $q[1] = ""; $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } - - } - -?> diff --git a/http/http_server.php b/http/http_server.php index fcfadef..1831364 100644 --- a/http/http_server.php +++ b/http/http_server.php @@ -1,197 +1,194 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/http/http_dispatcher.php'; require_once JAXL_CWD.'/http/http_request.php'; // carriage return and line feed define('HTTP_CRLF', "\r\n"); // 1xx informational define('HTTP_100', "Continue"); define('HTTP_101', "Switching Protocols"); // 2xx success define('HTTP_200', "OK"); // 3xx redirection define('HTTP_301', 'Moved Permanently'); define('HTTP_304', 'Not Modified'); // 4xx client error define('HTTP_400', 'Bad Request'); define('HTTP_403', 'Forbidden'); define('HTTP_404', 'Not Found'); define('HTTP_405', 'Method Not Allowed'); define('HTTP_499', 'Client Closed Request'); // Nginx // 5xx server error define('HTTP_500', 'Internal Server Error'); define('HTTP_503', 'Service Unavailable'); class HTTPServer { private $server = null; public $cb = null; private $dispatcher = null; private $requests = array(); public function __construct($port=9699, $address="127.0.0.1") { $path = 'tcp://'.$address.':'.$port; $this->server = new JAXLSocketServer( $path, array(&$this, 'on_accept'), array(&$this, 'on_request') ); $this->dispatcher = new HTTPDispatcher(); } public function __destruct() { $this->server = null; } public function dispatch($rules) { foreach($rules as $rule) { $this->dispatcher->add_rule($rule); } } public function start($cb=null) { $this->cb = $cb; JAXLLoop::run(); } public function on_accept($sock, $addr) { _debug("on_accept for client#$sock, addr:$addr"); // initialize new request obj $request = new HTTPRequest($sock, $addr); // setup sock cb $request->set_sock_cb( array(&$this->server, 'send'), array(&$this->server, 'read'), array(&$this->server, 'close') ); // cache request object $this->requests[$sock] = &$request; // reactive client for further read $this->server->read($sock); } public function on_request($sock, $raw) { _debug("on_request for client#$sock"); $request = $this->requests[$sock]; // 'wait_for_body' state is reached when ever // application calls recv_body() method // on received $request object if($request->state() == 'wait_for_body') { $request->body($raw); } else { // break on crlf $lines = explode(HTTP_CRLF, $raw); // parse request line if($request->state() == 'wait_for_request_line') { list($method, $resource, $version) = explode(" ", $lines[0]); $request->line($method, $resource, $version); unset($lines[0]); _info($request->ip." ".$request->method." ".$request->resource." ".$request->version); } // parse headers foreach($lines as $line) { $line_parts = explode(":", $line); if(sizeof($line_parts) > 1) { if(strlen($line_parts[0]) > 0) { $k = $line_parts[0]; unset($line_parts[0]); $v = implode(":", $line_parts); $request->set_header($k, $v); } } else if(strlen(trim($line_parts[0])) == 0) { $request->empty_line(); } // if exploded line array size is 1 // and thr is something in $line_parts[0] // must be request body else { $request->body($line); } } } // if request has reached 'headers_received' state? if($request->state() == 'headers_received') { // dispatch to any matching rule found _debug("delegating to dispatcher for further routing"); $dispatched = $this->dispatcher->dispatch($request); // if no dispatch rule matched call generic callback if(!$dispatched && $this->cb) { _debug("no dispatch rule matched, sending to generic callback"); call_user_func($this->cb, $request); } // else if not dispatched and not generic callbacked // send 404 not_found else if(!$dispatched) { // TODO: send 404 if no callback is registered for this request _debug("dropping request since no matching dispatch rule or generic callback was specified"); $request->not_found('404 Not Found'); } } // if state is not 'headers_received' // reactivate client socket for read event else { $this->server->read($sock); } } - } - -?> diff --git a/jaxl.php b/jaxl.php index e17c419..2453f6f 100644 --- a/jaxl.php +++ b/jaxl.php @@ -294,516 +294,513 @@ class JAXL extends XMPPStream { $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } - } - -?> diff --git a/jaxlctl b/jaxlctl index b46ea0a..6746360 100755 --- a/jaxlctl +++ b/jaxlctl @@ -1,190 +1,187 @@ #!/usr/bin/env php <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ $params = $argv; $exe = array_shift($params); $command = array_shift($params); require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // TODO: an abstract JAXLCtlCommand class // with seperate class per command // a mechanism to register new commands class JAXLCtl { protected $ipc = null; protected $buffer = ''; protected $buffer_cb = null; protected $cli = null; public $dots = "....... "; protected $symbols = array(); public function __construct($command, $params) { global $exe; if(method_exists($this, $command)) { $r = call_user_func_array(array(&$this, $command), $params); if(sizeof($r) == 2) { list($buffer_cb, $quit_cb) = $r; $this->buffer_cb = $buffer_cb; $this->cli = new JAXLCli(array(&$this, 'on_terminal_input'), $quit_cb); $this->run(); } else { _colorize("oops! internal command error", JAXL_ERROR); exit; } } else { _colorize("error: invalid command '$command' received", JAXL_ERROR); _colorize("type '$exe help' for list of available commands", JAXL_NOTICE); exit; } } public function run() { JAXLCli::prompt(); JAXLLoop::run(); } public function on_terminal_input($raw) { $raw = trim($raw); $last = substr($raw, -1, 1); if($last == ";") { // dispatch to buffer callback call_user_func($this->buffer_cb, $this->buffer.$raw); $this->buffer = ''; } else if($last == '\\') { $this->buffer .= substr($raw, 0, -1); echo $this->dots; } else { // buffer command $this->buffer .= $raw."; "; echo $this->dots; } } public static function print_help() { global $exe; _colorize("Usage: $exe command [options...]\n", JAXL_INFO); _colorize("Commands:", JAXL_NOTICE); _colorize(" help This help text", JAXL_DEBUG); _colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG); _colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG); echo "\n"; } protected function help() { JAXLCtl::print_help(); exit; } // // shell command // protected function shell() { return array(array(&$this, 'on_shell_input'), array(&$this, 'on_shell_quit')); } private function _eval($raw, $symbols) { extract($symbols); eval($raw); $g = get_defined_vars(); unset($g['raw']); unset($g['symbols']); return $g; } public function on_shell_input($raw) { $this->symbols = $this->_eval($raw, $this->symbols); JAXLCli::prompt(); } public function on_shell_quit() { exit; } // // debug command // protected function debug($sock_path) { $this->ipc = new JAXLSocketClient(); $this->ipc->set_callback(array(&$this, 'on_debug_response')); $this->ipc->connect('unix://'.$sock_path); return array(array(&$this, 'on_debug_input'), array(&$this, 'on_debug_quit')); } public function on_debug_response($raw) { $ret = unserialize($raw); print_r($ret); echo "\n"; JAXLCli::prompt(); } public function on_debug_input($raw) { $this->ipc->send($this->buffer.$raw); } public function on_debug_quit() { $this->ipc->disconnect(); exit; } - } // we atleast need a command argument if($argc < 2) { JAXLCtl::print_help(); exit; } $ctl = new JAXLCtl($command, $params); echo "done\n"; - -?> diff --git a/tests/test_jaxl_event.php b/tests/test_jaxl_event.php index 73022da..7bb6d6a 100644 --- a/tests/test_jaxl_event.php +++ b/tests/test_jaxl_event.php @@ -1,72 +1,71 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLEventTest extends PHPUnit_Framework_TestCase { function test_jaxl_event() { $ev = new JAXLEvent(); $ref1 = $ev->add('on_connect', 'some_func', 0); $ref2 = $ev->add('on_connect', 'some_func1', 0); $ref3 = $ev->add('on_connect', 'some_func2', 1); $ref4 = $ev->add('on_connect', 'some_func3', 4); $ref5 = $ev->add('on_disconnect', 'some_func', 1); $ref6 = $ev->add('on_disconnect', 'some_func1', 1); //$ev->emit('on_connect', null); $ev->del($ref2); $ev->del($ref1); $ev->del($ref6); $ev->del($ref5); $ev->del($ref4); $ev->del($ref3); //print_r($ev->reg); } - } diff --git a/tests/test_jaxl_socket_client.php b/tests/test_jaxl_socket_client.php index e1bdc2f..55f298f 100644 --- a/tests/test_jaxl_socket_client.php +++ b/tests/test_jaxl_socket_client.php @@ -1,60 +1,59 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLSocketClientTest extends PHPUnit_Framework_TestCase { function test_jaxl_socket_client() { $sock = new JAXLSocketClient("127.0.0.1", 5222); $sock->connect(); $sock->send("<stream:stream>"); while($sock->fd) { $sock->recv(); } } - } diff --git a/tests/test_xmpp_msg.php b/tests/test_xmpp_msg.php index b39733e..40a8b02 100644 --- a/tests/test_xmpp_msg.php +++ b/tests/test_xmpp_msg.php @@ -1,68 +1,67 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPMsgTest extends PHPUnit_Framework_TestCase { function test_xmpp_msg() { $msg = new XMPPMsg(array('to'=>'[email protected]', 'from'=>'[email protected]/~', 'type'=>'chat'), 'hi', 'thread1'); echo $msg->to.PHP_EOL; echo $msg->to_node.PHP_EOL; echo $msg->from.PHP_EOL; echo $msg->to_string().PHP_EOL; $msg->to = '[email protected]/sp'; $msg->body = 'hello world'; $msg->subject = 'some subject'; echo $msg->to.PHP_EOL; echo $msg->to_node.PHP_EOL; echo $msg->from.PHP_EOL; echo $msg->to_string().PHP_EOL; } - } diff --git a/tests/test_xmpp_stanza.php b/tests/test_xmpp_stanza.php index 4c03814..905b22e 100644 --- a/tests/test_xmpp_stanza.php +++ b/tests/test_xmpp_stanza.php @@ -1,76 +1,75 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPStanzaTest extends PHPUnit_Framework_TestCase { function test_xmpp_stanza_nested() { $stanza = new JAXLXml('message', array('to'=>'[email protected]', 'from'=>'[email protected]')); $stanza ->c('body')->attrs(array('xml:lang'=>'en'))->t('hello')->up() ->c('thread')->t('1234')->up() ->c('nested') ->c('nest')->t('nest1')->up() ->c('nest')->t('nest2')->up() ->c('nest')->t('nest3')->up()->up() ->c('c')->attrs(array('hash'=>'84jsdmnskd')); $this->assertEquals( '<message to="[email protected]" from="[email protected]"><body xml:lang="en">hello</body><thread>1234</thread><nested><nest>nest1</nest><nest>nest2</nest><nest>nest3</nest></nested><c hash="84jsdmnskd"></c></message>', $stanza->to_string() ); } function test_xmpp_stanza_from_jaxl_xml() { // xml to stanza test $xml = new JAXLXml('message', NS_JABBER_CLIENT, array('to'=>'[email protected]', 'from'=>'[email protected]/q')); $stanza = new XMPPStanza($xml); $stanza->c('body')->t('hello world'); echo $stanza->to."\n"; echo $stanza->to_string()."\n"; } - } diff --git a/tests/test_xmpp_stream.php b/tests/test_xmpp_stream.php index a41e4e9..19b2b4b 100644 --- a/tests/test_xmpp_stream.php +++ b/tests/test_xmpp_stream.php @@ -1,60 +1,59 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class XMPPStreamTest extends PHPUnit_Framework_TestCase { function test_xmpp_stream() { $xmpp = new XMPPStream("test@localhost", "password"); $xmpp->connect(); $xmpp->start_stream(); while($xmpp->sock->fd) { $xmpp->sock->recv(); } } - } diff --git a/tests/tests.php b/tests/tests.php index 40803b4..129bc05 100644 --- a/tests/tests.php +++ b/tests/tests.php @@ -1,52 +1,50 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // TODO: support for php unit and add more tests error_reporting(E_ALL); require_once "jaxl.php"; /** * * @author abhinavsingh * */ class JAXLTest extends PHPUnit_Framework_TestCase { } - -?> diff --git a/xep/xep_0030.php b/xep/xep_0030.php index ede0a39..3c0d07d 100644 --- a/xep/xep_0030.php +++ b/xep/xep_0030.php @@ -1,92 +1,89 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DISCO_INFO', 'http://jabber.org/protocol/disco#info'); define('NS_DISCO_ITEMS', 'http://jabber.org/protocol/disco#items'); class XEP_0030 extends XMPPXep { // // abstract method // public function init() { return array( ); } // // api methods // public function get_info_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( array('type'=>'get', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$entity_jid), new JAXLXml('query', NS_DISCO_INFO) ); } public function get_info($entity_jid, $callback=null) { $pkt = $this->get_info_pkt($entity_jid); if($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } public function get_items_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( array('type'=>'get', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$entity_jid), new JAXLXml('query', NS_DISCO_ITEMS) ); } public function get_items($entity_jid, $callback=null) { $pkt = $this->get_items_pkt($entity_jid); if($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } // // event callbacks // - } - -?> diff --git a/xep/xep_0045.php b/xep/xep_0045.php index 1414ef1..7345ddc 100644 --- a/xep/xep_0045.php +++ b/xep/xep_0045.php @@ -1,114 +1,111 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_MUC', 'http://jabber.org/protocol/muc'); class XEP_0045 extends XMPPXep { // // abstract method // public function init() { return array(); } public function send_groupchat($room_jid, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'groupchat', 'to'=>(($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid), 'from'=>$this->jaxl->full_jid->to_string() ), $body, $thread, $subject ); $this->jaxl->send($msg); } // // api methods (occupant use case) // // room_full_jid simply means room jid with nick name as resource public function get_join_room_pkt($room_full_jid, $options) { $pkt = $this->jaxl->get_pres_pkt( array( 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid) ) ); $x = $pkt->c('x', NS_MUC); if (isset($options['no_history'])) { $x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0)); } return $x; } public function join_room($room_full_jid, $options = array()) { $pkt = $this->get_join_room_pkt($room_full_jid, $options); $this->jaxl->send($pkt); } public function get_leave_room_pkt($room_full_jid) { return $this->jaxl->get_pres_pkt( array('type'=>'unavailable', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid)) ); } public function leave_room($room_full_jid) { $pkt = $this->get_leave_room_pkt($room_full_jid); $this->jaxl->send($pkt); } // // api methods (moderator use case) // // // event callbacks // - } - -?> diff --git a/xep/xep_0060.php b/xep/xep_0060.php index f7b4eca..dc6dcc4 100644 --- a/xep/xep_0060.php +++ b/xep/xep_0060.php @@ -1,139 +1,136 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_PUBSUB', 'http://jabber.org/protocol/pubsub'); class XEP_0060 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods (entity use case) // // // api methods (subscriber use case) // public function get_subscribe_pkt($service, $node, $jid=null) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('subscribe', null, array('node'=>$node, 'jid'=>($jid ? $jid : $this->jaxl->full_jid->to_string()))); return $this->get_iq_pkt($service, $child); } public function subscribe($service, $node, $jid=null) { $this->jaxl->send($this->get_subscribe_pkt($service, $node, $jid)); } public function unsubscribe() { } public function get_subscription_options() { } public function set_subscription_options() { } public function get_node_items() { } // // api methods (publisher use case) // public function get_publish_item_pkt($service, $node, $item) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('publish', null, array('node'=>$node)); $child->cnode($item); return $this->get_iq_pkt($service, $child); } public function publish_item($service, $node, $item) { $this->jaxl->send($this->get_publish_item_pkt($service, $node, $item)); } public function delete_item() { } // // api methods (owner use case) // public function get_create_node_pkt($service, $node) { $child = new JAXLXml('pubsub', NS_PUBSUB); $child->c('create', null, array('node'=>$node)); return $this->get_iq_pkt($service, $child); } public function create_node($service, $node) { $this->jaxl->send($this->get_create_node_pkt($service, $node)); } // // event callbacks // // // local methods // // this always add attrs protected function get_iq_pkt($service, $child, $type='set') { return $this->jaxl->get_iq_pkt( array('type'=>$type, 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$service), $child ); } - } - -?> diff --git a/xep/xep_0077.php b/xep/xep_0077.php index e34838f..9ec3074 100644 --- a/xep/xep_0077.php +++ b/xep/xep_0077.php @@ -1,83 +1,80 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_FEATURE_REGISTER', 'http://jabber.org/features/iq-register'); define('NS_INBAND_REGISTER', 'jabber:iq:register'); class XEP_0077 extends XMPPXep { // // abstract method // public function init() { return array( ); } // // api methods // public function get_form_pkt($domain) { return $this->jaxl->get_iq_pkt( array('to'=>$domain, 'type'=>'get'), new JAXLXml('query', NS_INBAND_REGISTER) ); } public function get_form($domain) { $this->jaxl->send($this->get_form_pkt($domain)); } public function set_form($domain, $form) { $query = new JAXLXml('query', NS_INBAND_REGISTER); foreach($form as $k=>$v) $query->c($k, null, array(), $v)->up(); $pkt = $this->jaxl->get_iq_pkt( array('to'=>$domain, 'type'=>'set'), $query ); $this->jaxl->send($pkt); } - } - -?> diff --git a/xep/xep_0114.php b/xep/xep_0114.php index 0748e8d..7651225 100644 --- a/xep/xep_0114.php +++ b/xep/xep_0114.php @@ -1,95 +1,92 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_JABBER_COMPONENT_ACCEPT', 'jabber:component:accept'); class XEP_0114 extends XMPPXep { // // abstract method // public function init() { return array( 'on_connect' => 'start_stream', 'on_stream_start' => 'start_handshake', 'on_handshake_stanza' => 'logged_in', 'on_error_stanza' => 'logged_out' ); } // // event callbacks // public function start_stream() { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" to="'.$this->jaxl->jid->to_string().'" xmlns="'.NS_JABBER_COMPONENT_ACCEPT.'">'; $this->jaxl->send_raw($xml); } public function start_handshake($stanza) { _debug("starting component handshake"); $id = $stanza->id; $hash = strtolower(sha1($id.$this->jaxl->pass)); $stanza = new JAXLXml('handshake', null, $hash); $this->jaxl->send($stanza); } public function logged_in($stanza) { _debug("component handshake complete"); $this->jaxl->handle_auth_success(); return array("logged_in", 1); } public function logged_out($stanza) { if($stanza->name == "error" && $stanza->ns == NS_XMPP) { $reason = $stanza->childrens[0]->name; $this->jaxl->handle_auth_failure($reason); $this->jaxl->send_end_stream(); return array("logged_out", 0); } else { _debug("uncatched stanza received in logged_out"); } } - } - -?> diff --git a/xep/xep_0115.php b/xep/xep_0115.php index 80eefa9..281d620 100644 --- a/xep/xep_0115.php +++ b/xep/xep_0115.php @@ -1,73 +1,70 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_CAPS', 'http://jabber.org/protocol/caps'); class XEP_0115 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods // public function get_caps_pkt($cat, $type, $lang, $name, $node, $features) { asort($features); $S = $cat.'/'.$type.'/'.$lang.'/'.$name.'<'; foreach($features as $feature) $S .= $feature.'<'; $ver = base64_encode(sha1($S, true)); $stanza = new JAXLXml('c', NS_CAPS, array('hash'=>'sha1', 'node'=>$node, 'ver'=>$ver)); return $stanza; } // // event callbacks // - } - -?> diff --git a/xep/xep_0199.php b/xep/xep_0199.php index 34c6846..c33e60d 100644 --- a/xep/xep_0199.php +++ b/xep/xep_0199.php @@ -1,60 +1,57 @@ <?php require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_XMPP_PING', 'urn:xmpp:ping'); class XEP_0199 extends XMPPXep { // // abstract method // public function init() { return array( 'on_auth_success' => 'on_auth_success', 'on_get_iq' => 'on_xmpp_ping' ); } // // api methods // public function get_ping_pkt() { $attrs = array( 'type'=>'get', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$this->jaxl->full_jid->domain ); return $this->jaxl->get_iq_pkt( $attrs, new JAXLXml('ping', NS_XMPP_PING) ); } public function ping() { $this->jaxl->send($this->get_ping_pkt()); } // // event callbacks // public function on_auth_success() { JAXLLoop::$clock->call_fun_periodic(30 * pow(10,6), array(&$this, 'ping')); } public function on_xmpp_ping($stanza) { if($stanza->exists('ping', NS_XMPP_PING)) { $stanza->type = "result"; $stanza->to = $stanza->from; $stanza->from = $this->jaxl->full_jid->to_string(); $this->jaxl->send($stanza); } } - } - -?> diff --git a/xep/xep_0203.php b/xep/xep_0203.php index 7845d2c..bfb5f6d 100644 --- a/xep/xep_0203.php +++ b/xep/xep_0203.php @@ -1,63 +1,60 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DELAYED_DELIVERY', 'urn:xmpp:delay'); class XEP_0203 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods // // // event callbacks // - } - -?> diff --git a/xep/xep_0206.php b/xep/xep_0206.php index e3f5be2..07d3636 100644 --- a/xep/xep_0206.php +++ b/xep/xep_0206.php @@ -1,236 +1,233 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind'); define('NS_BOSH', 'urn:xmpp:xbosh'); class XEP_0206 extends XMPPXep { private $mch = null; public $chs = array(); private $recv_cb = null; public $rid = null; public $sid = null; private $hold = 1; private $wait = 30; private $restarted = false; public $headers = array( 'Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8' ); // // abstract method // public function init() { $this->mch = curl_multi_init(); return array( ); } // // event callbacks // public function send($body) { if(is_object($body)) { $body = $body->to_string(); } else { if(substr($body, 0, 15) == '<stream:stream ') { $this->restarted = true; $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'xmpp:restart' => 'true', 'xmlns:xmpp' => NS_BOSH )); $body = $body->to_string(); } else if(substr($body, 0, 16) == '</stream:stream>') { $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'type' => 'terminate' )); $body = $body->to_string(); } else { $body = $this->wrap($body); } } _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body); $this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']); curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers); curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false); curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1); curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body); curl_multi_add_handle($this->mch, $this->chs[$this->rid]); } public function recv() { if($this->restarted) { $this->restarted = false; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); } _debug("recving for $this->rid"); do { $ret = curl_multi_exec($this->mch, $running); $changed = curl_multi_select($this->mch, 0.1); if($changed == 0 && $running == 0) { $ch = @$this->chs[$this->rid]; if($ch) { $data = curl_multi_getcontent($ch); curl_multi_remove_handle($this->mch, $ch); unset($this->chs[$this->rid]); _debug("recvd for $this->rid ".$data); list($body, $stanza) = $this->unwrap($data); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if(@$attrs['type'] == 'terminate') { // fool me again if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); } else { if(!$this->sid) { $this->sid = $attrs['sid']; } if($this->recv_cb) call_user_func($this->recv_cb, $stanza); } } else { _error("no ch found"); exit; } } } while($running); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function wrap($stanza) { return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>'; } public function unwrap($body) { // a dirty way but it works efficiently if(substr($body, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); if(isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; else $envelop = "<body/>"; if(isset($m[2][0])) $payload = $m[2][0]; else $payload = ''; return array($envelop, $payload); } public function session_start() { $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000); $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold; $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); $attrs = array( 'content' => 'text/xml; charset=utf-8', 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'], 'secure' => 'true', 'xml:lang' => 'en', 'xmpp:version' => '1.0', 'xmlns:xmpp' => NS_BOSH, 'hold' => $this->hold, 'wait' => $this->wait, 'rid' => $this->rid, 'ver' => '1.10' ); if(@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; $body = new JAXLXml('body', NS_HTTP_BIND, $attrs); $this->send($body); } public function ping() { $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid)); $this->send($body); } public function session_end() { $this->disconnect(); } public function disconnect() { _debug("disconnecting"); } - } - -?> diff --git a/xep/xep_0249.php b/xep/xep_0249.php index f37130d..8108ab8 100644 --- a/xep/xep_0249.php +++ b/xep/xep_0249.php @@ -1,81 +1,78 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DIRECT_MUC_INVITATION', 'jabber:x:conference'); class XEP_0249 extends XMPPXep { // // abstract method // public function init() { return array(); } // // api methods // public function get_invite_pkt($to_bare_jid, $room_jid, $password=null, $reason=null, $thread=null, $continue=null) { $xattrs = array('jid'=>$room_jid); if($password) $xattrs['password'] = $password; if($reason) $xattrs['reason'] = $reason; if($thread) $xattrs['thread'] = $thread; if($continue) $xattrs['continue'] = $continue; return $this->jaxl->get_msg_pkt( array('from'=>$this->jaxl->full_jid->to_string(), 'to'=>$to_bare_jid), null, null, null, new JAXLXml('x', NS_DIRECT_MUC_INVITATION, $xattrs) ); } public function invite($to_bare_jid, $room_jid, $password=null, $reason=null, $thread=null, $continue=null) { $this->jaxl->send($this->get_invite_pkt($to_bare_jid, $room_jid, $password, $reason, $thread, $continue)); } // // event callbacks // - } - -?> diff --git a/xmpp/xmpp_iq.php b/xmpp/xmpp_iq.php index 9e47dd2..8dd0a02 100644 --- a/xmpp/xmpp_iq.php +++ b/xmpp/xmpp_iq.php @@ -1,49 +1,46 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; class XMPPIq extends XMPPStanza { public function __construct($attrs) { parent::__construct('iq', $attrs); } - } - -?> diff --git a/xmpp/xmpp_jid.php b/xmpp/xmpp_jid.php index 0b3835b..c122a5f 100644 --- a/xmpp/xmpp_jid.php +++ b/xmpp/xmpp_jid.php @@ -1,83 +1,80 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Xmpp Jid * * @author abhinavsingh * */ class XMPPJid { public $node = null; public $domain = null; public $resource = null; public $bare = null; public function __construct($str) { $tmp = explode("@", $str); if(sizeof($tmp) == 2) { $this->node = $tmp[0]; $tmp = explode("/", $tmp[1]); if(sizeof($tmp) == 2) { $this->domain = $tmp[0]; $this->resource = $tmp[1]; } else { $this->domain = $tmp[0]; } } else if(sizeof($tmp) == 1) { $this->domain = $tmp[0]; } $this->bare = $this->node ? $this->node."@".$this->domain : $this->domain; } public function to_string() { $str = ""; if($this->node) $str .= $this->node.'@'.$this->domain; else if($this->domain) $str .= $this->domain; if($this->resource) $str .= '/'.$this->resource; return $str; } - } - -?> diff --git a/xmpp/xmpp_msg.php b/xmpp/xmpp_msg.php index dc53534..1a190dd 100644 --- a/xmpp/xmpp_msg.php +++ b/xmpp/xmpp_msg.php @@ -1,53 +1,50 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; class XMPPMsg extends XMPPStanza { public function __construct($attrs, $body=null, $thread=null, $subject=null) { parent::__construct('message', $attrs); if($body) $this->c('body')->t($body)->up(); if($thread) $this->c('thread')->t($thread)->up(); if($subject) $this->c('subject')->t($subject)->up(); } - } - -?> diff --git a/xmpp/xmpp_nss.php b/xmpp/xmpp_nss.php index 0235ad6..cbebab2 100644 --- a/xmpp/xmpp_nss.php +++ b/xmpp/xmpp_nss.php @@ -1,62 +1,60 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // XML define('NS_XML_pfx', "xml"); define('NS_XML', 'http://www.w3.org/XML/1998/namespace'); // XMPP Core (RFC 3920) define('NS_XMPP_pfx', "stream"); define('NS_XMPP', 'http://etherx.jabber.org/streams'); define('NS_STREAM_ERRORS', 'urn:ietf:params:xml:ns:xmpp-streams'); define('NS_TLS', 'urn:ietf:params:xml:ns:xmpp-tls'); define('NS_SASL', 'urn:ietf:params:xml:ns:xmpp-sasl'); define('NS_BIND', 'urn:ietf:params:xml:ns:xmpp-bind'); define('NS_STANZA_ERRORS', 'urn:ietf:params:xml:ns:xmpp-stanzas'); // XMPP-IM (RFC 3921) define('NS_JABBER_CLIENT', 'jabber:client'); define('NS_JABBER_SERVER', 'jabber:server'); define('NS_SESSION', 'urn:ietf:params:xml:ns:xmpp-session'); define('NS_ROSTER', 'jabber:iq:roster'); // Stream Compression (XEP-0138) define('NS_COMPRESSION_FEATURE', 'http://jabber.org/features/compress'); define('NS_COMPRESSION_PROTOCOL', 'http://jabber.org/protocol/compress'); - -?> diff --git a/xmpp/xmpp_pres.php b/xmpp/xmpp_pres.php index a3645bd..92420d2 100644 --- a/xmpp/xmpp_pres.php +++ b/xmpp/xmpp_pres.php @@ -1,53 +1,50 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_stanza.php'; class XMPPPres extends XMPPStanza { public function __construct($attrs, $status=null, $show=null, $priority=null) { parent::__construct('presence', $attrs); if($status) $this->c('status')->t($status)->up(); if($show) $this->c('show')->t($show)->up(); if($priority) $this->c('priority')->t($priority)->up(); } - } - -?> diff --git a/xmpp/xmpp_roster_item.php b/xmpp/xmpp_roster_item.php index e36a9e1..ebd89a8 100644 --- a/xmpp/xmpp_roster_item.php +++ b/xmpp/xmpp_roster_item.php @@ -1,59 +1,56 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh */ class XMPPRosterItem { public $jid = null; public $subscription = null; public $groups = array(); public $resources = array(); public $vcard = null; public function __construct($jid, $subscription, $groups) { $this->jid = $jid; $this->subscription = $subscription; $this->groups = $groups; } - } - -?> diff --git a/xmpp/xmpp_stanza.php b/xmpp/xmpp_stanza.php index c967d57..dfbeefd 100644 --- a/xmpp/xmpp_stanza.php +++ b/xmpp/xmpp_stanza.php @@ -1,176 +1,173 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; /** * Generic xmpp stanza object which provide convinient access pattern over xml objects * Also to be able to convert an existing xml object into stanza object (to get access patterns going) * this class doesn't extend xml, but infact works on a reference of xml object * If not provided during constructor, new xml object is created and saved as reference * * @author abhinavsingh * */ class XMPPStanza { private $xml; public function __construct($name, $attrs=array(), $ns=NS_JABBER_CLIENT) { if($name instanceof JAXLXml) $this->xml = $name; else $this->xml = new JAXLXml($name, $ns, $attrs); } public function __call($method, $args) { return call_user_func_array(array($this->xml, $method), $args); } public function __get($prop) { switch($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': return @$this->xml->attrs[$prop] ? $this->xml->attrs[$prop] : null; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val = @$this->xml->attrs[$attr] ? $this->xml->attrs[$attr] : null; if(!$val) return null; $val = new XMPPJid($val); return $val->$key; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val = $this->xml->exists($prop); if(!$val) return null; return $val->text; break; default: return null; break; } } public function __set($prop, $val) { switch($prop) { // access to jaxl xml properties case 'name': case 'ns': case 'text': case 'attrs': case 'childrens': return $this->xml->$prop = $val; break; // access to common xml attributes case 'to': case 'from': case 'id': case 'type': $this->xml->attrs[$prop] = $val; return true; break; // access to parts of common xml attributes case 'to_node': case 'to_domain': case 'to_resource': case 'from_node': case 'from_domain': case 'from_resource': list($attr, $key) = explode('_', $prop); $val1 = @$this->xml->attrs[$attr]; if(!$val1) $val1 = ''; $val1 = new XMPPJid($val1); $val1->$key = $val; $this->xml->attrs[$attr] = $val1->to_string(); return true; break; // access to first child element text case 'status': case 'show': case 'priority': case 'body': case 'thread': case 'subject': $val1 = $this->xml->exists($prop); if(!$val1) $this->xml->c($prop)->t($val)->up(); else $this->xml->update($prop, $val1->ns, $val1->attrs, $val); return true; break; default: return null; break; } } - } - -?> diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index ac96a78..dddaca7 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -156,516 +156,513 @@ abstract class XMPPStream extends JAXLFsm { switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if(strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if(!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if(!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if(isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc'=>$nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach(array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if(isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if(!$msg->id) $msg->id = $this->get_id(); if($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if(!$pres->id) $pres->id = $this->get_id(); if($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if(!$iq->id) $iq->id = $this->get_id(); if($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach($data as $pair) { $dd = strpos($pair, '='); if($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } else if(strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach(array('realm', 'cnonce', 'digest-uri') as $key) if(!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if(isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } else if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } else if($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if($stanza->name == 'message') { $this->handle_message($stanza); } else if($stanza->name == 'presence') { $this->handle_presence($stanza); } else if($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } - } - -?> diff --git a/xmpp/xmpp_xep.php b/xmpp/xmpp_xep.php index bde1bbb..ea8e9d5 100644 --- a/xmpp/xmpp_xep.php +++ b/xmpp/xmpp_xep.php @@ -1,66 +1,63 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * @author abhinavsingh * */ abstract class XMPPXep { // init() method defines various callbacks // required by this xep extension abstract public function init(); //abstract public $description; //abstract public $dependencies; // reference to jaxl instance // which required me protected $jaxl = null; public function __construct($jaxl) { $this->jaxl = $jaxl; } public function __destruct() { } - } - -?>
jaxl/JAXL
c2c83fc2740cc490245e6ae43f3166b47a50863b
Add specific JAXL ruleset for PHP_CodeSniffer
diff --git a/phpcs/README.md b/phpcs/README.md new file mode 100644 index 0000000..79d998d --- /dev/null +++ b/phpcs/README.md @@ -0,0 +1,6 @@ +PHP_CodeSniffer +--------------- + +Install [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer) and run it from the project base folder: + + phpcs --standard=phpcs/jaxl --tab-width=4 ./ ./jaxlctl diff --git a/phpcs/jaxl/ruleset.xml b/phpcs/jaxl/ruleset.xml new file mode 100644 index 0000000..fb69df5 --- /dev/null +++ b/phpcs/jaxl/ruleset.xml @@ -0,0 +1,33 @@ +<?xml version="1.0"?> +<ruleset name="JAXL"> + <description>The JAXL coding standard (based on PSR-2 excluding some rules).</description> + + <!-- Include the whole PSR-2 standard --> + <rule ref="PSR2"/> + + <rule ref="Generic.Files.LineLength"> + <properties> + <property name="lineLimit" value="120"/> + </properties> + </rule> + + <!-- TODO: Rename XEP_NNNN classes then remove this rule. --> + <rule ref="Squiz.Classes.ValidClassName.NotCamelCaps"> + <severity>0</severity> + </rule> + + <!-- TODO: Move to PHP 5.3+ with namespaces then remove this rule. --> + <rule ref="PSR1.Classes.ClassDeclaration.MissingNamespace"> + <severity>0</severity> + </rule> + + <!-- TODO: Register autoload (spl_autoload_register), remove include and require everywhere then remove this rule. --> + <rule ref="PSR1.Files.SideEffects.FoundWithSymbols"> + <severity>0</severity> + </rule> + + <!-- TODO: Rename all methods then remove this rule. --> + <rule ref="PSR1.Methods.CamelCapsMethodName.NotCamelCaps"> + <severity>0</severity> + </rule> +</ruleset>
jaxl/JAXL
07d39634721a89c1b11e519b5b24242ac3453016
Fix examples to conform to requirements for PHP 5.2.4
diff --git a/docs/users/xmpp_examples.rst b/docs/users/xmpp_examples.rst index bb2e78e..5c9f931 100644 --- a/docs/users/xmpp_examples.rst +++ b/docs/users/xmpp_examples.rst @@ -1,120 +1,123 @@ XMPP Examples ============= Echo Bot Client --------------- include ``jaxl.php`` and initialize a new ``JAXL`` instance: .. code-block:: ruby require 'jaxl.php'; $client = new JAXL(array( 'jid' => '[email protected]', 'pass' => 'password' )); We just initialized a new ``JAXL`` instance by passing our jabber client ``jid`` and ``pass``. View list of :ref:`available options <jaxl-instance>` that can be passed to ``JAXL`` constructor. Next we need to register callbacks on events of interest using ``JAXL::add_cb/2`` method as shown below: .. code-block:: ruby - $client->add_cb('on_auth_success', function() { + function on_auth_success_callback() { global $client; $client->set_status("available!"); // set your status $client->get_vcard(); // fetch your vcard $client->get_roster(); // fetch your roster list - }); + } + $client->add_cb('on_auth_success', 'on_auth_success_callback'); - $client->add_cb('on_chat_message', function($msg) { + function on_chat_message_callback($stanza) { global $client; // echo back - $msg->to = $msg->from; - $msg->from = $client->full_jid->to_string(); - $client->send($msg); - }); + $stanza->to = $stanza->from; + $stanza->from = $client->full_jid->to_string(); + $client->send($stanza); + } + $client->add_cb('on_chat_message', 'on_chat_message_callback'); - $client->add_cb('on_disconnect', function() { + function on_disconnect_callback() { _debug("got on_disconnect cb"); - }); + } + $client->add_cb('on_disconnect', 'on_disconnect_callback'); We just registered callbacks on ``on_auth_success``, ``on_chat_message`` and ``on_disconnect`` events that will occur inside our configured ``JAXL`` instance lifecycle. We also passed a method that will be called (with parameters if any) when the event has been detected. See list of :ref:`available event callbacks <jaxl-instance>` that we can hook to inside ``JAXL`` instance lifecycle. Received ``$msg`` parameter with ``on_chat_message`` event callback above, will be an instance of ``XMPPMsg`` which extends ``XMPPStanza`` class, that allows us easy to use access patterns to common XMPP stanza attributes like ``to``, ``from``, ``type``, ``id`` to name a few. We were also able to access our xmpp client full jabber id by calling ``$client->full_jid``. This attribute of ``JAXL`` instance is available from ``on_auth_success`` event. ``full_jid`` attribute is an instance of ``XMPPJid``. To send our echo back ``$msg`` packet we called ``JAXL::send/1`` which accepts a single parameter which MUST be an instance of ``JAXLXml``. Since ``XMPPStanza`` is a wrapper upon ``JAXLXml`` we can very well pass our modified ``$msg`` object to the send method. Read more about various :ref:`XML Objects <xml-objects>` and how they make writing XMPP applications fun and easy. You can also :ref:`add custom access patterns <xml-objects>` upon received ``XMPPStanza`` objects. Since all access patterns are evaluated upon first access and cached for later usage, adding hundreds of custom access patterns that retrieves information from 100th child of received XML packet will not be an issue. We will finally start our xmpp client by calling: .. code-block:: ruby $client->start(); See list of :ref:`available options <jaxl-instance>` that can be passed to the ``JAXL::start/2`` method. These options are particularly useful for debugging and monitoring. Echo Bot BOSH Client -------------------- Everything goes same for a cli BOSH client. To run above echo bot client example as a bosh client simply pass additional parameters to ``JAXL`` constructor: .. code-block:: ruby require 'jaxl.php'; $client = new JAXL(array( 'jid' => '[email protected]', 'pass' => 'password', 'bosh_url' => 'http://localhost:5280/http-bind' )); You can even pass custom values for ``hold``, ``wait`` and other attributes. View list of :ref:`available options <jaxl-instance>` that can be passed to ``JAXL`` constructor. Echo Bot External Component --------------------------- Again almost everything goes same for an external component except a few custom ``JAXL`` constructor parameter as shown below: .. code-block:: ruby require_once 'jaxl.php'; $comp = new JAXL(array( // (required) component host and secret 'jid' => $argv[1], 'pass' => $argv[2], // (required) destination socket 'host' => $argv[3], 'port' => $argv[4] )); We will also need to include ``XEP0114`` which implements Jabber Component XMPP Extension. .. code-block:: ruby // (required) $comp->require_xep(array( '0114' // jabber component protocol )); ``JAXL::require_xep/1`` accepts an array of XEP numbers passed as strings. diff --git a/examples/echo_bosh_bot.php b/examples/echo_bosh_bot.php index b23665f..a5911d0 100644 --- a/examples/echo_bosh_bot.php +++ b/examples/echo_bosh_bot.php @@ -1,108 +1,112 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // (required) 'bosh_url' => 'http://localhost:5280/http-bind', // (optional) srv lookup is done if not provided // for bosh client 'host' value is used for 'route' attribute //'host' => 'xmpp.domain.tld', // (optional) result from srv lookup used by default // for bosh client 'port' value is used for 'route' attribute //'port' => 5222, // (optional) //'resource' => 'resource', // (optional) defaults to PLAIN if supported, else other methods will be automatically tried 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN', 'log_level' => JAXL_INFO )); // // add necessary event callbacks here // -$client->add_cb('on_auth_success', function() { - global $client; - _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); - $client->set_status("available!", "dnd", 10); -}); - -$client->add_cb('on_auth_failure', function($reason) { - global $client; - $client->send_end_stream(); - _info("got on_auth_failure cb with reason $reason"); -}); - -$client->add_cb('on_chat_message', function($stanza) { - global $client; - - // echo back incoming message stanza - $stanza->to = $stanza->from; - $stanza->from = $client->full_jid->to_string(); - $client->send($stanza); -}); - -$client->add_cb('on_disconnect', function() { +function on_auth_success_callback() { + global $client; + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); + $client->set_status("available!", "dnd", 10); +} +$client->add_cb('on_auth_success', 'on_auth_success_callback'); + +function on_auth_failure_callback($reason) { + global $client; + $client->send_end_stream(); + _info("got on_auth_failure cb with reason $reason"); +} +$client->add_cb('on_auth_failure', 'on_auth_failure_callback'); + +function on_chat_message_callback($stanza) { + global $client; + + // echo back incoming message stanza + $stanza->to = $stanza->from; + $stanza->from = $client->full_jid->to_string(); + $client->send($stanza); +} +$client->add_cb('on_chat_message', 'on_chat_message_callback'); + +function on_disconnect_callback() { _info("got on_disconnect cb"); -}); +} +$client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/examples/echo_bot.php b/examples/echo_bot.php index e9437f3..762565a 100644 --- a/examples/echo_bot.php +++ b/examples/echo_bot.php @@ -1,149 +1,155 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // Run as: // php examples/echo_bot.php root@localhost password // php examples/echo_bot.php root@localhost password DIGEST-MD5 // php examples/echo_bot.php localhost "" ANONYMOUS if($argc < 3) { echo "Usage: $argv[0] jid pass auth_type\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // (optional) srv lookup is done if not provided //'host' => 'xmpp.domain.tld', // (optional) result from srv lookup used by default //'port' => 5222, // (optional) defaults to false //'force_tls' => true, // (optional) //'resource' => 'resource', // (optional) defaults to PLAIN if supported, else other methods will be automatically tried 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN', 'log_level' => JAXL_INFO )); // // required XEP's // $client->require_xep(array( '0199' // XMPP Ping )); // // add necessary event callbacks here // -$client->add_cb('on_auth_success', function() { - global $client; - _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); +function on_auth_success_callback() { + global $client; + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); - // fetch roster list - $client->get_roster(); + // fetch roster list + $client->get_roster(); - // fetch vcard - $client->get_vcard(); + // fetch vcard + $client->get_vcard(); - // set status - $client->set_status("available!", "dnd", 10); -}); + // set status + $client->set_status("available!", "dnd", 10); +} +$client->add_cb('on_auth_success', 'on_auth_success_callback'); // by default JAXL instance catches incoming roster list results and updates // roster list is parsed/cached and an event 'on_roster_update' is emitted -$client->add_cb('on_roster_update', function() { +function on_roster_update_callback() { //global $client; //print_r($client->roster); -}); +} +$client->add_cb('on_roster_update', 'on_roster_update_callback'); -$client->add_cb('on_auth_failure', function($reason) { - global $client; - _info("got on_auth_failure cb with reason $reason"); - $client->send_end_stream(); -}); +function on_auth_failure_callback($reason) { + global $client; + $client->send_end_stream(); + _info("got on_auth_failure cb with reason $reason"); +} +$client->add_cb('on_auth_failure', 'on_auth_failure_callback'); -$client->add_cb('on_chat_message', function($stanza) { - global $client; +function on_chat_message_callback($stanza) { + global $client; - // echo back incoming chat message stanza - $stanza->to = $stanza->from; - $stanza->from = $client->full_jid->to_string(); - $client->send($stanza); -}); + // echo back incoming chat message stanza + $stanza->to = $stanza->from; + $stanza->from = $client->full_jid->to_string(); + $client->send($stanza); +} +$client->add_cb('on_chat_message', 'on_chat_message_callback'); -$client->add_cb('on_presence_stanza', function($stanza) { +function on_presence_stanza_callback($stanza) { global $client; $type = ($stanza->type ? $stanza->type : "available"); $show = ($stanza->show ? $stanza->show : "???"); _info($stanza->from." is now ".$type." ($show)"); if($type == "available") { // fetch vcard $client->get_vcard($stanza->from); } -}); +} +$client->add_cb('on_presence_stanza', 'on_presence_stanza_callback'); -$client->add_cb('on_disconnect', function() { +function on_disconnect_callback() { _info("got on_disconnect cb"); -}); +} +$client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(array( '--with-debug-shell' => true, '--with-unix-sock' => true )); echo "done\n"; ?> diff --git a/examples/echo_component_bot.php b/examples/echo_component_bot.php index c37cb52..215fb25 100644 --- a/examples/echo_component_bot.php +++ b/examples/echo_component_bot.php @@ -1,100 +1,104 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc != 5) { echo "Usage: $argv[0] jid pass host port\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $comp = new JAXL(array( // (required) component host and secret 'jid' => $argv[1], 'pass' => $argv[2], // (required) 'host' => @$argv[3], 'port' => $argv[4], 'log_level' => JAXL_INFO )); // // XEP's required (required) // $comp->require_xep(array( '0114' // jabber component protocol )); // // add necessary event callbacks here // -$comp->add_cb('on_auth_success', function() { - _info("got on_auth_success cb"); -}); +function on_auth_success_callback() { + _info("got on_auth_success cb"); +} +$comp->add_cb('on_auth_success', 'on_auth_success_callback'); -$comp->add_cb('on_auth_failure', function($reason) { - global $comp; - $comp->send_end_stream(); - _info("got on_auth_failure cb with reason $reason"); -}); +function on_auth_failure_callback($reason) { + global $comp; + $comp->send_end_stream(); + _info("got on_auth_failure cb with reason $reason"); +} +$comp->add_cb('on_auth_failure', 'on_auth_failure_callback'); -$comp->add_cb('on_chat_message', function($stanza) { - global $comp; +function on_chat_message_callback($stanza) { + global $comp; - // echo back incoming message stanza - $stanza->to = $stanza->from; - $stanza->from = $comp->jid->to_string(); - $comp->send($stanza); -}); + // echo back incoming message stanza + $stanza->to = $stanza->from; + $stanza->from = $comp->jid->to_string(); + $comp->send($stanza); +} +$comp->add_cb('on_chat_message', 'on_chat_message_callback'); -$comp->add_cb('on_disconnect', function() { +function on_disconnect_callback() { _info("got on_disconnect cb"); -}); +} +$comp->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $comp->start(); echo "done\n"; ?> diff --git a/examples/http_bind.php b/examples/http_bind.php index edfcffa..6ff6a73 100644 --- a/examples/http_bind.php +++ b/examples/http_bind.php @@ -1,66 +1,67 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if(!isset($_GET['jid']) || !isset($_GET['pass'])) { echo "invalid input"; exit; } // // initialize JAXL object with initial config // require_once '../jaxl.php'; $client = new JAXL(array( 'jid' => $_GET['jid'], 'pass' => $_GET['pass'], 'bosh_url' => 'http://localhost:5280/http-bind', 'log_level' => JAXL_DEBUG )); -$client->add_cb('on_auth_success', function() { - global $client; - _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); -}); +function on_auth_success_callback() { + global $client; + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); +} +$client->add_cb('on_auth_success', 'on_auth_success_callback'); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php index 66f163d..6058509 100644 --- a/examples/http_pre_bind.php +++ b/examples/http_pre_bind.php @@ -1,91 +1,93 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // http pre bind php script $body = file_get_contents("php://input"); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if(!@$attrs['to'] && !@$attrs['rid'] && !@$attrs['wait'] && !@$attrs['hold']) { echo "invalid input"; exit; } // // initialize JAXL object with initial config // require_once '../jaxl.php'; $to = (string)$attrs['to']; $rid = (int)$attrs['rid']; $wait = (int)$attrs['wait']; $hold = (int)$attrs['hold']; list($host, $port) = JAXLUtil::get_dns_srv($to); $client = new JAXL(array( 'domain' => $to, 'host' => $host, 'port' => $port, 'bosh_url' => 'http://localhost:5280/http-bind', 'bosh_rid' => $rid, 'bosh_wait' => $wait, 'bosh_hold' => $hold, 'auth_type' => 'ANONYMOUS', 'log_level' => JAXL_INFO )); -$client->add_cb('on_auth_success', function() { - global $client; - _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); - echo '<body xmlns="'.NS_HTTP_BIND.'" sid="'.$client->xeps['0206']->sid.'" rid="'.$client->xeps['0206']->rid.'" jid="'.$client->full_jid->to_string().'"/>'; - exit; -}); +function on_auth_success_callback() { + global $client; + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); + echo '<body xmlns="'.NS_HTTP_BIND.'" sid="'.$client->xeps['0206']->sid.'" rid="'.$client->xeps['0206']->rid.'" jid="'.$client->full_jid->to_string().'"/>'; + exit; +} +$client->add_cb('on_auth_success', 'on_auth_success_callback'); -$client->add_cb('on_auth_failure', function($reason) { - global $client; - _info("got on_auth_failure cb with reason $reason"); - $client->send_end_stream(); -}); +function on_auth_failure_callback($reason) { + global $client; + $client->send_end_stream(); + _info("got on_auth_failure cb with reason $reason"); +} +$client->add_cb('on_auth_failure', 'on_auth_failure_callback'); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index a4b192b..4701022 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,146 +1,151 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 5) { echo "Usage: $argv[0] host jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[2], 'pass' => $argv[3], 'host' => $argv[1], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC '0203', // Delayed Delivery '0199' // XMPP Ping )); // // add necessary event callbacks here // $_room_full_jid = $argv[4]."/".$argv[5]; $room_full_jid = new XMPPJid($_room_full_jid); -$client->add_cb('on_auth_success', function() { - global $client, $room_full_jid; - _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); - - // join muc room - $client->xeps['0045']->join_room($room_full_jid); -}); - -$client->add_cb('on_auth_failure', function($reason) { - global $client; - $client->send_end_stream(); - _info("got on_auth_failure cb with reason $reason"); -}); - -$client->add_cb('on_groupchat_message', function($stanza) { - global $client; +function on_auth_success_callback() { + global $client, $room_full_jid; + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); - $from = new XMPPJid($stanza->from); - $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); + // join muc room + $client->xeps['0045']->join_room($room_full_jid); +} +$client->add_cb('on_auth_success', 'on_auth_success_callback'); - if($from->resource) { - echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; - } - else { - $subject = $stanza->exists('subject'); - if($subject) { - echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; - } - } -}); +function on_auth_failure_callback($reason) { + global $client; + $client->send_end_stream(); + _info("got on_auth_failure cb with reason $reason"); +} +$client->add_cb('on_auth_failure', 'on_auth_failure_callback'); + +function on_groupchat_message_callback($stanza) { + global $client; + + $from = new XMPPJid($stanza->from); + $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); + + if($from->resource) { + echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; + } + else { + $subject = $stanza->exists('subject'); + if($subject) { + echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; + } + } +} +$client->add_cb('on_groupchat_message', 'on_chat_message_callback'); -$client->add_cb('on_presence_stanza', function($stanza) { +function on_presence_stanza_callback($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster if(strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { if(($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { if(($status = $x->exists('status', null, array('code'=>'110'))) !== false) { $item = $x->exists('item'); _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); } else { _info("xmlns #user have no x child element"); } } else { _warning("=======> odd case 1"); } } // stanza from other users received else if(strtolower($from->bare) == strtolower($room_full_jid->bare)) { if(($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; } else { _warning("=======> odd case 2"); } } else { _warning("=======> odd case 3"); } -}); +} +$client->add_cb('on_presence_stanza', 'on_presence_stanza_callback'); -$client->add_cb('on_disconnect', function() { +function on_disconnect_callback() { _info("got on_disconnect cb"); -}); +} +$client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/examples/pipes.php b/examples/pipes.php index 3607333..48052a1 100644 --- a/examples/pipes.php +++ b/examples/pipes.php @@ -1,59 +1,60 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // include jaxl pipes require_once JAXL_CWD.'/core/jaxl_pipe.php'; // initialize $pipe_name = getmypid(); $pipe = new JAXLPipe($pipe_name); // add read event callback -$pipe->set_callback(function($data) { - global $pipe; - _info("read ".trim($data)." from pipe"); -}); +function read_event_callback($data) { + global $pipe; + _info("read ".trim($data)." from pipe"); +} +$pipe->set_callback('read_event_callback'); JAXLLoop::run(); echo "done\n"; ?> diff --git a/examples/publisher.php b/examples/publisher.php index 9e9beeb..9891d35 100644 --- a/examples/publisher.php +++ b/examples/publisher.php @@ -1,99 +1,102 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // -$client->add_cb('on_auth_success', function() { - global $client; - _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); +function on_auth_success_callback() { + global $client; + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); - // create node - //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); + // create node + //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); - // publish - $item = new JAXLXml('item', null, array('id'=>time())); - $item->c('entry', 'http://www.w3.org/2005/Atom'); + // publish + $item = new JAXLXml('item', null, array('id'=>time())); + $item->c('entry', 'http://www.w3.org/2005/Atom'); - $item->c('title')->t('Soliloquy')->up(); - $item->c('summary')->t('To be, or not to be: that is the question')->up(); - $item->c('link', null, array('rel'=>'alternate', 'type'=>'text/html', 'href'=>'http://denmark.lit/2003/12/13/atom03'))->up(); - $item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up(); - $item->c('published')->t('2003-12-13T18:30:02Z')->up(); - $item->c('updated')->t('2003-12-13T18:30:02Z')->up(); + $item->c('title')->t('Soliloquy')->up(); + $item->c('summary')->t('To be, or not to be: that is the question')->up(); + $item->c('link', null, array('rel'=>'alternate', 'type'=>'text/html', 'href'=>'http://denmark.lit/2003/12/13/atom03'))->up(); + $item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up(); + $item->c('published')->t('2003-12-13T18:30:02Z')->up(); + $item->c('updated')->t('2003-12-13T18:30:02Z')->up(); - $client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item); -}); + $client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item); +} +$client->add_cb('on_auth_success', 'on_auth_success_callback'); -$client->add_cb('on_auth_failure', function($reason) { - global $client; - $client->send_end_stream(); - _info("got on_auth_failure cb with reason $reason"); -}); +function on_auth_failure_callback($reason) { + global $client; + $client->send_end_stream(); + _info("got on_auth_failure cb with reason $reason"); +} +$client->add_cb('on_auth_failure', 'on_auth_failure_callback'); -$client->add_cb('on_disconnect', function() { +function on_disconnect_callback() { _info("got on_disconnect cb"); -}); +} +$client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/examples/register_user.php b/examples/register_user.php index 947dc76..3c40d69 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,169 +1,172 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // $form = array(); function wait_for_register_response($event, $args) { global $client, $form; if($event == 'stanza_cb') { $stanza = $args[0]; if($stanza->name == 'iq') { $form['type'] = $stanza->attrs['type']; if($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } else if($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->send_end_stream(); return "logged_out"; } } } else { _notice("unhandled event $event rcvd"); } } function wait_for_register_form($event, $args) { global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if($query) { $instructions = $query->exists('instructions'); if($instructions) { echo $instructions->text.PHP_EOL; } foreach($query->childrens as $k=>$child) { if($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // -$client->add_cb('on_stream_features', function($stanza) { +function on_stream_features_callback($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; -}); +} +$client->add_cb('on_stream_features', 'on_stream_features_callback'); -$client->add_cb('on_disconnect', function() { +function on_disconnect_callback() { global $form; _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); -}); +} +$client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(); // // if registration was successful // try to connect with newly registered account // if($form['type'] == 'result') { _info("connecting newly registered user account"); $client = new JAXL(array( 'jid' => $form['username'].'@'.$argv[1], 'pass' => $form['password'], 'log_level' => JAXL_DEBUG )); -$client->add_cb('on_auth_success', function() { - global $client; - $client->set_status('Available'); -}); +function on_auth_success_callback() { + global $client; + $client->set_status('Available'); +} +$client->add_cb('on_auth_success', 'on_auth_success_callback'); $client->start(); } echo "done\n"; ?> diff --git a/examples/subscriber.php b/examples/subscriber.php index 69a3345..8bb6346 100644 --- a/examples/subscriber.php +++ b/examples/subscriber.php @@ -1,99 +1,103 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // -$client->add_cb('on_auth_success', function() { - global $client; - _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); +function on_auth_success_callback() { + global $client; + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); - // create node - //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); + // create node + //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); - // subscribe - $client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node'); -}); + // subscribe + $client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node'); +} +$client->add_cb('on_auth_success', 'on_auth_success_callback'); -$client->add_cb('on_auth_failure', function($reason) { - global $client; - $client->send_end_stream(); - _info("got on_auth_failure cb with reason $reason"); -}); +function on_auth_failure_callback($reason) { + global $client; + $client->send_end_stream(); + _info("got on_auth_failure cb with reason $reason"); +} +$client->add_cb('on_auth_failure', 'on_auth_failure_callback'); -$client->add_cb('on_headline_message', function($stanza) { +function on_headline_message_callback($stanza) { global $client; if(($event = $stanza->exists('event', NS_PUBSUB.'#event'))) { _info("got pubsub event"); } else { _warning("unknown headline message rcvd"); } -}); +} +$client->add_cb('on_headline_message', 'on_headline_message_callback'); -$client->add_cb('on_disconnect', function() { +function on_disconnect_callback() { _info("got on_disconnect cb"); -}); +} +$client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/examples/xfacebook_platform_client.php b/examples/xfacebook_platform_client.php index 76ae7e3..1ba26ac 100644 --- a/examples/xfacebook_platform_client.php +++ b/examples/xfacebook_platform_client.php @@ -1,100 +1,104 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc != 4) { echo "Usage: $argv[0] fb_user_id_or_username fb_app_key fb_access_token\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1].'@chat.facebook.com', 'fb_app_key' => $argv[2], 'fb_access_token' => $argv[3], // force tls (facebook require this now) 'force_tls' => true, // (required) force facebook oauth 'auth_type' => 'X-FACEBOOK-PLATFORM', // (optional) //'resource' => 'resource', 'log_level' => JAXL_INFO )); // // add necessary event callbacks here // -$client->add_cb('on_auth_success', function() { - global $client; - _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); - $client->set_status("available!", "dnd", 10); -}); +function on_auth_success_callback() { + global $client; + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); + $client->set_status("available!", "dnd", 10); +} +$client->add_cb('on_auth_success', 'on_auth_success_callback'); -$client->add_cb('on_auth_failure', function($reason) { - global $client; - $client->send_end_stream(); - _info("got on_auth_failure cb with reason $reason"); -}); +function on_auth_failure_callback($reason) { + global $client; + $client->send_end_stream(); + _info("got on_auth_failure cb with reason $reason"); +} +$client->add_cb('on_auth_failure', 'on_auth_failure_callback'); -$client->add_cb('on_chat_message', function($stanza) { - global $client; +function on_chat_message_callback($stanza) { + global $client; - // echo back incoming message stanza - $stanza->to = $stanza->from; - $stanza->from = $client->full_jid->to_string(); - $client->send($stanza); -}); + // echo back incoming message stanza + $stanza->to = $stanza->from; + $stanza->from = $client->full_jid->to_string(); + $client->send($stanza); +} +$client->add_cb('on_chat_message', 'on_chat_message_callback'); -$client->add_cb('on_disconnect', function() { +function on_disconnect_callback() { _info("got on_disconnect cb"); -}); +} +$client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/examples/xmpp_rest.php b/examples/xmpp_rest.php index 0e052c6..1451e04 100644 --- a/examples/xmpp_rest.php +++ b/examples/xmpp_rest.php @@ -1,77 +1,79 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // View explanation for this example here: // https://groups.google.com/d/msg/jaxl/QaGjZP4A2gY/n6SYutrBVxsJ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // initialize xmpp client require_once 'jaxl.php'; $xmpp = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); // register callbacks on required xmpp events -$xmpp->add_cb('on_auth_success', function() { - global $xmpp; - _info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string()); -}); +function on_auth_success_callback() { + global $xmpp; + _info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string()); +} +$xmpp->add_cb('on_auth_success', 'on_auth_success_callback'); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); // add generic callback // you can also dispatch REST style callback // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules -$http->cb = function($request) { - // For demo purposes we simply return xmpp client full jid - global $xmpp; - $request->ok($xmpp->full_jid->to_string()); -}; +function generic_callback($request) { + // For demo purposes we simply return xmpp client full jid + global $xmpp; + $request->ok($xmpp->full_jid->to_string()); +} +$http->cb = 'generic_callback'; // This will start main JAXLLoop, // hence we don't need to call $http->start() explicitly $xmpp->start(); ?> diff --git a/examples/xoauth2_gtalk_client.php b/examples/xoauth2_gtalk_client.php index 8a5d6cb..ce2c61e 100644 --- a/examples/xoauth2_gtalk_client.php +++ b/examples/xoauth2_gtalk_client.php @@ -1,99 +1,103 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc != 3) { echo "Usage: $argv[0] jid access_token\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // force tls 'force_tls' => true, // (required) perform X-OAUTH2 'auth_type' => 'X-OAUTH2', // (optional) //'resource' => 'resource', 'log_level' => JAXL_DEBUG )); // // add necessary event callbacks here // -$client->add_cb('on_auth_success', function() { - global $client; - _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); - $client->set_status("available!", "dnd", 10); -}); +function on_auth_success_callback() { + global $client; + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); + $client->set_status("available!", "dnd", 10); +} +$client->add_cb('on_auth_success', 'on_auth_success_callback'); -$client->add_cb('on_auth_failure', function($reason) { - global $client; - $client->send_end_stream(); - _info("got on_auth_failure cb with reason $reason"); -}); +function on_auth_failure_callback($reason) { + global $client; + $client->send_end_stream(); + _info("got on_auth_failure cb with reason $reason"); +} +$client->add_cb('on_auth_failure', 'on_auth_failure_callback'); -$client->add_cb('on_chat_message', function($stanza) { - global $client; +function on_chat_message_callback($stanza) { + global $client; - // echo back incoming message stanza - $stanza->to = $stanza->from; - $stanza->from = $client->full_jid->to_string(); - $client->send($stanza); -}); + // echo back incoming message stanza + $stanza->to = $stanza->from; + $stanza->from = $client->full_jid->to_string(); + $client->send($stanza); +} +$client->add_cb('on_chat_message', 'on_chat_message_callback'); -$client->add_cb('on_disconnect', function() { +function on_disconnect_callback() { _info("got on_disconnect cb"); -}); +} +$client->add_cb('on_disconnect', 'on_disconnect_callback'); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?>
jaxl/JAXL
6137802b8d6300d9235e3660c003b3253369a220
Add protocol configuration to use it
diff --git a/jaxl.php b/jaxl.php index 81748e0..f529a07 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,809 +1,812 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { $this->cfg = $config; // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { - return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; + $protocol = ($this->cfg['port'] == 5223 ? "ssl" : "tcp"); + if ($this->cfg['protocol']) + $protocol = $this->cfg['protocol']; + return $protocol."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?>
jaxl/JAXL
37742270015a563e7035f49dbf8c5a9adf69461f
allow / and @ characters in jid resource
diff --git a/xmpp/xmpp_jid.php b/xmpp/xmpp_jid.php index 806499f..1a92af3 100644 --- a/xmpp/xmpp_jid.php +++ b/xmpp/xmpp_jid.php @@ -1,83 +1,83 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Xmpp Jid * * @author abhinavsingh * */ class XMPPJid { public $node = null; public $domain = null; public $resource = null; public $bare = null; public function __construct($str) { - $tmp = explode("@", $str); + $tmp = explode("@", $str, 2); if(sizeof($tmp) == 2) { $this->node = $tmp[0]; - $tmp = explode("/", $tmp[1]); + $tmp = explode("/", $tmp[1], 2); if(sizeof($tmp) == 2) { $this->domain = $tmp[0]; $this->resource = $tmp[1]; } else { $this->domain = $tmp[0]; } } else if(sizeof($tmp) == 1) { $this->domain = $tmp[0]; } $this->bare = $this->node ? $this->node."@".$this->domain : $this->domain; } public function to_string() { $str = ""; if($this->node) $str .= $this->node.'@'.$this->domain; else if($this->domain) $str .= $this->domain; if($this->resource) $str .= '/'.$this->resource; return $str; } } ?>
jaxl/JAXL
0f857529627ad4761910e8332a48fe6b9e36f4fd
Composer bin support
diff --git a/composer.json b/composer.json index aa3aa45..78c3829 100644 --- a/composer.json +++ b/composer.json @@ -1,23 +1,24 @@ { "name": "abhinavsingh/jaxl", "type": "library", "description": "Jaxl - Async, Non-Blocking, Event based Networking Library in PHP.", "keywords": ["xmpp", "jabber", "http", "asynchronous", "non blocking", "event loop", "php", "jaxl", "abhinavsingh"], "homepage": "http://jaxl.readthedocs.org/en/latest/index.html", "license": "MIT", "authors": [ { "name": "Abhinavsingh", "homepage": "https://abhinavsingh.com/" } ], "require": { "php": ">=5.2.4" }, "autoload": { "files": ["jaxl.php"] - } + }, + "bin": ["jaxlctl"] } \ No newline at end of file
jaxl/JAXL
b6b1dde10cd3fe11520023dc11ab54776ca282c4
fix Call-time pass-by-reference
diff --git a/jaxlctl b/jaxlctl index b7415a3..a1f1b95 100755 --- a/jaxlctl +++ b/jaxlctl @@ -1,190 +1,190 @@ #!/usr/bin/env php <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ $params = $argv; $exe = array_shift($params); $command = array_shift($params); require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // TODO: an abstract JAXLCtlCommand class // with seperate class per command // a mechanism to register new commands class JAXLCtl { protected $ipc = null; protected $buffer = ''; protected $buffer_cb = null; protected $cli = null; public $dots = "....... "; protected $symbols = array(); public function __construct($command, $params) { global $exe; - if(method_exists(&$this, $command)) { + if(method_exists($this, $command)) { $r = call_user_func_array(array(&$this, $command), $params); if(sizeof($r) == 2) { list($buffer_cb, $quit_cb) = $r; $this->buffer_cb = $buffer_cb; $this->cli = new JAXLCli(array(&$this, 'on_terminal_input'), $quit_cb); $this->run(); } else { _colorize("oops! internal command error", JAXL_ERROR); exit; } } else { _colorize("error: invalid command '$command' received", JAXL_ERROR); _colorize("type '$exe help' for list of available commands", JAXL_NOTICE); exit; } } public function run() { JAXLCli::prompt(); JAXLLoop::run(); } public function on_terminal_input($raw) { $raw = trim($raw); $last = substr($raw, -1, 1); if($last == ";") { // dispatch to buffer callback call_user_func($this->buffer_cb, $this->buffer.$raw); $this->buffer = ''; } else if($last == '\\') { $this->buffer .= substr($raw, 0, -1); echo $this->dots; } else { // buffer command $this->buffer .= $raw."; "; echo $this->dots; } } public static function print_help() { global $exe; _colorize("Usage: $exe command [options...]\n", JAXL_INFO); _colorize("Commands:", JAXL_NOTICE); _colorize(" help This help text", JAXL_DEBUG); _colorize(" debug Attach a debug console to a running JAXL daemon", JAXL_DEBUG); _colorize(" shell Open up Jaxl shell emulator", JAXL_DEBUG); echo "\n"; } protected function help() { JAXLCtl::print_help(); exit; } // // shell command // protected function shell() { return array(array(&$this, 'on_shell_input'), array(&$this, 'on_shell_quit')); } private function _eval($raw, $symbols) { extract($symbols); eval($raw); $g = get_defined_vars(); unset($g['raw']); unset($g['symbols']); return $g; } public function on_shell_input($raw) { $this->symbols = $this->_eval($raw, $this->symbols); JAXLCli::prompt(); } public function on_shell_quit() { exit; } // // debug command // protected function debug($sock_path) { $this->ipc = new JAXLSocketClient(); $this->ipc->set_callback(array(&$this, 'on_debug_response')); $this->ipc->connect('unix://'.$sock_path); return array(array(&$this, 'on_debug_input'), array(&$this, 'on_debug_quit')); } public function on_debug_response($raw) { $ret = unserialize($raw); print_r($ret); echo "\n"; JAXLCli::prompt(); } public function on_debug_input($raw) { $this->ipc->send($this->buffer.$raw); } public function on_debug_quit() { $this->ipc->disconnect(); exit; } } // we atleast need a command argument if($argc < 2) { JAXLCtl::print_help(); exit; } $ctl = new JAXLCtl($command, $params); echo "done\n"; ?>
jaxl/JAXL
e1b0f5ef69e2bd49417e3dba289269b57e59616e
Fix usage of curl_multi_*
diff --git a/xep/xep_0206.php b/xep/xep_0206.php index 8f0e79e..6d0a1da 100644 --- a/xep/xep_0206.php +++ b/xep/xep_0206.php @@ -1,236 +1,242 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind'); define('NS_BOSH', 'urn:xmpp:xbosh'); class XEP_0206 extends XMPPXep { private $mch = null; public $chs = array(); private $recv_cb = null; public $rid = null; public $sid = null; private $hold = 1; private $wait = 30; private $restarted = false; public $headers = array( 'Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8' ); // // abstract method // public function init() { $this->mch = curl_multi_init(); return array( ); } // // event callbacks // public function send($body) { if(is_object($body)) { $body = $body->to_string(); } else { if(substr($body, 0, 15) == '<stream:stream ') { $this->restarted = true; $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'xmpp:restart' => 'true', 'xmlns:xmpp' => NS_BOSH )); $body = $body->to_string(); } else if(substr($body, 0, 16) == '</stream:stream>') { $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'type' => 'terminate' )); $body = $body->to_string(); } else { $body = $this->wrap($body); } } _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body); $this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']); curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers); curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false); curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1); curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body); curl_multi_add_handle($this->mch, $this->chs[$this->rid]); } public function recv() { if($this->restarted) { $this->restarted = false; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); } _debug("recving for $this->rid"); do { - $ret = curl_multi_exec($this->mch, $running); - $changed = curl_multi_select($this->mch, 0.1); + $mrc = curl_multi_exec($this->mch, $running); + _debug("mrc=$mrc running=$running"); + } while ($mrc == CURLM_CALL_MULTI_PERFORM); + while ($running && $mrc == CURLM_OK) { + $ms = curl_multi_select($this->mch, 0.1); + if ($ms != -1) { + do { + $mrc = curl_multi_exec($this->mch, $running); + } while ($mrc == CURLM_CALL_MULTI_PERFORM); + } + } + + $ch = @$this->chs[$this->rid]; + if($ch) { + $data = curl_multi_getcontent($ch); - if($changed == 0 && $running == 0) { - $ch = @$this->chs[$this->rid]; - if($ch) { - $data = curl_multi_getcontent($ch); - - curl_multi_remove_handle($this->mch, $ch); - unset($this->chs[$this->rid]); - _debug("recvd for $this->rid ".$data); - - list($body, $stanza) = $this->unwrap($data); - $body = new SimpleXMLElement($body); - $attrs = $body->attributes(); - - if(@$attrs['type'] == 'terminate') { - // fool me again - if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); - } - else { - if(!$this->sid) { - $this->sid = $attrs['sid']; - } - - if($this->recv_cb) call_user_func($this->recv_cb, $stanza); - } - } - else { - _error("no ch found"); - exit; + curl_multi_remove_handle($this->mch, $ch); + unset($this->chs[$this->rid]); + _debug("recvd for $this->rid ".$data); + + list($body, $stanza) = $this->unwrap($data); + $body = new SimpleXMLElement($body); + $attrs = $body->attributes(); + + if(@$attrs['type'] == 'terminate') { + // fool me again + if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); + } + else { + if(!$this->sid) { + $this->sid = $attrs['sid']; } + + if($this->recv_cb) call_user_func($this->recv_cb, $stanza); } - } while($running); + } + else { + _error("no ch found"); + exit; + } } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function wrap($stanza) { return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>'; } public function unwrap($body) { // a dirty way but it works efficiently if(substr($body, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); if(isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; else $envelop = "<body/>"; if(isset($m[2][0])) $payload = $m[2][0]; else $payload = ''; return array($envelop, $payload); } public function session_start() { $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000); $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold; $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); $attrs = array( 'content' => 'text/xml; charset=utf-8', 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'], 'secure' => 'true', 'xml:lang' => 'en', 'xmpp:version' => '1.0', 'xmlns:xmpp' => NS_BOSH, 'hold' => $this->hold, 'wait' => $this->wait, 'rid' => $this->rid, 'ver' => '1.10' ); if(@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; $body = new JAXLXml('body', NS_HTTP_BIND, $attrs); $this->send($body); } public function ping() { $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid)); $this->send($body); } public function session_end() { $this->disconnect(); } public function disconnect() { _debug("disconnecting"); } } ?>
jaxl/JAXL
f8e6f0d825f927133e05fde7b7b6ee94e3836f3e
Fixed unwrap funciton in BOSH module (XEP 0206)
diff --git a/xep/xep_0206.php b/xep/xep_0206.php index e5f61c1..8f0e79e 100644 --- a/xep/xep_0206.php +++ b/xep/xep_0206.php @@ -1,236 +1,236 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind'); define('NS_BOSH', 'urn:xmpp:xbosh'); class XEP_0206 extends XMPPXep { private $mch = null; public $chs = array(); private $recv_cb = null; public $rid = null; public $sid = null; private $hold = 1; private $wait = 30; private $restarted = false; public $headers = array( 'Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8' ); // // abstract method // public function init() { $this->mch = curl_multi_init(); return array( ); } // // event callbacks // public function send($body) { if(is_object($body)) { $body = $body->to_string(); } else { if(substr($body, 0, 15) == '<stream:stream ') { $this->restarted = true; $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'xmpp:restart' => 'true', 'xmlns:xmpp' => NS_BOSH )); $body = $body->to_string(); } else if(substr($body, 0, 16) == '</stream:stream>') { $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'type' => 'terminate' )); $body = $body->to_string(); } else { $body = $this->wrap($body); } } _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body); $this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']); curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers); curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false); curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1); curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body); curl_multi_add_handle($this->mch, $this->chs[$this->rid]); } public function recv() { if($this->restarted) { $this->restarted = false; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); } _debug("recving for $this->rid"); do { $ret = curl_multi_exec($this->mch, $running); $changed = curl_multi_select($this->mch, 0.1); if($changed == 0 && $running == 0) { $ch = @$this->chs[$this->rid]; if($ch) { $data = curl_multi_getcontent($ch); curl_multi_remove_handle($this->mch, $ch); unset($this->chs[$this->rid]); _debug("recvd for $this->rid ".$data); list($body, $stanza) = $this->unwrap($data); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if(@$attrs['type'] == 'terminate') { // fool me again if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); } else { if(!$this->sid) { $this->sid = $attrs['sid']; } if($this->recv_cb) call_user_func($this->recv_cb, $stanza); } } else { _error("no ch found"); exit; } } } while($running); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function wrap($stanza) { return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>'; } public function unwrap($body) { // a dirty way but it works efficiently - if(substr($body -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); + if(substr($body, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); if(isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; else $envelop = "<body/>"; if(isset($m[2][0])) $payload = $m[2][0]; else $payload = ''; return array($envelop, $payload); } public function session_start() { $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000); $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold; $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); $attrs = array( 'content' => 'text/xml; charset=utf-8', 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'], 'secure' => 'true', 'xml:lang' => 'en', 'xmpp:version' => '1.0', 'xmlns:xmpp' => NS_BOSH, 'hold' => $this->hold, 'wait' => $this->wait, 'rid' => $this->rid, 'ver' => '1.10' ); if(@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; $body = new JAXLXml('body', NS_HTTP_BIND, $attrs); $this->send($body); } public function ping() { $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid)); $this->send($body); } public function session_end() { $this->disconnect(); } public function disconnect() { _debug("disconnecting"); } } ?>
jaxl/JAXL
e5b53b42fb524dd3a34dfbb139f0497c93d35eaf
fixes #26
diff --git a/jaxl.php b/jaxl.php index 764c5d9..81748e0 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,703 +1,706 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { - // env $this->cfg = $config; + + // setup logger + if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; + //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; + if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; + else JAXLLogger::$level = $this->log_level; + + // env $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); - // setup logger - if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; - //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; - if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; - else JAXLLogger::$level = $this->log_level; - // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified - $host = @$this->cfg['host']; $port = @$this->cfg['port'] ? $this->cfg['port'] : 5222; - if(!$host && !$port && $jid) { + $host = @$this->cfg['host']; + $port = @$this->cfg['port']; + if((!$host || !$port) && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } - $this->cfg['host'] = $host; $this->cfg['port'] = $port; + $this->cfg['host'] = @$this->cfg['host'] ? $this->cfg['host'] : $host; + $this->cfg['port'] = @$this->cfg['port'] ? $this->cfg['port'] : $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { - list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); + //list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text;
jaxl/JAXL
5b848a25f7a68e9bef98d0bdee3a7c802c0cb543
Fixed examples/muc_log_bot.php - setting host in a script argument
diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index 25f8e66..1c0ec3f 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,145 +1,146 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 5) { - echo "Usage: $argv[0] jid pass [email protected] nickname\n"; + echo "Usage: $argv[0] host jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials - 'jid' => $argv[1], - 'pass' => $argv[2], + 'jid' => $argv[2], + 'pass' => $argv[3], + 'host' => $argv[1], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC '0203', // Delayed Delivery '0199' // XMPP Ping )); // // add necessary event callbacks here // -$_room_full_jid = $argv[3]."/".$argv[4]; +$_room_full_jid = $argv[4]."/".$argv[5]; $room_full_jid = new XMPPJid($_room_full_jid); $client->add_cb('on_auth_success', function() { global $client, $room_full_jid; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // join muc room $client->xeps['0045']->join_room($room_full_jid); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_groupchat_message', function($stanza) { global $client; $from = new XMPPJid($stanza->from); $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); if($from->resource) { echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } else { $subject = $stanza->exists('subject'); if($subject) { echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } } }); $client->add_cb('on_presence_stanza', function($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster if(strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { if(($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { if(($status = $x->exists('status', null, array('code'=>'110'))) !== false) { $item = $x->exists('item'); _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); } else { _info("xmlns #user have no x child element"); } } else { _warning("=======> odd case 1"); } } // stanza from other users received else if(strtolower($from->bare) == strtolower($room_full_jid->bare)) { if(($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; } else { _warning("=======> odd case 2"); } } else { _warning("=======> odd case 3"); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?>
jaxl/JAXL
da995658281f9527caa1616644203659246a93b3
Joining MUC without receiving discussion history
diff --git a/xep/xep_0045.php b/xep/xep_0045.php index 32aea4e..90cd013 100644 --- a/xep/xep_0045.php +++ b/xep/xep_0045.php @@ -1,110 +1,114 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_MUC', 'http://jabber.org/protocol/muc'); class XEP_0045 extends XMPPXep { // // abstract method // public function init() { return array(); } public function send_groupchat($room_jid, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'groupchat', 'to'=>(($room_jid instanceof XMPPJid) ? $room_jid->to_string() : $room_jid), 'from'=>$this->jaxl->full_jid->to_string() ), $body, $thread, $subject ); $this->jaxl->send($msg); } // // api methods (occupant use case) // // room_full_jid simply means room jid with nick name as resource - public function get_join_room_pkt($room_full_jid) { + public function get_join_room_pkt($room_full_jid, $options) { $pkt = $this->jaxl->get_pres_pkt( array( 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid) ) ); - return $pkt->c('x', NS_MUC); + $x = $pkt->c('x', NS_MUC); + if (isset($options['no_history'])) { + $x->c('history')->attrs(array('maxstanzas' => 0, 'seconds' => 0)); + } + return $x; } - public function join_room($room_full_jid) { - $pkt = $this->get_join_room_pkt($room_full_jid); + public function join_room($room_full_jid, $options = array()) { + $pkt = $this->get_join_room_pkt($room_full_jid, $options); $this->jaxl->send($pkt); } public function get_leave_room_pkt($room_full_jid) { return $this->jaxl->get_pres_pkt( array('type'=>'unavailable', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>(($room_full_jid instanceof XMPPJid) ? $room_full_jid->to_string() : $room_full_jid)) ); } public function leave_room($room_full_jid) { $pkt = $this->get_leave_room_pkt($room_full_jid); $this->jaxl->send($pkt); } // // api methods (moderator use case) // // // event callbacks // } ?>
jaxl/JAXL
254518a06883203b7a61312657db6428c46de134
restored composer.json SHA-4e8fd3e
diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..aa3aa45 --- /dev/null +++ b/composer.json @@ -0,0 +1,23 @@ +{ + "name": "abhinavsingh/jaxl", + "type": "library", + "description": "Jaxl - Async, Non-Blocking, Event based Networking Library in PHP.", + "keywords": ["xmpp", "jabber", "http", "asynchronous", "non blocking", "event loop", "php", "jaxl", "abhinavsingh"], + "homepage": "http://jaxl.readthedocs.org/en/latest/index.html", + "license": "MIT", + + "authors": [ + { + "name": "Abhinavsingh", + "homepage": "https://abhinavsingh.com/" + } + ], + + "require": { + "php": ">=5.2.4" + }, + + "autoload": { + "files": ["jaxl.php"] + } +} \ No newline at end of file
jaxl/JAXL
af93d9ade9e9b68ce9b73628718ca4ba0b91b90b
fixes #22
diff --git a/examples/multi_client.php b/examples/multi_client.php new file mode 100644 index 0000000..a7bb1f4 --- /dev/null +++ b/examples/multi_client.php @@ -0,0 +1,129 @@ +<?php +/** + * Jaxl (Jabber XMPP Library) + * + * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Abhinav Singh nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +// enable multi client support +// this will force 1st parameter of callbacks +// as connected client instance +define('JAXL_MULTI_CLIENT', true); + +// input multiple account credentials +$accounts = array(); +$add_new = TRUE; +while($add_new) { + $jid = readline('Enter Jabber Id: '); + $pass = readline('Enter Password: '); + $accounts[] = array($jid, $pass); + $next = readline('Add another account (y/n): '); + $add_new = $next == 'y' ? TRUE : FALSE; +} + +// setup jaxl +require_once 'jaxl.php'; + +// +// common callbacks +// + +function on_auth_success($client) { + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); + + // fetch roster list + $client->get_roster(); + + // fetch vcard + $client->get_vcard(); + + // set status + $client->set_status("available!", "dnd", 10); +} + +function on_auth_failure($client, $reason) { + _info("got on_auth_failure cb with reason $reason"); + $client->send_end_stream(); +} + +function on_chat_message($client, $stanza) { + // echo back incoming chat message stanza + $stanza->to = $stanza->from; + $stanza->from = $client->full_jid->to_string(); + $client->send($stanza); +} + +function on_presence_stanza($client, $stanza) { + global $client; + + $type = ($stanza->type ? $stanza->type : "available"); + $show = ($stanza->show ? $stanza->show : "???"); + _info($stanza->from." is now ".$type." ($show)"); + + if($type == "available") { + // fetch vcard + $client->get_vcard($stanza->from); + } +} + +function on_disconnect($client) { + _info("got on_disconnect cb"); +} + +// +// bootstrap all account instances +// + +foreach($accounts as $account) { + $client = new JAXL(array( + 'jid' => $account[0], + 'pass' => $account[1], + 'log_level' => JAXL_DEBUG + )); + + $client->add_cb('on_auth_success', 'on_auth_success'); + $client->add_cb('on_auth_failure', 'on_auth_failure'); + $client->add_cb('on_chat_message', 'on_chat_message'); + $client->add_cb('on_presence_stanza', 'on_presence_stanza'); + $client->add_cb('on_disconnect', 'on_disconnect'); + + $client->connect($client->get_socket_path()); + $client->start_stream(); +} + +// start core loop +JAXLLoop::run(); +echo "done\n"; + +?>
jaxl/JAXL
4cc203ea62887eededf43276296265fd5658d2c0
fixes #23
diff --git a/examples/register_user.php b/examples/register_user.php index 4fbc950..dc716d9 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,138 +1,169 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], - 'log_level' => JAXL_INFO + 'log_level' => JAXL_DEBUG )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // +$form = array(); + function wait_for_register_response($event, $args) { - global $client; + global $client, $form; - if($event == 'end_stream') { - exit; - } - else if($event == 'stanza_cb') { + if($event == 'stanza_cb') { $stanza = $args[0]; if($stanza->name == 'iq') { + $form['type'] = $stanza->attrs['type']; if($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; - $client->end_stream(); + $client->send_end_stream(); return "logged_out"; } else if($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; - $client->end_stream(); + $client->send_end_stream(); return "logged_out"; } } } + else { + _notice("unhandled event $event rcvd"); + } } function wait_for_register_form($event, $args) { - global $client; + global $client, $form; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if($query) { - $form = array(); $instructions = $query->exists('instructions'); if($instructions) { echo $instructions->text.PHP_EOL; } foreach($query->childrens as $k=>$child) { if($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); + } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // $client->add_cb('on_stream_features', function($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; }); +$client->add_cb('on_disconnect', function() { + global $form; + _info("registration " . ($form['type'] == 'result' ? 'succeeded' : 'failed')); +}); + // // finally start configured xmpp stream // $client->start(); + +// +// if registration was successful +// try to connect with newly registered account +// +if($form['type'] == 'result') { + +_info("connecting newly registered user account"); +$client = new JAXL(array( + 'jid' => $form['username'].'@'.$argv[1], + 'pass' => $form['password'], + 'log_level' => JAXL_DEBUG +)); + +$client->add_cb('on_auth_success', function() { + global $client; + $client->set_status('Available'); +}); + +$client->start(); + +} + echo "done\n"; ?>
jaxl/JAXL
b626cd8d545bc03ad4f8b1ec959a150fdd24ea4e
fixes #21
diff --git a/jaxl.php b/jaxl.php index 6bdd440..764c5d9 100644 --- a/jaxl.php +++ b/jaxl.php @@ -250,556 +250,557 @@ class JAXL extends XMPPStream { } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); + $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?> diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index e6299af..44ee84d 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -98,575 +98,574 @@ abstract class XMPPStream extends JAXLFsm { $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if(isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; if(isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism'=>$mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if(strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if(!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if(!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if(isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc'=>$nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach(array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if(isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if(!$msg->id) $msg->id = $this->get_id(); if($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if(!$pres->id) $pres->id = $this->get_id(); if($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if(!$iq->id) $iq->id = $this->get_id(); if($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach($data as $pair) { $dd = strpos($pair, '='); if($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } else if(strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach(array('realm', 'cnonce', 'digest-uri') as $key) if(!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if(isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } else if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } else if($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if($stanza->name == 'message') { - $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->handle_message($stanza); } else if($stanza->name == 'presence') { $this->handle_presence($stanza); } else if($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; case "connect": return $this->do_connect($args); break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } } ?>
jaxl/JAXL
4e8fd3e65f38b4a4f7d91c76f670d7d5bb057fe8
checkin for XMPPRosterItem and other cleanups (use composer.json from here http://bit.ly/PX4hkT)
diff --git a/composer.json b/composer.json deleted file mode 100644 index bd116ba..0000000 --- a/composer.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "abhinavsingh/jaxl", - "type": "library", - "description": "jaxl - Jabber XMPP Client Library in PHP.", - "keywords": ["xmpp", "jabber", "jaxl", "abhinavsingh"], - "homepage": "http://jaxl.readthedocs.org/en/latest/index.html", - "license": "MIT", - - "authors": [ - { - "name": "Abhinavsingh", - "homepage": "https://github.com/abhinavsingh" - } - ], - - "require": { - "php": ">=5.2.4" - }, - "minimum-stability": "dev", - "autoload": { - "files": ["jaxl.php"] - } -} \ No newline at end of file diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php index adc6e80..a474ca5 100644 --- a/core/jaxl_clock.php +++ b/core/jaxl_clock.php @@ -1,126 +1,126 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class JAXLClock { // current clock time in microseconds private $tick = 0; // current Unix timestamp with microseconds public $time = null; // scheduled jobs public $jobs = array(); public function __construct() { $this->time = microtime(true); } public function __destruct() { _info("shutting down clock server..."); } public function tick($by=null) { // update clock if($by) { $this->tick += $by; $this->time += $by / pow(10,6); } else { $time = microtime(true); $by = $time - $this->time; $this->tick += $by * pow(10, 6); $this->time = $time; } // run scheduled jobs foreach($this->jobs as $ref=>$job) { if($this->tick >= $job['scheduled_on'] + $job['after']) { //_debug("running job#".($ref+1)." at tick ".$this->tick.", scheduled on ".$job['scheduled_on']." after ".$job['after'].", periodic ".$job['is_periodic']); call_user_func($job['cb'], $job['args']); if(!$job['is_periodic']) { unset($this->jobs[$ref]); } else { $job['scheduled_on'] = $this->tick; $job['runs']++; $this->jobs[$ref] = $job; } } } } // calculate execution time of callback public function tc($callback, $args=null) { } - // callback after $time seconds + // callback after $time microseconds public function call_fun_after($time, $callback, $args=null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => false, 'runs' => 0 ); return sizeof($this->jobs); } - // callback periodically after $time seconds + // callback periodically after $time microseconds public function call_fun_periodic($time, $callback, $args=null) { $this->jobs[] = array( 'scheduled_on' => $this->tick, 'after' => $time, 'cb' => $callback, 'args' => $args, 'is_periodic' => true, 'runs' => 0 ); return sizeof($this->jobs); } // cancel a previously scheduled callback public function cancel_fun_call($ref) { unset($this->jobs[$ref-1]); } } ?> diff --git a/jaxl.php b/jaxl.php index 78a3f02..6bdd440 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,687 +1,687 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info - const version = '3.0.0-alpha-1'; + const version = '3.0.1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { // env $this->cfg = $config; $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified - $host = @$this->cfg['host']; $port = @$this->cfg['port']; + $host = @$this->cfg['host']; $port = @$this->cfg['port'] ? $this->cfg['port'] : 5222; if(!$host && !$port && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = $host; $this->cfg['port'] = $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // lifecycle events callback $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { diff --git a/xmpp/xmpp_roster_item.php b/xmpp/xmpp_roster_item.php new file mode 100644 index 0000000..9e22b5c --- /dev/null +++ b/xmpp/xmpp_roster_item.php @@ -0,0 +1,59 @@ +<?php +/** + * Jaxl (Jabber XMPP Library) + * + * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Abhinav Singh nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +/** + * + * @author abhinavsingh + */ +class XMPPRosterItem { + + public $jid = null; + public $subscription = null; + public $groups = array(); + public $resources = array(); + public $vcard = null; + + public function __construct($jid, $subscription, $groups) { + $this->jid = $jid; + $this->subscription = $subscription; + $this->groups = $groups; + } + +} + +?>
jaxl/JAXL
900019af99207446fc63379f9c9658f96a75df00
fixes #20 added provision for common callback parameters inside JAXLEvent, used by JAXL if JAXL_MULTI_CLIENT constant is set
diff --git a/core/jaxl_event.php b/core/jaxl_event.php index 4b02d5a..1324b36 100644 --- a/core/jaxl_event.php +++ b/core/jaxl_event.php @@ -1,119 +1,121 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * following kind of events are possible: * 1) hook i.e. if a callback for such an event is registered, calling function is responsible for the workflow from their on * 2) filter i.e. calling function will manipulate passed arguments and modified arguments will be passed to next chain of filter * * As a rule of thumb, only 1 hook can be registered for an event, while more than 1 filter is allowed for an event * hook and filter both cannot be applied on an event * * @author abhinavsingh * */ class JAXLEvent { + protected $common = array(); public $reg = array(); - public function __construct() { - + public function __construct($common) { + $this->common = $common; } public function __destruct() { } // add callback on a event // returns a reference to be used while deleting callback // callback'd method must return TRUE to be persistent // if none returned or FALSE, callback will be removed automatically public function add($ev, $cb, $pri) { if(!isset($this->reg[$ev])) $this->reg[$ev] = array(); $ref = sizeof($this->reg[$ev]); $this->reg[$ev][] = array($pri, $cb); return $ev."-".$ref; } // emit event to notify registered callbacks // is a pqueue required here for performance enhancement // in case we have too many cbs on a specific event? public function emit($ev, $data=array()) { + $data = array_merge($this->common, $data); $cbs = array(); if(!isset($this->reg[$ev])) return $data; foreach($this->reg[$ev] as $cb) { if(!isset($cbs[$cb[0]])) $cbs[$cb[0]] = array(); $cbs[$cb[0]][] = $cb[1]; } foreach($cbs as $pri => $cb) { foreach($cb as $c) { $ret = call_user_func_array($c, $data); // this line is for fixing situation where callback function doesn't return an array type // in such cases next call of call_user_func_array will report error since $data is not an array type as expected // things will change in future, atleast put the callback inside a try/catch block // here we only check if there was a return, if yes we update $data with return value // this is bad design, need more thoughts, should work as of now if($ret) $data = $ret; } } unset($cbs); return $data; } // remove previous registered callback public function del($ref) { $ref = explode("-", $ref); unset($this->reg[$ref[0]][$ref[1]]); } public function exists($ev) { $ret = isset($this->reg[$ev]); //_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists")); return $ret; } } ?> diff --git a/jaxl.php b/jaxl.php index bc8051b..78a3f02 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,824 +1,805 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; +require_once JAXL_CWD.'/xmpp/xmpp_roster_item.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; -/** - * - * @author abhinavsingh - */ -class RosterItem { - - public $jid = null; - public $subscription = null; - public $groups = array(); - public $resources = array(); - public $vcard = null; - - public function __construct($jid, $subscription, $groups) { - $this->jid = $jid; - $this->subscription = $subscription; - $this->groups = $groups; - } - -} - /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.0-alpha-1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { // env $this->cfg = $config; $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); - // initialize core modules - $this->ev = new JAXLEvent(); - // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if(!$host && !$port && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = $host; $this->cfg['port'] = $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } + // lifecycle events callback + $this->ev = new JAXLEvent(defined('JAXL_MULTI_CLIENT') ? array(&$this) : array()); + // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function retry() { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _info("Will try to restart in ".$retry_after." seconds"); // TODO: use jaxl cron if sigalarms cannnot be used sleep($retry_after); $this->start(); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { // reset in case we connected back after retries $this->retry_attempt = 0; // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } - + exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } - $this->roster[$jid] = new RosterItem($jid, $subscription, $groups); + $this->roster[$jid] = new XMPPRosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?>
jaxl/JAXL
7e1f1d8841e6214f73492a5693f97fb7424ad9f6
moved retry connection logic into a public method
diff --git a/jaxl.php b/jaxl.php index 46730c5..bc8051b 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,816 +1,824 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * * @author abhinavsingh */ class RosterItem { public $jid = null; public $subscription = null; public $groups = array(); public $resources = array(); public $vcard = null; public function __construct($jid, $subscription, $groups) { $this->jid = $jid; $this->subscription = $subscription; $this->groups = $groups; } } /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.0-alpha-1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { // env $this->cfg = $config; $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // initialize core modules $this->ev = new JAXLEvent(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if(!$host && !$port && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = $host; $this->cfg['port'] = $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } + public function retry() { + $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; + $this->retry_attempt++; + _info("Will try to restart in ".$retry_after." seconds"); + + // TODO: use jaxl cron if sigalarms cannnot be used + sleep($retry_after); + $this->start(); + } + public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { + // reset in case we connected back after retries + $this->retry_attempt = 0; + // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { - $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; - $this->retry_attempt++; - _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr."), will try again in ".$retry_after." seconds"); - // TODO: use sigalrm instead - // they usually doesn't gel well inside select loop - sleep($retry_after); - $this->start(); + _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr.")"); + $this->retry(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new RosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?>
jaxl/JAXL
a6625c5224979dd9a7e8ff1b6759569cfa8e9082
XMPPStream can reconnect once they have reached disconnected or logged_out states
diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index 491d415..e6299af 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,670 +1,672 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass=null, $resource=null, $force_tls=false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if(isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; if(isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism'=>$mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if(strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if(!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if(!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if(isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc'=>$nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach(array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if(isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if(!$msg->id) $msg->id = $this->get_id(); if($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if(!$pres->id) $pres->id = $this->get_id(); if($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if(!$iq->id) $iq->id = $this->get_id(); if($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach($data as $pair) { $dd = strpos($pair, '='); if($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } else if(strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach(array('realm', 'cnonce', 'digest-uri') as $key) if(!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if(isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream - // even before "connect" was called - // must be bosh + // even before "connect" was called must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { if($this->trans->crypt()) { $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { $this->handle_auth_failure("tls-negotiation-failed"); return "logged_out"; } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } else if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } else if($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if($stanza->name == 'message') { $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->handle_message($stanza); } else if($stanza->name == 'presence') { $this->handle_presence($stanza); } else if($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; + case "connect": + return $this->do_connect($args); + break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } } ?>
jaxl/JAXL
163f1ea8e55f291dd4a0024a801253c2379034fb
make a check if callback are still active before calling them
diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index 43e388f..a53a14b 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,157 +1,159 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLLoop { public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; private function __construct() {} private function __clone() {} public static function watch($fd, $opts) { if(isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } if(isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function unwatch($fd, $opts) { if(isset($opts['read'])) { $fdid = (int) $fd; if(isset(self::$read_fds[$fdid])) { unset(self::$read_fds[$fdid]); unset(self::$read_cbs[$fdid]); --self::$active_read_fds; } } if(isset($opts['write'])) { $fdid = (int) $fd; if(isset(self::$write_fds[$fdid])) { unset(self::$write_fds[$fdid]); unset(self::$write_cbs[$fdid]); --self::$active_write_fds; } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function run() { if(!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); while((self::$active_read_fds + self::$active_write_fds) > 0) self::select(); _debug("no more active fd's to select"); self::$is_running = false; } } private static function select() { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); if($changed === false) { _error("error in the event loop, shutting down..."); /*foreach(self::$read_fds as $fd) { if(is_resource($fd)) print_r(stream_get_meta_data($fd)); }*/ exit; } else if($changed > 0) { // read callback foreach($read as $r) { $fdid = array_search($r, self::$read_fds); - call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); + if(isset(self::$read_fds[$fdid])) + call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); } // write callback foreach($write as $w) { $fdid = array_search($w, self::$write_fds); - call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); + if(isset(self::$write_fds[$fdid])) + call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); } self::$clock->tick(); } else if($changed === 0) { //_debug("nothing changed while selecting for read"); self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); } } } ?>
jaxl/JAXL
b699285450908b015ac256126e42c3c6ce128a1a
on socket client disconnect remove write watch, added session_env method to xep-0206
diff --git a/core/jaxl_exception.php b/core/jaxl_exception.php index 23b7e15..200ae46 100644 --- a/core/jaxl_exception.php +++ b/core/jaxl_exception.php @@ -1,93 +1,94 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ error_reporting(E_ALL | E_STRICT); /** * * @author abhinavsingh */ class JAXLException extends Exception { public function __construct($message = null, $code = null, $file = null, $line = null) { _notice("got jaxl exception construct with $message, $code, $file, $line"); if($code === null) { parent::__construct($message); } else { parent::__construct($message, $code); } if($file !== null) { $this->file = $file; } if($line !== null) { $this->line = $line; } } public static function error_handler($errno, $error, $file, $line, $vars) { - //_debug("error handler called with $errno, $error, $file, $line"); + _debug("error handler called with $errno, $error, $file, $line"); if($errno === 0 || ($errno & error_reporting()) === 0) { return; } throw new JAXLException($error, $errno, $file, $line); } public static function exception_handler($e) { _debug("exception handler catched ".json_encode($e)); // TODO: Pretty print backtrace //print_r(debug_backtrace()); } public static function shutdown_handler() { try { + _debug("got shutdown handler"); if(null !== ($error = error_get_last())) { throw new JAXLException($error['message'], $error['type'], $error['file'], $error['line']); } } catch(Exception $e) { _debug("shutdown handler catched with exception ".json_encode($e)); } } } ?> diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index 6668948..f81769c 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,218 +1,219 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; public function __construct($stream_context=null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ public function connect($socket_path) { if(gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); if(sizeof($path_parts) == 3) $this->port = $path_parts[2]; _info("trying ".$socket_path); if($this->stream_context) $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); else $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); } else { $this->fd = &$socket_path; } if($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); $this->disconnect(); return false; } } public function disconnect() { JAXLLoop::unwatch($this->fd, array( - 'read' => true + 'read' => true, + 'write' => true )); @fclose($this->fd); $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); return $ret; } public function send($data) { $this->obuffer .= $data; // add watch for write events if($this->writing) return; JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if($bytes === 0) { $meta = stream_get_meta_data($fd); if($meta['eof'] === TRUE) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); if($bytes > 0) _debug($raw); // callback if($this->recv_cb) call_user_func($this->recv_cb, $raw); } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if(strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } } ?> diff --git a/jaxl.php b/jaxl.php index cabd725..46730c5 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,816 +1,816 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * * @author abhinavsingh */ class RosterItem { public $jid = null; public $subscription = null; public $groups = array(); public $resources = array(); public $vcard = null; public function __construct($jid, $subscription, $groups) { $this->jid = $jid; $this->subscription = $subscription; $this->groups = $groups; } } /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.0-alpha-1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { // env $this->cfg = $config; $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; if($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // initialize core modules $this->ev = new JAXLEvent(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if(!$host && !$port && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = $host; $this->cfg['port'] = $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function add_exception_handlers() { _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); set_error_handler(array('JAXLException', 'error_handler')); set_exception_handler(array('JAXLException', 'exception_handler')); register_shutdown_function(array('JAXLException', 'shutdown_handler')); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr."), will try again in ".$retry_after." seconds"); // TODO: use sigalrm instead // they usually doesn't gel well inside select loop sleep($retry_after); $this->start(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); - + switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new RosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?> diff --git a/xep/xep_0206.php b/xep/xep_0206.php index 87e5605..e5f61c1 100644 --- a/xep/xep_0206.php +++ b/xep/xep_0206.php @@ -1,232 +1,236 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind'); define('NS_BOSH', 'urn:xmpp:xbosh'); class XEP_0206 extends XMPPXep { private $mch = null; public $chs = array(); private $recv_cb = null; public $rid = null; public $sid = null; private $hold = 1; private $wait = 30; private $restarted = false; public $headers = array( 'Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8' ); // // abstract method // public function init() { $this->mch = curl_multi_init(); return array( ); } // // event callbacks // public function send($body) { if(is_object($body)) { $body = $body->to_string(); } else { if(substr($body, 0, 15) == '<stream:stream ') { $this->restarted = true; $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'xmpp:restart' => 'true', 'xmlns:xmpp' => NS_BOSH )); $body = $body->to_string(); } else if(substr($body, 0, 16) == '</stream:stream>') { $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'type' => 'terminate' )); $body = $body->to_string(); } else { $body = $this->wrap($body); } } _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body); $this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']); curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers); curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false); curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1); curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body); curl_multi_add_handle($this->mch, $this->chs[$this->rid]); } public function recv() { if($this->restarted) { $this->restarted = false; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); } _debug("recving for $this->rid"); do { $ret = curl_multi_exec($this->mch, $running); $changed = curl_multi_select($this->mch, 0.1); if($changed == 0 && $running == 0) { $ch = @$this->chs[$this->rid]; if($ch) { $data = curl_multi_getcontent($ch); curl_multi_remove_handle($this->mch, $ch); unset($this->chs[$this->rid]); _debug("recvd for $this->rid ".$data); list($body, $stanza) = $this->unwrap($data); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if(@$attrs['type'] == 'terminate') { // fool me again if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); } else { if(!$this->sid) { $this->sid = $attrs['sid']; } - + if($this->recv_cb) call_user_func($this->recv_cb, $stanza); } } else { _error("no ch found"); exit; } } } while($running); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function wrap($stanza) { return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>'; } public function unwrap($body) { // a dirty way but it works efficiently if(substr($body -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); if(isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; else $envelop = "<body/>"; if(isset($m[2][0])) $payload = $m[2][0]; else $payload = ''; return array($envelop, $payload); } public function session_start() { $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000); $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold; $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); $attrs = array( 'content' => 'text/xml; charset=utf-8', 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'], 'secure' => 'true', 'xml:lang' => 'en', 'xmpp:version' => '1.0', 'xmlns:xmpp' => NS_BOSH, 'hold' => $this->hold, 'wait' => $this->wait, 'rid' => $this->rid, 'ver' => '1.10' ); if(@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; $body = new JAXLXml('body', NS_HTTP_BIND, $attrs); $this->send($body); } public function ping() { $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid)); $this->send($body); } + public function session_end() { + $this->disconnect(); + } + public function disconnect() { - + _debug("disconnecting"); } } ?>
jaxl/JAXL
9df85416f3b1d83213470306d62242afa6cb48ae
emit on_auth_failure upon tls negotiation failure
diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index a19d056..491d415 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,665 +1,670 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass=null, $resource=null, $force_tls=false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; //if(isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; if(isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism'=>$mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if(strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if(!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if(!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if(isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc'=>$nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach(array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if(isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if(!$msg->id) $msg->id = $this->get_id(); if($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if(!$pres->id) $pres->id = $this->get_id(); if($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if(!$iq->id) $iq->id = $this->get_id(); if($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach($data as $pair) { $dd = strpos($pair, '='); if($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } else if(strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach(array('realm', 'cnonce', 'digest-uri') as $key) if(!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if(isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called // must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { - $this->trans->crypt(); - $this->xml->reset_parser(); - $this->send_start_stream($this->jid); - return "wait_for_stream_start"; + if($this->trans->crypt()) { + $this->xml->reset_parser(); + $this->send_start_stream($this->jid); + return "wait_for_stream_start"; + } + else { + $this->handle_auth_failure("tls-negotiation-failed"); + return "logged_out"; + } } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } else if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } else if($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if($stanza->name == 'message') { $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->handle_message($stanza); } else if($stanza->name == 'presence') { $this->handle_presence($stanza); } else if($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } } ?>
jaxl/JAXL
cdc3f1711bcf0d2d07ea920f066f90bbe2cfca87
unwatching file descriptor for read upon disconnect
diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index edce7a7..6668948 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,214 +1,218 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; public function __construct($stream_context=null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } /** * @param string | resource $socket_path */ public function connect($socket_path) { if(gettype($socket_path) == "string") { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); if(sizeof($path_parts) == 3) $this->port = $path_parts[2]; _info("trying ".$socket_path); if($this->stream_context) $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); else $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); } else { $this->fd = &$socket_path; } if($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); $this->disconnect(); return false; } } public function disconnect() { + JAXLLoop::unwatch($this->fd, array( + 'read' => true + )); @fclose($this->fd); $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); + return $ret; } public function send($data) { $this->obuffer .= $data; // add watch for write events if($this->writing) return; JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if($bytes === 0) { $meta = stream_get_meta_data($fd); if($meta['eof'] === TRUE) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); if($bytes > 0) _debug($raw); // callback if($this->recv_cb) call_user_func($this->recv_cb, $raw); } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if(strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } } ?>
jaxl/JAXL
8342f47bae82d26e73d1873e000fc75007fc4b30
JAXLLoop::unwatch can be called repeatedly, method will take care of it. Also switching is_running flag after no more active fd
diff --git a/core/jaxl_loop.php b/core/jaxl_loop.php index 59f2361..43e388f 100644 --- a/core/jaxl_loop.php +++ b/core/jaxl_loop.php @@ -1,152 +1,157 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_clock.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLLoop { public static $clock = null; private static $is_running = false; private static $active_read_fds = 0; private static $active_write_fds = 0; private static $read_fds = array(); private static $read_cbs = array(); private static $write_fds = array(); private static $write_cbs = array(); private static $secs = 0; private static $usecs = 30000; private function __construct() {} private function __clone() {} public static function watch($fd, $opts) { if(isset($opts['read'])) { $fdid = (int) $fd; self::$read_fds[$fdid] = $fd; self::$read_cbs[$fdid] = $opts['read']; ++self::$active_read_fds; } if(isset($opts['write'])) { $fdid = (int) $fd; self::$write_fds[$fdid] = $fd; self::$write_cbs[$fdid] = $opts['write']; ++self::$active_write_fds; } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function unwatch($fd, $opts) { if(isset($opts['read'])) { $fdid = (int) $fd; - unset(self::$read_fds[$fdid]); - unset(self::$read_cbs[$fdid]); - --self::$active_read_fds; + if(isset(self::$read_fds[$fdid])) { + unset(self::$read_fds[$fdid]); + unset(self::$read_cbs[$fdid]); + --self::$active_read_fds; + } } if(isset($opts['write'])) { $fdid = (int) $fd; - unset(self::$write_fds[$fdid]); - unset(self::$write_cbs[$fdid]); - --self::$active_write_fds; + if(isset(self::$write_fds[$fdid])) { + unset(self::$write_fds[$fdid]); + unset(self::$write_cbs[$fdid]); + --self::$active_write_fds; + } } _debug("active read fds: ".self::$active_read_fds.", write fds: ".self::$active_write_fds); } public static function run() { if(!self::$is_running) { self::$is_running = true; self::$clock = new JAXLClock(); while((self::$active_read_fds + self::$active_write_fds) > 0) self::select(); _debug("no more active fd's to select"); + self::$is_running = false; } } private static function select() { $read = self::$read_fds; $write = self::$write_fds; $except = null; $changed = @stream_select($read, $write, $except, self::$secs, self::$usecs); if($changed === false) { _error("error in the event loop, shutting down..."); /*foreach(self::$read_fds as $fd) { if(is_resource($fd)) print_r(stream_get_meta_data($fd)); }*/ exit; } else if($changed > 0) { // read callback foreach($read as $r) { $fdid = array_search($r, self::$read_fds); call_user_func(self::$read_cbs[$fdid], self::$read_fds[$fdid]); } // write callback foreach($write as $w) { $fdid = array_search($w, self::$write_fds); call_user_func(self::$write_cbs[$fdid], self::$write_fds[$fdid]); } self::$clock->tick(); } else if($changed === 0) { //_debug("nothing changed while selecting for read"); self::$clock->tick((self::$secs * pow(10,6)) + self::$usecs); } } } ?>
jaxl/JAXL
e62dd30f263e8a1b5a3631352df4b25a06712c4a
using _info inside examples for visibility to developers on whats happening
diff --git a/examples/http_rest_server.php b/examples/http_rest_server.php index c89f66b..cfbc116 100644 --- a/examples/http_rest_server.php +++ b/examples/http_rest_server.php @@ -1,117 +1,117 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; // print usage notice and parse addr/port parameters if passed _colorize("Usage: $argv[0] port (default: 9699)", JAXL_NOTICE); $port = ($argc == 2 ? $argv[1] : 9699); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer($port); // callback method for dispatch rule (see below) function index($request) { $request->send_response( 200, array('Content-Type'=>'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><a href="/upload">upload a file</a></body></html>' ); $request->close(); } // callback method for dispatch rule (see below) function upload($request) { if($request->method == 'GET') { $request->ok(array( 'Content-Type'=>'text/html'), '<html><head/><body><h1>Jaxl Http Server</h1><form enctype="multipart/form-data" method="POST" action="http://127.0.0.1:9699/upload/"><input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>' ); } else if($request->method == 'POST') { if($request->body === null && $request->expect) { $request->recv_body(); } else { // got upload body, save it _info("file upload complete, got ".strlen($request->body)." bytes of data"); $upload_data = $request->multipart->form_data[0]['body']; $request->ok($upload_data, array('Content-Type'=>$request->multipart->form_data[0]['headers']['Content-Type'])); } } } // add dispatch rules with callback method as first argument $index = array('index', '^/$'); $upload = array('upload', '^/upload', array('GET', 'POST')); // some REST CRUD style callback methods // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules function create_event($request) { - _debug("got event create request"); + _info("got event create request"); $request->close(); } function read_event($request, $pk) { - _debug("got event read request for $pk"); + _info("got event read request for $pk"); $request->close(); } function update_event($request, $pk) { - _debug("got event update request for $pk"); + _info("got event update request for $pk"); $request->close(); } function delete_event($request, $pk) { - _debug("got event delete request for $pk"); + _info("got event delete request for $pk"); $request->close(); } $event_create = array('create_event', '^/event/create/$', array('PUT')); $event_read = array('read_event', '^/event/(?P<pk>\d+)/$', array('GET', 'HEAD')); $event_update = array('update_event', '^/event/(?P<pk>\d+)/$', array('POST')); $event_delete = array('delete_event', '^/event/(?P<pk>\d+)/$', array('DELETE')); // prepare rule set $rules = array($index, $upload, $event_create, $event_read, $event_update, $event_delete); $http->dispatch($rules); // start http server $http->start();
jaxl/JAXL
2518a44b9dfeb9ec947922f078cf4f8663497712
ensuring ./.jaxl/pipes folder
diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php index 01ba80a..8fe1395 100644 --- a/core/jaxl_pipe.php +++ b/core/jaxl_pipe.php @@ -1,112 +1,115 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * bidirectional communication pipes for processes * * This is how this will be (when complete): * $pipe = new JAXLPipe() will return an array of size 2 * $pipe[0] represents the read end of the pipe * $pipe[1] represents the write end of the pipe * * Proposed functionality might even change (currently consider this as experimental) * * @author abhinavsingh * */ class JAXLPipe { protected $perm = 0600; protected $recv_cb = null; protected $fd = null; protected $client = null; public $name = null; public function __construct($name, $read_cb=null) { + $pipes_folder = JAXL_CWD.'/.jaxl/pipes'; + if(!is_dir($pipes_folder)) mkdir($pipes_folder); + $this->ev = new JAXLEvent(); $this->name = $name; $this->read_cb = $read_cb; $pipe_path = $this->get_pipe_file_path(); if(!file_exists($pipe_path)) { posix_mkfifo($pipe_path, $this->perm); $this->fd = fopen($pipe_path, 'r+'); if(!$this->fd) { _error("unable to open pipe"); } else { _debug("pipe opened using path $pipe_path"); _notice("Usage: $ echo 'Hello World!' > $pipe_path"); $this->client = new JAXLSocketClient(); $this->client->connect($this->fd); $this->client->set_callback(array(&$this, 'on_data')); } } else { _error("pipe with name $name already exists"); } } public function __destruct() { @fclose($this->fd); @unlink($this->get_pipe_file_path()); _debug("unlinking pipe file"); } public function get_pipe_file_path() { return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe'; } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function on_data($data) { // callback if($this->recv_cb) call_user_func($this->recv_cb, $data); } } ?>
jaxl/JAXL
da18babb95312ccd886e7084bcf43096a4ef86c3
removed setting up to attribute inside opening stream packet (for oauth mech where an input jid is not mandatory, this breaks the flow, need better fix later, disabled as of now)
diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index 15541e3..a19d056 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,644 +1,644 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass=null, $resource=null, $force_tls=false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; - if(isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; + //if(isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; if(isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism'=>$mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if(strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if(!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if(!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if(isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc'=>$nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach(array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if(isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if(!$msg->id) $msg->id = $this->get_id(); if($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if(!$pres->id) $pres->id = $this->get_id(); if($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if(!$iq->id) $iq->id = $this->get_id(); if($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach($data as $pair) { $dd = strpos($pair, '='); if($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } else if(strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach(array('realm', 'cnonce', 'digest-uri') as $key) if(!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if(isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called // must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { $this->trans->crypt(); $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } else if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } else if($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if($stanza->name == 'message') { $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->handle_message($stanza); } else if($stanza->name == 'presence') { $this->handle_presence($stanza); } else if($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect();
jaxl/JAXL
eb6a4e141f1bdd27ee7279ad91c8070d6ea8c4ba
working example of http_bind.php
diff --git a/examples/http_bind.php b/examples/http_bind.php index b9cc2fa..edfcffa 100644 --- a/examples/http_bind.php +++ b/examples/http_bind.php @@ -1,56 +1,66 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -// backward compatibility example -// for developers who were using JAXL directly via browsers -// through ajax calls (probably by using distributed jaxl.js) -// Yet not working, keep an eye on this example file +if(!isset($_GET['jid']) || !isset($_GET['pass'])) { + echo "invalid input"; + exit; +} // // initialize JAXL object with initial config // -require_once 'jaxl.php'; -$bosh = new JAXL(); +require_once '../jaxl.php'; +$client = new JAXL(array( + 'jid' => $_GET['jid'], + 'pass' => $_GET['pass'], + 'bosh_url' => 'http://localhost:5280/http-bind', + 'log_level' => JAXL_DEBUG +)); + +$client->add_cb('on_auth_success', function() { + global $client; + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); +}); // // finally start configured xmpp stream // -//$bosh->start(); +$client->start(); echo "done\n"; ?>
jaxl/JAXL
34a6c5aa4aaec7d6196256b1ca7e61400404b624
checking in a working example of http_pre_bind.php with related tweaks in stack files
diff --git a/examples/echo_bot.php b/examples/echo_bot.php index 36e1c63..6d51476 100644 --- a/examples/echo_bot.php +++ b/examples/echo_bot.php @@ -1,145 +1,149 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ +// Run as: +// php examples/echo_bot.php root@localhost password +// php examples/echo_bot.php root@localhost password DIGEST-MD5 +// php examples/echo_bot.php localhost "" ANONYMOUS if($argc < 3) { - echo "Usage: $argv[0] jid pass\n"; + echo "Usage: $argv[0] jid pass auth_type\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // (optional) srv lookup is done if not provided //'host' => 'xmpp.domain.tld', // (optional) result from srv lookup used by default //'port' => 5222, // (optional) defaults to false //'force_tls' => true, // (optional) //'resource' => 'resource', // (optional) defaults to PLAIN if supported, else other methods will be automatically tried 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN', 'log_level' => JAXL_INFO )); // // required XEP's // $client->require_xep(array( '0199' // XMPP Ping )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // fetch roster list $client->get_roster(); // fetch vcard $client->get_vcard(); // set status $client->set_status("available!", "dnd", 10); }); // by default JAXL instance catches incoming roster list results and updates // roster list is parsed/cached and an event 'on_roster_update' is emitted $client->add_cb('on_roster_update', function() { //global $client; //print_r($client->roster); }); $client->add_cb('on_auth_failure', function($reason) { global $client; - $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); + $client->send_end_stream(); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming chat message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_presence_stanza', function($stanza) { global $client; $type = ($stanza->type ? $stanza->type : "available"); $show = ($stanza->show ? $stanza->show : "???"); _info($stanza->from." is now ".$type." ($show)"); if($type == "available") { // fetch vcard $client->get_vcard($stanza->from); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(array( '--with-debug-shell' => true, '--with-unix-sock' => true )); echo "done\n"; ?> diff --git a/examples/http_pre_bind.php b/examples/http_pre_bind.php index 28b970a..66f163d 100644 --- a/examples/http_pre_bind.php +++ b/examples/http_pre_bind.php @@ -1,86 +1,91 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // http pre bind php script $body = file_get_contents("php://input"); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if(!@$attrs['to'] && !@$attrs['rid'] && !@$attrs['wait'] && !@$attrs['hold']) { echo "invalid input"; exit; } // // initialize JAXL object with initial config // -require_once 'jaxl.php'; +require_once '../jaxl.php'; -$to = $attrs['to']; -$rid = $attrs['rid']; -$wait = $attrs['wait']; -$hold = $attrs['hold']; -echo $to." ".$rid." ".$wait." ".$hold; exit; +$to = (string)$attrs['to']; +$rid = (int)$attrs['rid']; +$wait = (int)$attrs['wait']; +$hold = (int)$attrs['hold']; list($host, $port) = JAXLUtil::get_dns_srv($to); $client = new JAXL(array( 'domain' => $to, 'host' => $host, 'port' => $port, 'bosh_url' => 'http://localhost:5280/http-bind', 'bosh_rid' => $rid, 'bosh_wait' => $wait, 'bosh_hold' => $hold, - 'auth_type' => 'ANONYMOUS' + 'auth_type' => 'ANONYMOUS', + 'log_level' => JAXL_INFO )); $client->add_cb('on_auth_success', function() { global $client; - _info($client->full_jid->to_string()); - _info($client->xeps['0206']->sid); - _info($client->xeps['0206']->rid); + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); + echo '<body xmlns="'.NS_HTTP_BIND.'" sid="'.$client->xeps['0206']->sid.'" rid="'.$client->xeps['0206']->rid.'" jid="'.$client->full_jid->to_string().'"/>'; exit; }); +$client->add_cb('on_auth_failure', function($reason) { + global $client; + _info("got on_auth_failure cb with reason $reason"); + $client->send_end_stream(); +}); + // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/xep/xep_0206.php b/xep/xep_0206.php index 25b5d74..87e5605 100644 --- a/xep/xep_0206.php +++ b/xep/xep_0206.php @@ -1,232 +1,232 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_HTTP_BIND', 'http://jabber.org/protocol/httpbind'); define('NS_BOSH', 'urn:xmpp:xbosh'); class XEP_0206 extends XMPPXep { private $mch = null; public $chs = array(); private $recv_cb = null; public $rid = null; public $sid = null; private $hold = 1; private $wait = 30; private $restarted = false; public $headers = array( 'Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8' ); // // abstract method // public function init() { $this->mch = curl_multi_init(); return array( ); } // // event callbacks // public function send($body) { if(is_object($body)) { $body = $body->to_string(); } else { if(substr($body, 0, 15) == '<stream:stream ') { $this->restarted = true; $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'xmpp:restart' => 'true', 'xmlns:xmpp' => NS_BOSH )); $body = $body->to_string(); } else if(substr($body, 0, 16) == '</stream:stream>') { $body = new JAXLXml('body', NS_HTTP_BIND, array( 'sid' => $this->sid, 'rid' => ++$this->rid, 'type' => 'terminate' )); $body = $body->to_string(); } else { $body = $this->wrap($body); } } - _debug("send to ".$this->jaxl->cfg['bosh_url']." body ".$body); + _debug("posting to ".$this->jaxl->cfg['bosh_url']." body ".$body); $this->chs[$this->rid] = curl_init($this->jaxl->cfg['bosh_url']); curl_setopt($this->chs[$this->rid], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->chs[$this->rid], CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($this->chs[$this->rid], CURLOPT_HTTPHEADER, $this->headers); curl_setopt($this->chs[$this->rid], CURLOPT_FOLLOWLOCATION, true); curl_setopt($this->chs[$this->rid], CURLOPT_VERBOSE, false); curl_setopt($this->chs[$this->rid], CURLOPT_POST, 1); curl_setopt($this->chs[$this->rid], CURLOPT_POSTFIELDS, $body); curl_multi_add_handle($this->mch, $this->chs[$this->rid]); } public function recv() { if($this->restarted) { $this->restarted = false; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); } _debug("recving for $this->rid"); do { $ret = curl_multi_exec($this->mch, $running); $changed = curl_multi_select($this->mch, 0.1); if($changed == 0 && $running == 0) { $ch = @$this->chs[$this->rid]; if($ch) { $data = curl_multi_getcontent($ch); curl_multi_remove_handle($this->mch, $ch); unset($this->chs[$this->rid]); _debug("recvd for $this->rid ".$data); list($body, $stanza) = $this->unwrap($data); $body = new SimpleXMLElement($body); $attrs = $body->attributes(); if(@$attrs['type'] == 'terminate') { // fool me again if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_end_stream()); } else { if(!$this->sid) { $this->sid = $attrs['sid']; } if($this->recv_cb) call_user_func($this->recv_cb, $stanza); } } else { _error("no ch found"); exit; } } } while($running); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function wrap($stanza) { return '<body sid="'.$this->sid.'" rid="'.++$this->rid.'" xmlns="'.NS_HTTP_BIND.'">'.$stanza.'</body>'; } public function unwrap($body) { // a dirty way but it works efficiently if(substr($body -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $body, $m); else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $body, $m); if(isset($m[1][0])) $envelop = "<body ".$m[1][0]."/>"; else $envelop = "<body/>"; if(isset($m[2][0])) $payload = $m[2][0]; else $payload = ''; return array($envelop, $payload); } public function session_start() { $this->rid = @$this->jaxl->cfg['bosh_rid'] ? $this->jaxl->cfg['bosh_rid'] : rand(1000, 10000); $this->hold = @$this->jaxl->cfg['bosh_hold'] ? $this->jaxl->cfg['bosh_hold'] : $this->hold; $this->wait = @$this->jaxl->cfg['bosh_wait'] ? $this->jaxl->cfg['bosh_wait'] : $this->wait; // fool xmpp_stream state machine with stream start packet // and make transition to wait_for_stream_features state if($this->recv_cb) call_user_func($this->recv_cb, $this->jaxl->get_start_stream(new XMPPJid("bosh.jaxl"))); $attrs = array( 'content' => 'text/xml; charset=utf-8', 'to' => @$this->jaxl->jid ? $this->jaxl->jid->domain : $this->jaxl->cfg['domain'], 'route' => 'xmpp:'.$this->jaxl->cfg['host'].':'.$this->jaxl->cfg['port'], 'secure' => 'true', 'xml:lang' => 'en', 'xmpp:version' => '1.0', 'xmlns:xmpp' => NS_BOSH, 'hold' => $this->hold, 'wait' => $this->wait, 'rid' => $this->rid, 'ver' => '1.10' ); if(@$this->jaxl->cfg['jid']) $attrs['from'] = @$this->jaxl->cfg['jid']; $body = new JAXLXml('body', NS_HTTP_BIND, $attrs); $this->send($body); } public function ping() { $body = new JAXLXml('body', NS_HTTP_BIND, array('sid' => $this->sid, 'rid' => ++$this->rid)); $this->send($body); } public function disconnect() { } } ?> diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index c7df5bc..15541e3 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,643 +1,647 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass=null, $resource=null, $force_tls=false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { - return '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" from="'.$jid->bare.'" to="'.$jid->domain.'" xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; + $xml = '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" '; + if(isset($jid->bare)) $xml .= 'from="'.$jid->bare.'" '; + if(isset($jid->domain)) $xml .= 'to="'.$jid->domain.'" '; + $xml .= 'xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; + return $xml; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism'=>$mechanism)); switch($mechanism) { case 'PLAIN': case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if(strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if(!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if(!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if(isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc'=>$nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach(array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if(isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if(!$msg->id) $msg->id = $this->get_id(); if($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if(!$pres->id) $pres->id = $this->get_id(); if($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if(!$iq->id) $iq->id = $this->get_id(); if($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach($data as $pair) { $dd = strpos($pair, '='); if($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } else if(strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach(array('realm', 'cnonce', 'digest-uri') as $key) if(!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if(isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called // must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { $this->trans->crypt(); $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } else if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } else if($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if($stanza->name == 'message') { $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->handle_message($stanza); } else if($stanza->name == 'presence') { $this->handle_presence($stanza); } else if($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream":
jaxl/JAXL
9fa38c1c389e78d24c5dfa145b1c2e34e19bbbd6
moved exception handlers from JAXLException to inside of JAXL class, a constructor config option strict=>FALSE can be used to disable these handlers
diff --git a/core/jaxl_exception.php b/core/jaxl_exception.php index 1f3e274..23b7e15 100644 --- a/core/jaxl_exception.php +++ b/core/jaxl_exception.php @@ -1,97 +1,93 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ error_reporting(E_ALL | E_STRICT); /** * * @author abhinavsingh */ class JAXLException extends Exception { public function __construct($message = null, $code = null, $file = null, $line = null) { _notice("got jaxl exception construct with $message, $code, $file, $line"); if($code === null) { parent::__construct($message); } else { parent::__construct($message, $code); } if($file !== null) { $this->file = $file; } if($line !== null) { $this->line = $line; } } public static function error_handler($errno, $error, $file, $line, $vars) { //_debug("error handler called with $errno, $error, $file, $line"); if($errno === 0 || ($errno & error_reporting()) === 0) { return; } throw new JAXLException($error, $errno, $file, $line); } public static function exception_handler($e) { _debug("exception handler catched ".json_encode($e)); // TODO: Pretty print backtrace //print_r(debug_backtrace()); } public static function shutdown_handler() { try { if(null !== ($error = error_get_last())) { throw new JAXLException($error['message'], $error['type'], $error['file'], $error['line']); } } catch(Exception $e) { _debug("shutdown handler catched with exception ".json_encode($e)); } } } -set_error_handler(array('JAXLException', 'error_handler')); -set_exception_handler(array('JAXLException', 'exception_handler')); -register_shutdown_function(array('JAXLException', 'shutdown_handler')); - ?> diff --git a/jaxl.php b/jaxl.php index c73f1fc..cabd725 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,746 +1,755 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * * @author abhinavsingh */ class RosterItem { public $jid = null; public $subscription = null; public $groups = array(); public $resources = array(); public $vcard = null; public function __construct($jid, $subscription, $groups) { $this->jid = $jid; $this->subscription = $subscription; $this->groups = $groups; } } /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.0-alpha-1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { // env $this->cfg = $config; + $strict = isset($this->cfg['strict']) ? $this->cfg['strict'] : TRUE; + if($strict) $this->add_exception_handlers(); $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // initialize core modules $this->ev = new JAXLEvent(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if(!$host && !$port && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = $host; $this->cfg['port'] = $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } + public function add_exception_handlers() { + _info("strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this"); + set_error_handler(array('JAXLException', 'error_handler')); + set_exception_handler(array('JAXLException', 'exception_handler')); + register_shutdown_function(array('JAXLException', 'shutdown_handler')); + } + public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function get_socket_path() { return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect($this->get_socket_path())) { // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr."), will try again in ".$retry_after." seconds"); // TODO: use sigalrm instead // they usually doesn't gel well inside select loop sleep($retry_after); $this->start(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new RosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource])
jaxl/JAXL
3a3fc78c0460530fc796a1802590ca12cb504a13
added get_socket_path util method and fixed unix socket server example to accomodate changes done in socket server class contructor
diff --git a/examples/echo_unix_sock_server.php b/examples/echo_unix_sock_server.php index 35c33a7..e8be394 100644 --- a/examples/echo_unix_sock_server.php +++ b/examples/echo_unix_sock_server.php @@ -1,61 +1,61 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 2) { echo "Usage: $argv[0] /path/to/server.sock\n"; exit; } require_once 'jaxl.php'; JAXLLogger::$level = JAXL_INFO; $server = null; function on_request($client, $raw) { global $server; $server->send($client, $raw); _info("got client callback ".$raw); } @unlink($argv[1]); -$server = new JAXLSocketServer('unix://'.$argv[1], 'on_request'); +$server = new JAXLSocketServer('unix://'.$argv[1], NULL, 'on_request'); JAXLLoop::run(); echo "done\n"; ?> diff --git a/jaxl.php b/jaxl.php index 1e289f9..c73f1fc 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,803 +1,807 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * * @author abhinavsingh */ class RosterItem { public $jid = null; public $subscription = null; public $groups = array(); public $resources = array(); public $vcard = null; public function __construct($jid, $subscription, $groups) { $this->jid = $jid; $this->subscription = $subscription; $this->groups = $groups; } } /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.0-alpha-1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { // env $this->cfg = $config; $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // initialize core modules $this->ev = new JAXLEvent(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if(!$host && !$port && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = $host; $this->cfg['port'] = $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } + public function get_socket_path() { + return ($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port']; + } + public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port - if($this->connect(($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port'])) { + if($this->connect($this->get_socket_path())) { // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr."), will try again in ".$retry_after." seconds"); // TODO: use sigalrm instead // they usually doesn't gel well inside select loop sleep($retry_after); $this->start(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); // if pref auth exists, try it if($pref_auth_exists) { $mech = $pref_auth; } // if pref auth doesn't exists, choose one from available mechanisms else { foreach($mechs as $mech=>$any) { // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new RosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?>
jaxl/JAXL
2abb54b743fd299bdd862a6b14d7d1175fd39538
logger will now truncate msg to 1000 max length due to error_log 1024 max size limit (log_errors_max_len ini setting need to be checked as an alternative)
diff --git a/core/jaxl_logger.php b/core/jaxl_logger.php index cfd647d..a0f039c 100644 --- a/core/jaxl_logger.php +++ b/core/jaxl_logger.php @@ -1,93 +1,92 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // log level define('JAXL_ERROR', 1); define('JAXL_WARNING', 2); define('JAXL_NOTICE', 3); define('JAXL_INFO', 4); define('JAXL_DEBUG', 5); // generic global logging shortcuts for different level of verbosity function _error($msg) { JAXLLogger::log($msg, JAXL_ERROR); } function _warning($msg) { JAXLLogger::log($msg, JAXL_WARNING); } function _notice($msg) { JAXLLogger::log($msg, JAXL_NOTICE); } function _info($msg) { JAXLLogger::log($msg, JAXL_INFO); } function _debug($msg) { JAXLLogger::log($msg, JAXL_DEBUG); } // generic global terminal output colorize method // finally sends colorized message to terminal using error_log/1 // this method is mainly to escape $msg from file:line and time // prefix done by _debug, _error, ... methods function _colorize($msg, $verbosity) { error_log(JAXLLogger::colorize($msg, $verbosity)); } class JAXLLogger { public static $level = JAXL_DEBUG; public static $path = null; + public static $max_log_size = 1000; protected static $colors = array( 1 => 31, // error: red 2 => 34, // warning: blue 3 => 33, // notice: yellow 4 => 32, // info: green 5 => 37 // debug: white ); public static function log($msg, $verbosity=1) { if($verbosity <= self::$level) { $bt = debug_backtrace(); array_shift($bt); $callee = array_shift($bt); $msg = basename($callee['file'], '.php').":".$callee['line']." - ".@date('Y-m-d H:i:s')." - ".$msg; - // if no path is set via jaxl config, default log to env stderr - if(isset(self::$path)) { - error_log($msg . PHP_EOL, 3, self::$path); - } - else { - error_log(self::colorize($msg, $verbosity)); - } + $size = strlen($msg); + if($size > self::$max_log_size) $msg = substr($msg, 0, self::$max_log_size) . ' ...'; + + if(isset(self::$path)) error_log($msg . PHP_EOL, 3, self::$path); + else error_log(self::colorize($msg, $verbosity)); } } public static function colorize($msg, $verbosity) { return "\033[".self::$colors[$verbosity]."m".$msg."\033[0m"; } } ?>
jaxl/JAXL
95f9cc52fc3fc39acb6adf36ca26bb7b8eb8f0c2
fixes #17
diff --git a/core/jaxl_socket_client.php b/core/jaxl_socket_client.php index c2aca87..1807cca 100644 --- a/core/jaxl_socket_client.php +++ b/core/jaxl_socket_client.php @@ -1,206 +1,206 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * * Enter description here ... * @author abhinavsingh * */ class JAXLSocketClient { private $host = null; private $port = null; private $transport = null; private $stream_context = null; private $blocking = false; public $fd = null; public $errno = null; public $errstr = null; private $timeout = 10; private $ibuffer = ""; private $obuffer = ""; private $compressed = false; private $recv_bytes = 0; private $send_bytes = 0; private $recv_cb = null; private $recv_chunk_size = 1024; private $writing = false; public function __construct($stream_context=null) { $this->stream_context = $stream_context; } public function __destruct() { //_debug("cleaning up xmpp socket..."); $this->disconnect(); } public function set_callback($recv_cb) { $this->recv_cb = $recv_cb; } public function connect($socket_path) { $path_parts = explode(":", $socket_path); $this->transport = $path_parts[0]; $this->host = substr($path_parts[1], 2, strlen($path_parts[1])); if(sizeof($path_parts) == 3) $this->port = $path_parts[2]; _info("trying ".$socket_path); if($this->stream_context) $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); else $this->fd = @stream_socket_client($socket_path, $this->errno, $this->errstr, $this->timeout); if($this->fd) { _debug("connected to ".$socket_path.""); stream_set_blocking($this->fd, $this->blocking); // watch descriptor for read/write events JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); return true; } else { _error("unable to connect ".$socket_path." with error no: ".$this->errno.", error str: ".$this->errstr.""); $this->disconnect(); return false; } } public function disconnect() { @fclose($this->fd); $this->fd = null; } public function compress() { $this->compressed = true; //stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ); //stream_filter_append($this->fd, 'zlib.deflate', STREAM_FILTER_WRITE); } public function crypt() { // set blocking (since tls negotiation fails if stream is non-blocking) stream_set_blocking($this->fd, true); $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT); if($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); if($ret == false) { $ret = stream_socket_enable_crypto($this->fd, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); } } } // switch back to non-blocking stream_set_blocking($this->fd, false); } public function send($data) { $this->obuffer .= $data; // add watch for write events if($this->writing) return; JAXLLoop::watch($this->fd, array( 'write' => array(&$this, 'on_write_ready') )); $this->writing = true; } public function on_read_ready($fd) { //_debug("on read ready called"); $raw = @fread($fd, $this->recv_chunk_size); $bytes = strlen($raw); if($bytes === 0) { $meta = stream_get_meta_data($fd); if($meta['eof'] === TRUE) { _warning("socket eof, disconnecting"); JAXLLoop::unwatch($fd, array( 'read' => true )); $this->disconnect(); return; } } $this->recv_bytes += $bytes; $total = $this->ibuffer.$raw; $this->ibuffer = ""; _debug("read ".$bytes."/".$this->recv_bytes." of data"); if($bytes > 0) _debug($raw); // callback if($this->recv_cb) call_user_func($this->recv_cb, $raw); } public function on_write_ready($fd) { //_debug("on write ready called"); $total = strlen($this->obuffer); $bytes = @fwrite($fd, $this->obuffer); $this->send_bytes += $bytes; _debug("sent ".$bytes."/".$this->send_bytes." of data"); - _debug($this->obuffer); + _debug(substr($this->obuffer, 0, $bytes)); $this->obuffer = substr($this->obuffer, $bytes, $total-$bytes); // unwatch for write if obuffer is empty if(strlen($this->obuffer) === 0) { JAXLLoop::unwatch($fd, array( 'write' => true )); $this->writing = false; } //_debug("current obuffer size: ".strlen($this->obuffer).""); } } ?>
jaxl/JAXL
8510b16480fa7c240ce8113dcbbff13951a71e76
.gitignore update
diff --git a/.gitignore b/.gitignore index 5156d6d..6654fa5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ .buildpath .project .jaxl +.pydevproject +.settings/ docs/_build
jaxl/JAXL
eb7933fb25b7491d888eb86fd51112fcf3fa3dd5
right ordering for roster list retrieval and then presence update inside echo bot example, fixed a typo inside http dispatcher which will allow GET as default method if not specified in dispatch rule specs
diff --git a/examples/echo_bot.php b/examples/echo_bot.php index df7045d..36e1c63 100644 --- a/examples/echo_bot.php +++ b/examples/echo_bot.php @@ -1,145 +1,145 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // (optional) srv lookup is done if not provided //'host' => 'xmpp.domain.tld', // (optional) result from srv lookup used by default //'port' => 5222, // (optional) defaults to false //'force_tls' => true, // (optional) //'resource' => 'resource', // (optional) defaults to PLAIN if supported, else other methods will be automatically tried 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN', 'log_level' => JAXL_INFO )); // // required XEP's // $client->require_xep(array( '0199' // XMPP Ping )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); - // set status - $client->set_status("available!", "dnd", 10); + // fetch roster list + $client->get_roster(); // fetch vcard $client->get_vcard(); - // fetch roster list - $client->get_roster(); + // set status + $client->set_status("available!", "dnd", 10); }); // by default JAXL instance catches incoming roster list results and updates // roster list is parsed/cached and an event 'on_roster_update' is emitted $client->add_cb('on_roster_update', function() { //global $client; //print_r($client->roster); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming chat message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_presence_stanza', function($stanza) { global $client; $type = ($stanza->type ? $stanza->type : "available"); $show = ($stanza->show ? $stanza->show : "???"); _info($stanza->from." is now ".$type." ($show)"); if($type == "available") { // fetch vcard $client->get_vcard($stanza->from); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(array( '--with-debug-shell' => true, '--with-unix-sock' => true )); echo "done\n"; ?> diff --git a/http/http_dispatcher.php b/http/http_dispatcher.php index 7003ee7..3929dee 100644 --- a/http/http_dispatcher.php +++ b/http/http_dispatcher.php @@ -1,121 +1,121 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // // (optionally) set an array of url dispatch rules // each dispatch rule is defined by an array of size 4 like: // array($callback, $pattern, $methods, $extra), where // $callback the method which will be called if this rule matches // $pattern regular expression to match request path // $methods list of allowed methods for this rule // pass boolean true to allow all http methods // if omitted or an empty array() is passed (which actually doesnt make sense) // by default 'GET' will be the method allowed on this rule // $extra reserved for future (you can totally omit this as of now) // class HTTPDispatchRule { // match callback public $cb = null; // regexp to match on request path public $pattern = null; // methods to match upon // add atleast 1 method for this rule to work public $methods = null; // other matching rules public $extra = array(); - public function __construct($cb, $pattern, $methods=null, $extra=array()) { + public function __construct($cb, $pattern, $methods=array('GET'), $extra=array()) { $this->cb = $cb; $this->pattern = $pattern; $this->methods = $methods; $this->extra = $extra; } public function match($path, $method) { if(preg_match("/".str_replace("/", "\/", $this->pattern)."/", $path, $matches)) { if(in_array($method, $this->methods)) { return $matches; } } return false; } } class HTTPDispatcher { protected $rules = array(); public function __construct() { $this->rules = array(); } public function add_rule($rule) { $s = sizeof($rule); if($s > 4) { _debug("invalid rule"); return; } // fill up defaults if($s == 3) { $rule[] = array(); } else if($s == 2) { $rule[] = array('GET'); $rule[] = array(); } else { _debug("invalid rule"); return; } $this->rules[] = new HTTPDispatchRule($rule[0], $rule[1], $rule[2], $rule[3]); } public function dispatch($request) { foreach($this->rules as $rule) { //_debug("matching $request->path with pattern $rule->pattern"); if(($matches = $rule->match($request->path, $request->method)) !== false) { _debug("matching rule found, dispatching"); $params = array($request); // TODO: a bad way to restrict on 'pk', fix me for generalization if(@isset($matches['pk'])) $params[] = $matches['pk']; call_user_func_array($rule->cb, $params); return true; } } return false; } } ?>
jaxl/JAXL
f228d6209d8363a20fd636a18234300e8f8e8490
SOCK5 checkin and few updates to HTTPClient class
diff --git a/core/jaxl_sock5.php b/core/jaxl_sock5.php new file mode 100644 index 0000000..05ef906 --- /dev/null +++ b/core/jaxl_sock5.php @@ -0,0 +1,128 @@ +<?php +/** + * Jaxl (Jabber XMPP Library) + * + * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Abhinav Singh nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +require_once JAXL_CWD.'/core/jaxl_socket_client.php'; + +/** + * TODO: convert into a finite state machine + * + * @author abhinavsingh + * + */ +class JAXLSock5 { + + private $client = null; + + protected $transport = null; + protected $ip = null; + protected $port = null; + + public function __construct($transport='tcp') { + $this->transport = $transport; + $this->client = new JAXLSocketClient(); + $this->client->set_callback(array(&$this, 'on_response')); + } + + public function __destruct() { + + } + + public function connect($ip, $port=1080) { + $this->ip = $ip; + $this->port = $port; + $sock_path = $this->_sock_path(); + + if($this->client->connect($sock_path)) { + _debug("established connection to $sock_path"); + return true; + } + else { + _error("unable to connect $sock_path"); + return false; + } + } + + // + // Three phases of SOCK5 + // + + // Negotiation pkt consists of 3 part: + // 0x05 => Sock protocol version + // 0x01 => Number of method identifier octet + // + // Following auth methods are defined: + // 0x00 => No authentication required + // 0x01 => GSSAPI + // 0x02 => USERNAME/PASSWORD + // 0x03 to 0x7F => IANA ASSIGNED + // 0x80 to 0xFE => RESERVED FOR PRIVATE METHODS + // 0xFF => NO ACCEPTABLE METHODS + public function negotiate() { + $pkt = pack("C3", 0x05, 0x01, 0x00); + $this->client->send($pkt); + + // enter sub-negotiation state + } + + public function relay_request() { + // enter wait for reply state + } + + public function send_data() { + + } + + // + // Socket client callback + // + + public function on_response($raw) { + _debug($raw); + } + + // + // Private + // + + protected function _sock_path() { + return $this->transport.'://'.$this->ip.':'.$this->port; + } + +} + +?> diff --git a/examples/curl.php b/examples/curl.php index 3084179..de27e3f 100644 --- a/examples/curl.php +++ b/examples/curl.php @@ -1,46 +1,51 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ +if($argc < 2) { + echo "Usage: $argv[0] url\n"; + exit; +} + require_once 'jaxl.php'; -JAXLLogger::$level = JAXL_INFO; +JAXLLogger::$level = JAXL_DEBUG; require_once JAXL_CWD.'/http/http_client.php'; -$request = new HTTPClient('http://google.com/'); +$request = new HTTPClient($argv[1]); $request->start(); ?> diff --git a/http/http_client.php b/http/http_client.php index 30b4976..113ae28 100644 --- a/http/http_client.php +++ b/http/http_client.php @@ -1,130 +1,138 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_socket_client.php'; +/** + * TODO: convert into a finite state machine + * + * @author abhinavsingh + * + */ class HTTPClient { private $url = null; private $parts = array(); private $headers = array(); private $data = null; - public $method = 'GET'; + public $method = null; private $client = null; public function __construct($url, $headers=array(), $data=null) { $this->url = $url; $this->headers = $headers; $this->data = $data; $this->client = new JAXLSocketClient(); $this->client->set_callback(array(&$this, 'on_response')); } - public function start() { + public function start($method='GET') { + $this->method = $method; + $this->parts = parse_url($this->url); $transport = $this->_transport(); $ip = $this->_ip(); $port = $this->_port(); $socket_path = $transport.'://'.$ip.':'.$port; if($this->client->connect($socket_path)) { _debug("connection to $this->url established"); // send request data $this->send_request(); - // start loop and wait for response + // start main loop JAXLLoop::run(); } else { _debug("unable to open $this->url"); } } public function on_response($raw) { - _debug($raw); + _info("got http response"); } protected function send_request() { $this->client->send($this->_line()."\r\n"); $this->client->send($this->_ua()."\r\n"); $this->client->send($this->_host()."\r\n"); $this->client->send("\r\n"); } // // private methods on uri parts // private function _line() { return $this->method.' '.$this->_uri().' HTTP/1.1'; } private function _ua() { return 'User-Agent: jaxl_http_client/3.x'; } private function _host() { return 'Host: '.$this->parts['host'].':'.$this->_port(); } private function _transport() { return ($this->parts['scheme'] == 'http' ? 'tcp' : 'ssl'); } private function _ip() { return gethostbyname($this->parts['host']); } private function _port() { return @$this->parts['port'] ? $this->parts['port'] : 80; } private function _uri() { $uri = $this->parts['path']; if(@$this->parts['query']) $uri .= '?'.$this->parts['query']; if(@$this->parts['fragment']) $uri .= '#'.$this->parts['fragment']; return $uri; } } ?> diff --git a/http/http_request.php b/http/http_request.php index 742e92e..887f086 100644 --- a/http/http_request.php +++ b/http/http_request.php @@ -1,490 +1,492 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/http/http_multipart.php'; // // These methods are available only once // $request FSM has reached 'headers_received' state // // following shortcuts are available // on received $request object: // // $request->{status_code_name}($headers, $body) // $request->{status_code_name}($body, $headers) // // $request->{status_code_name}($headers) // $request->{status_code_name}($body) // // following specific methods are also available: // // $request->send_line($code) // $request->send_header($key, $value) // $request->send_headers($headers) // $request->send_message($string) // // all the above methods can also be directly performed using: // // $request->send_response($code, $headers=array(), $body=null) // // Note: All the send_* methods do not manage connection close/keep-alive logic, // it is upto you to do that, by default connection will usually be dropped // on client disconnect if not handled by you. // class HTTPRequest extends JAXLFsm { // peer identifier public $sock = null; public $ip = null; public $port = null; // request line public $version = null; public $method = null; public $resource = null; public $path = null; public $query = array(); // headers and body public $headers = array(); public $body = null; public $recvd_body_len = 0; // is true if 'Expect: 100-Continue' // request header has been seen public $expect = false; // set if there is Content-Type: multipart/form-data; boundary=... // header already seen public $multipart = null; // callback for send/read/close actions on accepted sock private $_send_cb = null; private $_read_cb = null; private $_close_cb = null; private $shortcuts = array( 'ok' => 200, // 2xx 'redirect' => 302, 'not_modified' => 304, // 3xx 'not_found' => 404, 'bad_request' => 400, // 4xx 'internal_error' => 500, // 5xx 'recv_body' => true, 'close' => true // others ); public function __construct($sock, $addr) { $this->sock = $sock; $addr = explode(":", $addr); $this->ip = $addr[0]; if(sizeof($addr) == 2) { $this->port = $addr[1]; } parent::__construct("setup"); } public function __destruct() { _debug("http request going down in ".$this->state." state"); } public function state() { return $this->state; } // // abstract method implementation + // + public function handle_invalid_state($r) { _debug("handle invalid state called with"); var_dump($r); } // // fsm States // public function setup($event, $args) { switch($event) { case 'set_sock_cb': $this->_send_cb = $args[0]; $this->_read_cb = $args[1]; $this->_close_cb = $args[2]; return 'wait_for_request_line'; break; default: _warning("uncatched $event"); return 'setup'; } } public function wait_for_request_line($event, $args) { switch($event) { case 'line': $this->_line($args[0], $args[1], $args[2]); return 'wait_for_headers'; break; default: _warning("uncatched $event"); return 'wait_for_request_line'; } } public function wait_for_headers($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'maybe_headers_received'; default: _warning("uncatched $event"); return 'wait_for_headers'; } } public function maybe_headers_received($event, $args) { switch($event) { case 'set_header': $this->set_header($args[0], $args[1]); return 'wait_for_headers'; break; case 'empty_line': return 'headers_received'; break; case 'body': return $this->wait_for_body($event, $args); break; default: _warning("uncatched $event"); return 'maybe_headers_received'; } } public function wait_for_body($event, $args) { switch($event) { case 'body': $content_length = $this->headers['Content-Length']; $rcvd = $args[0]; $rcvd_len = strlen($rcvd); $this->recvd_body_len += $rcvd_len; if($this->body === null) $this->body = $rcvd; else $this->body .= $rcvd; if($this->multipart) { // boundary start, content_disposition, form data, boundary start, ....., boundary end // these define various states of a multipart/form-data $form_data = explode("\r\n", $rcvd); foreach($form_data as $data) { //_debug("passing $data to multipart fsm"); if(!$this->multipart->process($data)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } } } if($this->recvd_body_len < $content_length && $this->multipart->state() != 'done') { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'set_header': $content_length = $this->headers['Content-Length']; $body = implode(":", $args); $rcvd_len = strlen($body); $this->recvd_body_len += $rcvd_len; if(!$this->multipart->process($body)) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; case 'empty_line': $content_length = $this->headers['Content-Length']; if(!$this->multipart->process('')) { _debug("multipart fsm returned false"); $this->_close(); return array('closed', false); } if($this->recvd_body_len < $content_length) { _debug("rcvd body len: $this->recvd_body_len/$content_length"); return 'wait_for_body'; } else { _debug("all data received, switching state for dispatch"); return 'headers_received'; } break; default: _warning("uncatched $event"); return 'wait_for_body'; } } // headers and may be body received public function headers_received($event, $args) { switch($event) { case 'empty_line': return 'headers_received'; break; default: if(substr($event, 0, 5) == 'send_') { $protected = '_'.$event; if(method_exists($this, $protected)) { call_user_func_array(array(&$this, $protected), $args); return 'headers_received'; } else { _debug("non-existant method $event called"); return 'headers_received'; } } else if(@isset($this->shortcuts[$event])) { return $this->handle_shortcut($event, $args); } else { _warning("uncatched $event ".$args[0]); return 'headers_received'; } } } public function closed($event, $args) { _warning("uncatched $event"); } // sets input headers // called internally for every header received protected function set_header($k, $v) { $k = trim($k); $v = ltrim($v); // is expect header? if(strtolower($k) == 'expect' && strtolower($v) == '100-continue') { $this->expect = true; } // is multipart form data? if(strtolower($k) == 'content-type') { $ctype = explode(';', $v); if(sizeof($ctype) == 2 && strtolower(trim($ctype[0])) == 'multipart/form-data') { $boundary = explode('=', trim($ctype[1])); if(strtolower(trim($boundary[0])) == 'boundary') { _debug("multipart with boundary $boundary[1] detected"); $this->multipart = new HTTPMultiPart(ltrim($boundary[1])); } } } $this->headers[trim($k)] = trim($v); } // shortcut handler protected function handle_shortcut($event, $args) { _debug("executing shortcut '$event'"); switch($event) { // http status code shortcuts case 'ok': case 'redirect': case 'not_modified': case 'bad_request': case 'not_found': case 'internal_error': list($headers, $body) = $this->parse_shortcut_args($args); $code = $this->shortcuts[$event]; $this->_send_response($code, $headers, $body); $this->_close(); return 'closed'; break; // others case 'recv_body': // send expect header if required if($this->expect) { $this->expect = false; $this->_send_line(100); } // read data $this->_read(); return 'wait_for_body'; break; case 'close': $this->_close(); return 'closed'; break; } } private function parse_shortcut_args($args) { if(sizeof($args) == 0) { $body = null; $headers = array(); } if(sizeof($args) == 1) { // http headers or body only received if(is_array($args[0])) { // http headers only $headers = $args[0]; $body = null; } else { // body only $body = $args[0]; $headers = array(); } } else if(sizeof($args) == 2) { // body and http headers both received if(is_array($args[0])) { // header first $body = $args[1]; $headers = $args[0]; } else { // body first $body = $args[0]; $headers = $args[1]; } } return array($headers, $body); } // // send methods // available only on 'headers_received' state // protected function _send_line($code) { $raw = $this->version." ".$code." ".constant('HTTP_'.$code).HTTP_CRLF; $this->_send($raw); } protected function _send_header($k, $v) { $raw = $k.': '.$v.HTTP_CRLF; $this->_send($raw); } protected function _send_headers($code, $headers) { foreach($headers as $k=>$v) $this->_send_header($k, $v); } protected function _send_body($body) { $this->_send($body); } protected function _send_response($code, $headers=array(), $body=null) { // send out response line $this->_send_line($code); // set content length of body exists and is not already set if($body && !isset($headers['Content-Length'])) $headers['Content-Length'] = strlen($body); // send out headers $this->_send_headers($code, $headers); // send body // prefixed with an empty line _debug("sending out HTTP_CRLF prefixed body"); if($body) $this->_send_body(HTTP_CRLF.$body); } // // internal methods // // initializes status line elements private function _line($method, $resource, $version) { $this->method = $method; $this->resource = $resource; $resource = explode("?", $resource); $this->path = $resource[0]; if(sizeof($resource) == 2) { $query = $resource[1]; $query = explode("&", $query); foreach($query as $q) { $q = explode("=", $q); if(sizeof($q) == 1) $q[1] = ""; $this->query[$q[0]] = $q[1]; } } $this->version = $version; } private function _send($raw) { call_user_func($this->_send_cb, $this->sock, $raw); } private function _read() { call_user_func($this->_read_cb, $this->sock); } private function _close() { call_user_func($this->_close_cb, $this->sock); } } ?>
jaxl/JAXL
f42e0505b0f3374beea06de559b6574e793e8aff
added Google X-OAUTH2 support with an example to demonstrate the same
diff --git a/examples/echo_facebook_client.php b/examples/xfacebook_platform_client.php similarity index 100% rename from examples/echo_facebook_client.php rename to examples/xfacebook_platform_client.php diff --git a/examples/xoauth2_gtalk_client.php b/examples/xoauth2_gtalk_client.php new file mode 100644 index 0000000..702c98c --- /dev/null +++ b/examples/xoauth2_gtalk_client.php @@ -0,0 +1,99 @@ +<?php +/** + * Jaxl (Jabber XMPP Library) + * + * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Abhinav Singh nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +if($argc != 3) { + echo "Usage: $argv[0] jid access_token\n"; + exit; +} + +// +// initialize JAXL object with initial config +// +require_once 'jaxl.php'; +$client = new JAXL(array( + // (required) credentials + 'jid' => $argv[1], + 'pass' => $argv[2], + + // force tls + 'force_tls' => true, + // (required) perform X-OAUTH2 + 'auth_type' => 'X-OAUTH2', + + // (optional) + //'resource' => 'resource', + + 'log_level' => JAXL_DEBUG +)); + +// +// add necessary event callbacks here +// + +$client->add_cb('on_auth_success', function() { + global $client; + _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); + $client->set_status("available!", "dnd", 10); +}); + +$client->add_cb('on_auth_failure', function($reason) { + global $client; + $client->send_end_stream(); + _info("got on_auth_failure cb with reason $reason"); +}); + +$client->add_cb('on_chat_message', function($stanza) { + global $client; + + // echo back incoming message stanza + $stanza->to = $stanza->from; + $stanza->from = $client->full_jid->to_string(); + $client->send($stanza); +}); + +$client->add_cb('on_disconnect', function() { + _info("got on_disconnect cb"); +}); + +// +// finally start configured xmpp stream +// +$client->start(); +echo "done\n"; + +?> diff --git a/jaxl.php b/jaxl.php index 80219ff..1e289f9 100644 --- a/jaxl.php +++ b/jaxl.php @@ -102,697 +102,702 @@ class JAXL extends XMPPStream { // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "mutual" public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { // env $this->cfg = $config; $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // initialize core modules $this->ev = new JAXLEvent(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if(!$host && !$port && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = $host; $this->cfg['port'] = $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect(($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port'])) { // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr."), will try again in ".$retry_after." seconds"); // TODO: use sigalrm instead // they usually doesn't gel well inside select loop sleep($retry_after); $this->start(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } + // extract available mechanisms $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; + + // check if preferred auth type exists in available mechanisms $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); + // if pref auth exists, try it if($pref_auth_exists) { - // try prefered auth $mech = $pref_auth; } + // if pref auth doesn't exists, choose one from available mechanisms else { - // choose one from available mechanisms foreach($mechs as $mech=>$any) { + // choose X-FACEBOOK-PLATFORM only if fb_access_token config value is available if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } + // else try first of the available methods else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new RosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above // TODO: can we add more checks here before calling back // e.g. checks on existence of an attribute, check on 1st level child ns and so on if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?> diff --git a/xmpp/xmpp_stream.php b/xmpp/xmpp_stream.php index a2c6e42..c7df5bc 100644 --- a/xmpp/xmpp_stream.php +++ b/xmpp/xmpp_stream.php @@ -1,660 +1,661 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_fsm.php'; require_once JAXL_CWD.'/core/jaxl_xml.php'; require_once JAXL_CWD.'/core/jaxl_xml_stream.php'; require_once JAXL_CWD.'/core/jaxl_util.php'; require_once JAXL_CWD.'/core/jaxl_socket_client.php'; require_once JAXL_CWD.'/xmpp/xmpp_nss.php'; require_once JAXL_CWD.'/xmpp/xmpp_jid.php'; require_once JAXL_CWD.'/xmpp/xmpp_msg.php'; require_once JAXL_CWD.'/xmpp/xmpp_pres.php'; require_once JAXL_CWD.'/xmpp/xmpp_iq.php'; /** * * Enter description here ... * @author abhinavsingh * */ abstract class XMPPStream extends JAXLFsm { // jid with binding resource value public $full_jid = null; // input parameters public $jid = null; public $pass = null; public $resource = null; public $force_tls = false; // underlying socket/bosh and xml stream ref protected $trans = null; protected $xml = null; // stanza id protected $last_id = 0; // // abstract methods // abstract public function handle_stream_start($stanza); abstract public function handle_auth_mechs($stanza, $mechs); abstract public function handle_auth_success(); abstract public function handle_auth_failure($reason); abstract public function handle_iq($stanza); abstract public function handle_presence($stanza); abstract public function handle_message($stanza); abstract public function handle_other($event, $args); // // public api // public function __construct($transport, $jid, $pass=null, $resource=null, $force_tls=false) { $this->jid = $jid; $this->pass = $pass; $this->resource = $resource ? $resource : md5(time()); $this->force_tls = $force_tls; $this->trans = $transport; $this->xml = new JAXLXmlStream(); $this->trans->set_callback(array(&$this->xml, "parse")); $this->xml->set_callback(array(&$this, "start_cb"), array(&$this, "end_cb"), array(&$this, "stanza_cb")); parent::__construct("setup"); } public function __destruct() { //_debug("cleaning up xmpp stream..."); } public function handle_invalid_state($r) { _error("got invalid return value from state handler '".$this->state."', sending end stream..."); $this->send_end_stream(); $this->state = "logged_out"; _notice("state handler '".$this->state."' returned ".serialize($r).", kindly report this to developers"); } public function send($stanza) { $this->trans->send($stanza->to_string()); } public function send_raw($data) { $this->trans->send($data); } // // pkt creation utilities // public function get_start_stream($jid) { return '<stream:stream xmlns:stream="'.NS_XMPP.'" version="1.0" from="'.$jid->bare.'" to="'.$jid->domain.'" xmlns="'.NS_JABBER_CLIENT.'" xml:lang="en" xmlns:xml="'.NS_XML.'">'; } public function get_end_stream() { return '</stream:stream>'; } public function get_starttls_pkt() { $stanza = new JAXLXml('starttls', NS_TLS); return $stanza; } public function get_compress_pkt($method) { $stanza = new JAXLXml('compress', NS_COMPRESSION_PROTOCOL); $stanza->c('method')->t($method); return $stanza; } // someday this all needs to go inside jaxl_sasl_auth public function get_auth_pkt($mechanism, $user, $pass) { $stanza = new JAXLXml('auth', NS_SASL, array('mechanism'=>$mechanism)); switch($mechanism) { case 'PLAIN': + case 'X-OAUTH2': $stanza->t(base64_encode("\x00".$user."\x00".$pass)); break; case 'DIGEST-MD5': break; case 'CRAM-MD5': break; case 'SCRAM-SHA-1': // client first message always starts with n, y or p for GS2 extensibility $stanza->t(base64_encode("n,,n=".$user.",r=".JAXLUtil::get_nonce(false))); break; case 'ANONYMOUS': break; case 'EXTERNAL': // If no password, then we are probably doing certificate auth, so follow RFC 6120 form and pass '='. if(strlen($pass) == 0) $stanza->t('='); break; default: break; } return $stanza; } public function get_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $decoded = $this->explode_data(base64_decode($challenge)); if(!isset($decoded['rspauth'])) { _debug("calculating response to challenge"); $stanza->t($this->get_challenge_response($decoded)); } return $stanza; } public function get_challenge_response($decoded) { $response = array(); $nc = '00000001'; if(!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$this->jid->domain; $decoded['cnonce'] = base64_encode(JAXLUtil::get_nonce()); if(isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) $decoded['qop'] = 'auth'; $data = array_merge($decoded, array('nc'=>$nc)); $response = array( 'username'=> $this->jid->node, 'response' => $this->encrypt_password($data, $this->jid->node, $this->pass), 'charset' => 'utf-8', 'nc' => $nc, 'qop' => 'auth' ); foreach(array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) if(isset($decoded[$key])) $response[$key] = $decoded[$key]; return base64_encode($this->implode_data($response)); } public function get_bind_pkt($resource) { $stanza = new JAXLXml('bind', NS_BIND); $stanza->c('resource')->t($resource); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_session_pkt() { $stanza = new JAXLXml('session', NS_SESSION); return $this->get_iq_pkt(array( 'type' => 'set' ), $stanza); } public function get_msg_pkt($attrs, $body=null, $thread=null, $subject=null, $payload=null) { $msg = new XMPPMsg($attrs, $body, $thread, $subject); if(!$msg->id) $msg->id = $this->get_id(); if($payload) $msg->cnode($payload); return $msg; } public function get_pres_pkt($attrs, $status=null, $show=null, $priority=null, $payload=null) { $pres = new XMPPPres($attrs, $status, $show, $priority); if(!$pres->id) $pres->id = $this->get_id(); if($payload) $pres->cnode($payload); return $pres; } public function get_iq_pkt($attrs, $payload) { $iq = new XMPPIq($attrs); if(!$iq->id) $iq->id = $this->get_id(); if($payload) $iq->cnode($payload); return $iq; } public function get_id() { ++$this->last_id; return dechex($this->last_id); } public function explode_data($data) { $data = explode(',', $data); $pairs = array(); $key = false; foreach($data as $pair) { $dd = strpos($pair, '='); if($dd) { $key = trim(substr($pair, 0, $dd)); $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"'); } else if(strpos(strrev(trim($pair)), '"') === 0 && $key) { $pairs[$key] .= ',' . trim(trim($pair), '"'); continue; } } return $pairs; } public function implode_data($data) { $return = array(); foreach($data as $key => $value) $return[] = $key . '="' . $value . '"'; return implode(',', $return); } public function encrypt_password($data, $user, $pass) { foreach(array('realm', 'cnonce', 'digest-uri') as $key) if(!isset($data[$key])) $data[$key] = ''; $pack = md5($user.':'.$data['realm'].':'.$pass); if(isset($data['authzid'])) $a1 = pack('H32',$pack).sprintf(':%s:%s:%s',$data['nonce'],$data['cnonce'],$data['authzid']); else $a1 = pack('H32',$pack).sprintf(':%s:%s',$data['nonce'],$data['cnonce']); $a2 = 'AUTHENTICATE:'.$data['digest-uri']; return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2))); } // // socket senders // protected function send_start_stream($jid) { $this->send_raw($this->get_start_stream($jid)); } public function send_end_stream() { $this->send_raw($this->get_end_stream()); } protected function send_auth_pkt($type, $user, $pass) { $this->send($this->get_auth_pkt($type, $user, $pass)); } protected function send_starttls_pkt() { $this->send($this->get_starttls_pkt()); } protected function send_compress_pkt($method) { $this->send($this->get_compress_pkt($method)); } protected function send_challenge_response($challenge) { $this->send($this->get_challenge_response_pkt($challenge)); } protected function send_bind_pkt($resource) { $this->send($this->get_bind_pkt($resource)); } protected function send_session_pkt() { $this->send($this->get_session_pkt()); } private function do_connect($args) { $socket_path = @$args[0]; if($this->trans->connect($socket_path)) { return array("connected", 1); } else { return array("disconnected", 0); } } // // fsm States // public function setup($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; // someone else already started the stream // even before "connect" was called // must be bosh case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); //print_r($args); return $this->handle_other($event, $args); //return array("setup", 0); break; } } public function connected($event, $args) { switch($event) { case "start_stream": $this->send_start_stream($this->jid); return array("wait_for_stream_start", 1); break; // someone else already started the stream before us // even before "start_stream" was called // must be component case "start_cb": $stanza = $args[0]; return $this->handle_stream_start($stanza); break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("connected", 0); break; } } public function disconnected($event, $args) { switch($event) { case "connect": return $this->do_connect($args); break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("disconnected", 0); break; } } public function wait_for_stream_start($event, $args) { switch($event) { case "start_cb": // TODO: save stream id and other meta info //_debug("stream started"); return "wait_for_stream_features"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_start", 0); break; } } // XEP-0170: Recommended Order of Stream Feature Negotiation public function wait_for_stream_features($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // get starttls requirements $starttls = $stanza->exists('starttls', NS_TLS); $required = $starttls ? ($this->force_tls ? true : ($starttls->exists('required') ? true : false)) : false; if($starttls && $required) { $this->send_starttls_pkt(); return "wait_for_tls_result"; } // handle auth mech $mechs = $stanza->exists('mechanisms', NS_SASL); if($mechs) { $new_state = $this->handle_auth_mechs($stanza, $mechs); return $new_state ? $new_state : "wait_for_sasl_response"; } // post auth $bind = $stanza->exists('bind', NS_BIND) ? true : false; $sess = $stanza->exists('session', NS_SESSION) ? true : false; $comp = $stanza->exists('compression', NS_COMPRESSION_FEATURE) ? true : false; if($bind) { $this->send_bind_pkt($this->resource); return "wait_for_bind_response"; } /*// compression not supported due to bug in php stream filters else if($comp) { $this->send_compress_pkt("zlib"); return "wait_for_compression_result"; }*/ else { _debug("no catch"); } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_stream_features", 0); break; } } public function wait_for_tls_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'proceed' && $stanza->ns == NS_TLS) { $this->trans->crypt(); $this->xml->reset_parser(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } else { // FIXME: here } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_tls_result", 0); break; } } public function wait_for_compression_result($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'compressed' && $stanza->ns == NS_COMPRESSION_PROTOCOL) { $this->xml->reset_parser(); $this->trans->compress(); $this->send_start_stream($this->jid); return "wait_for_stream_start"; } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_compression_result", 0); break; } } public function wait_for_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'failure' && $stanza->ns == NS_SASL) { $reason = $stanza->childrens[0]->name; //_debug("sasl failed with reason ".$reason.""); $this->handle_auth_failure($reason); return "logged_out"; } else if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_challenge_response($challenge); return "wait_for_sasl_response"; } else if($stanza->name == 'success' && $stanza->ns == NS_SASL) { $this->xml->reset_parser(); $this->send_start_stream(@$this->jid); return "wait_for_stream_start"; } else { _debug("got unhandled sasl response"); } return "wait_for_sasl_response"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_sasl_response", 0); break; } } public function wait_for_bind_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // TODO: chk on id if($stanza->name == 'iq' && $stanza->attrs['type'] == 'result' && ($jid = $stanza->exists('bind', NS_BIND)->exists('jid'))) { $this->full_jid = new XMPPJid($jid->text); $this->send_session_pkt(); return "wait_for_session_response"; } else { // FIXME: } break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_bind_response", 0); break; } } public function wait_for_session_response($event, $args) { switch($event) { case "stanza_cb": $this->handle_auth_success(); return "logged_in"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("wait_for_session_response", 0); break; } } public function logged_in($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; // call abstract if($stanza->name == 'message') { $stanza->type = (@$stanza->type ? $stanza->type : 'normal'); $this->handle_message($stanza); } else if($stanza->name == 'presence') { $this->handle_presence($stanza); } else if($stanza->name == 'iq') { $this->handle_iq($stanza); } else { $this->handle_other($event, $args); } return "logged_in"; break; case "end_cb": $this->send_end_stream(); return "logged_out"; break; case "end_stream": $this->send_end_stream(); return "logged_out"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_in", 0); break; } } public function logged_out($event, $args) { switch($event) { case "end_cb": $this->trans->disconnect(); return "disconnected"; break; case "end_stream": return "disconnected"; break; case "disconnect": $this->trans->disconnect(); return "disconnected"; break; default: // exit for any other event in logged_out state _debug("uncatched $event"); return $this->handle_other($event, $args); //return array("logged_out", 0); break; } } } ?>
jaxl/JAXL
54461065900a2108bb6dfc502845996ec352a5a5
added pongs for pings received from the server inside XEP-0199 (XMPP Ping)
diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index c7445d8..25f8e66 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,144 +1,145 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 5) { echo "Usage: $argv[0] jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC - '0203' // Delayed Delivery + '0203', // Delayed Delivery + '0199' // XMPP Ping )); // // add necessary event callbacks here // $_room_full_jid = $argv[3]."/".$argv[4]; $room_full_jid = new XMPPJid($_room_full_jid); $client->add_cb('on_auth_success', function() { global $client, $room_full_jid; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // join muc room $client->xeps['0045']->join_room($room_full_jid); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_groupchat_message', function($stanza) { global $client; $from = new XMPPJid($stanza->from); $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); if($from->resource) { echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } else { $subject = $stanza->exists('subject'); if($subject) { echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } } }); $client->add_cb('on_presence_stanza', function($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster if(strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { if(($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { if(($status = $x->exists('status', null, array('code'=>'110'))) !== false) { $item = $x->exists('item'); _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); } else { _info("xmlns #user have no x child element"); } } else { _warning("=======> odd case 1"); } } // stanza from other users received else if(strtolower($from->bare) == strtolower($room_full_jid->bare)) { if(($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; } else { _warning("=======> odd case 2"); } } else { _warning("=======> odd case 3"); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/jaxl.php b/jaxl.php index 0537089..80219ff 100644 --- a/jaxl.php +++ b/jaxl.php @@ -206,591 +206,593 @@ class JAXL extends XMPPStream { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect(($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port'])) { // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr."), will try again in ".$retry_after." seconds"); // TODO: use sigalrm instead // they usually doesn't gel well inside select loop sleep($retry_after); $this->start(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); if($pref_auth_exists) { // try prefered auth $mech = $pref_auth; } else { // choose one from available mechanisms foreach($mechs as $mech=>$any) { if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new RosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above - if(!$emited) + // TODO: can we add more checks here before calling back + // e.g. checks on existence of an attribute, check on 1st level child ns and so on + if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } // if managing subscription requests // we need to automate stuff here if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { $this->subscribed($stanza->from); if($this->manage_subscribe == "mutual") $this->subscribe($stanza->from); } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?> diff --git a/xep/xep_0199.php b/xep/xep_0199.php index 9896d60..3d60b38 100644 --- a/xep/xep_0199.php +++ b/xep/xep_0199.php @@ -1,50 +1,60 @@ <?php require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_XMPP_PING', 'urn:xmpp:ping'); class XEP_0199 extends XMPPXep { // // abstract method // public function init() { return array( - 'on_auth_success' => 'on_auth_success' + 'on_auth_success' => 'on_auth_success', + 'on_get_iq' => 'on_xmpp_ping' ); } // // api methods // public function get_ping_pkt() { $attrs = array( 'type'=>'get', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$this->jaxl->full_jid->domain ); return $this->jaxl->get_iq_pkt( $attrs, new JAXLXml('ping', NS_XMPP_PING) ); } public function ping() { $this->jaxl->send($this->get_ping_pkt()); } // // event callbacks // public function on_auth_success() { JAXLLoop::$clock->call_fun_periodic(30 * pow(10,6), array(&$this, 'ping')); } + public function on_xmpp_ping($stanza) { + if($stanza->exists('ping', NS_XMPP_PING)) { + $stanza->type = "result"; + $stanza->to = $stanza->from; + $stanza->from = $this->jaxl->full_jid->to_string(); + $this->jaxl->send($stanza); + } + } + } ?>
jaxl/JAXL
93d190e8fdfccb1fab9859f2b7cee3d3f6bb2602
refix for last temporary fix, need some thoughts on JAXLEvent class when callee expects a return value from callbacks
diff --git a/core/jaxl_event.php b/core/jaxl_event.php index b6c0233..4b02d5a 100644 --- a/core/jaxl_event.php +++ b/core/jaxl_event.php @@ -1,115 +1,119 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * following kind of events are possible: * 1) hook i.e. if a callback for such an event is registered, calling function is responsible for the workflow from their on * 2) filter i.e. calling function will manipulate passed arguments and modified arguments will be passed to next chain of filter * * As a rule of thumb, only 1 hook can be registered for an event, while more than 1 filter is allowed for an event * hook and filter both cannot be applied on an event * * @author abhinavsingh * */ class JAXLEvent { public $reg = array(); public function __construct() { } public function __destruct() { } // add callback on a event // returns a reference to be used while deleting callback // callback'd method must return TRUE to be persistent // if none returned or FALSE, callback will be removed automatically public function add($ev, $cb, $pri) { if(!isset($this->reg[$ev])) $this->reg[$ev] = array(); $ref = sizeof($this->reg[$ev]); $this->reg[$ev][] = array($pri, $cb); return $ev."-".$ref; } // emit event to notify registered callbacks // is a pqueue required here for performance enhancement // in case we have too many cbs on a specific event? public function emit($ev, $data=array()) { $cbs = array(); if(!isset($this->reg[$ev])) return $data; foreach($this->reg[$ev] as $cb) { if(!isset($cbs[$cb[0]])) $cbs[$cb[0]] = array(); $cbs[$cb[0]][] = $cb[1]; } foreach($cbs as $pri => $cb) { foreach($cb as $c) { - $data = call_user_func_array($c, $data); - // this line is to a fix, things will change in future - if(!is_array($data)) $data = array(); + $ret = call_user_func_array($c, $data); + // this line is for fixing situation where callback function doesn't return an array type + // in such cases next call of call_user_func_array will report error since $data is not an array type as expected + // things will change in future, atleast put the callback inside a try/catch block + // here we only check if there was a return, if yes we update $data with return value + // this is bad design, need more thoughts, should work as of now + if($ret) $data = $ret; } } unset($cbs); return $data; } // remove previous registered callback public function del($ref) { $ref = explode("-", $ref); unset($this->reg[$ref[0]][$ref[1]]); } public function exists($ev) { $ret = isset($this->reg[$ev]); //_debug("event ".$ev." callback ".($ret ? "exists" : "do not exists")); return $ret; } } ?> diff --git a/examples/curl.php b/examples/curl.php index 50dc5f1..3084179 100644 --- a/examples/curl.php +++ b/examples/curl.php @@ -1,46 +1,46 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once 'jaxl.php'; -JAXLLogger::$level = JAXL_DEBUG; +JAXLLogger::$level = JAXL_INFO; require_once JAXL_CWD.'/http/http_client.php'; $request = new HTTPClient('http://google.com/'); $request->start(); ?> diff --git a/examples/echo_bosh_bot.php b/examples/echo_bosh_bot.php index e19e07e..3c36ee2 100644 --- a/examples/echo_bosh_bot.php +++ b/examples/echo_bosh_bot.php @@ -1,106 +1,108 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // (required) 'bosh_url' => 'http://localhost:5280/http-bind', // (optional) srv lookup is done if not provided // for bosh client 'host' value is used for 'route' attribute //'host' => 'xmpp.domain.tld', // (optional) result from srv lookup used by default // for bosh client 'port' value is used for 'route' attribute //'port' => 5222, // (optional) //'resource' => 'resource', // (optional) defaults to PLAIN if supported, else other methods will be automatically tried 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN', + + 'log_level' => JAXL_INFO )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); $client->set_status("available!", "dnd", 10); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/examples/echo_facebook_client.php b/examples/echo_facebook_client.php index ee2ea55..4e6572a 100644 --- a/examples/echo_facebook_client.php +++ b/examples/echo_facebook_client.php @@ -1,98 +1,100 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc != 4) { echo "Usage: $argv[0] fb_user_id_or_username fb_app_key fb_access_token\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1].'@chat.facebook.com', 'fb_app_key' => $argv[2], 'fb_access_token' => $argv[3], // force tls (facebook require this now) 'force_tls' => true, // (required) force facebook oauth 'auth_type' => 'X-FACEBOOK-PLATFORM', // (optional) - //'resource' => 'resource' + //'resource' => 'resource', + + 'log_level' => JAXL_INFO )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); $client->set_status("available!", "dnd", 10); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/examples/muc_log_bot.php b/examples/muc_log_bot.php index 792d1e0..c7445d8 100644 --- a/examples/muc_log_bot.php +++ b/examples/muc_log_bot.php @@ -1,145 +1,144 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 5) { echo "Usage: $argv[0] jid pass [email protected] nickname\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], - 'log_level' => JAXL_INFO )); $client->require_xep(array( '0045', // MUC '0203' // Delayed Delivery )); // // add necessary event callbacks here // $_room_full_jid = $argv[3]."/".$argv[4]; $room_full_jid = new XMPPJid($_room_full_jid); $client->add_cb('on_auth_success', function() { global $client, $room_full_jid; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // join muc room $client->xeps['0045']->join_room($room_full_jid); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_groupchat_message', function($stanza) { global $client; $from = new XMPPJid($stanza->from); $delay = $stanza->exists('delay', NS_DELAYED_DELIVERY); if($from->resource) { echo "message stanza rcvd from ".$from->resource." saying... ".$stanza->body.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } else { $subject = $stanza->exists('subject'); if($subject) { echo "room subject: ".$subject->text.($delay ? ", delay timestamp ".$delay->attrs['stamp'] : ", timestamp ".gmdate("Y-m-dTH:i:sZ")).PHP_EOL; } } }); $client->add_cb('on_presence_stanza', function($stanza) { global $client, $room_full_jid; $from = new XMPPJid($stanza->from); // self-stanza received, we now have complete room roster if(strtolower($from->to_string()) == strtolower($room_full_jid->to_string())) { if(($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { if(($status = $x->exists('status', null, array('code'=>'110'))) !== false) { $item = $x->exists('item'); _info("xmlns #user exists with x ".$x->ns." status ".$status->attrs['code'].", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role']); } else { _info("xmlns #user have no x child element"); } } else { _warning("=======> odd case 1"); } } // stanza from other users received else if(strtolower($from->bare) == strtolower($room_full_jid->bare)) { if(($x = $stanza->exists('x', NS_MUC.'#user')) !== false) { $item = $x->exists('item'); echo "presence stanza of type ".($stanza->type ? $stanza->type : "available")." received from ".$from->resource.", affiliation:".$item->attrs['affiliation'].", role:".$item->attrs['role'].PHP_EOL; } else { _warning("=======> odd case 2"); } } else { _warning("=======> odd case 3"); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/examples/pipes.php b/examples/pipes.php index e5e76d1..a55e06d 100644 --- a/examples/pipes.php +++ b/examples/pipes.php @@ -1,49 +1,49 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // include and configure logger require_once 'jaxl.php'; -JAXLLogger::$level = JAXL_DEBUG; +JAXLLogger::$level = JAXL_INFO; require_once JAXL_CWD.'/core/jaxl_pipe.php'; $pipe = new JAXLPipe(getmypid()); JAXLLoop::run(); echo "done\n"; ?> diff --git a/examples/publisher.php b/examples/publisher.php index 1a383cd..9c7cf35 100644 --- a/examples/publisher.php +++ b/examples/publisher.php @@ -1,98 +1,99 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], - 'pass' => $argv[2] + 'pass' => $argv[2], + 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // create node //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); // publish $item = new JAXLXml('item', null, array('id'=>time())); $item->c('entry', 'http://www.w3.org/2005/Atom'); $item->c('title')->t('Soliloquy')->up(); $item->c('summary')->t('To be, or not to be: that is the question')->up(); $item->c('link', null, array('rel'=>'alternate', 'type'=>'text/html', 'href'=>'http://denmark.lit/2003/12/13/atom03'))->up(); $item->c('id')->t('tag:denmark.lit,2003:entry-32397')->up(); $item->c('published')->t('2003-12-13T18:30:02Z')->up(); $item->c('updated')->t('2003-12-13T18:30:02Z')->up(); $client->xeps['0060']->publish_item('pubsub.localhost', 'dummy_node', $item); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/examples/subscriber.php b/examples/subscriber.php index f4e52d4..d6cdf2c 100644 --- a/examples/subscriber.php +++ b/examples/subscriber.php @@ -1,98 +1,99 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], - 'pass' => $argv[2] + 'pass' => $argv[2], + 'log_level' => JAXL_INFO )); $client->require_xep(array( '0060' // Publish-Subscribe )); // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // create node //$client->xeps['0060']->create_node('pubsub.localhost', 'dummy_node'); // subscribe $client->xeps['0060']->subscribe('pubsub.localhost', 'dummy_node'); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_headline_message', function($stanza) { global $client; if(($event = $stanza->exists('event', NS_PUBSUB.'#event'))) { _info("got pubsub event"); } else { _warning("unknown headline message rcvd"); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/examples/xmpp_rest.php b/examples/xmpp_rest.php index 2504734..9d10653 100644 --- a/examples/xmpp_rest.php +++ b/examples/xmpp_rest.php @@ -1,76 +1,77 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ // View explanation for this example here: // https://groups.google.com/d/msg/jaxl/QaGjZP4A2gY/n6SYutrBVxsJ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // initialize xmpp client require_once 'jaxl.php'; $xmpp = new JAXL(array( 'jid' => $argv[1], - 'pass' => $argv[2] + 'pass' => $argv[2], + 'log_level' => JAXL_INFO )); // register callbacks on required xmpp events $xmpp->add_cb('on_auth_success', function() { global $xmpp; _info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string()); }); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); // add generic callback // you can also dispatch REST style callback // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules $http->cb = function($request) { // For demo purposes we simply return xmpp client full jid global $xmpp; $request->ok($xmpp->full_jid->to_string()); }; // This will start main JAXLLoop, // hence we don't need to call $http->start() explicitly $xmpp->start(); ?>
jaxl/JAXL
900c310583f89b4991db428782a4e552e265dc5c
added manage_subscribe constructor option which will automate stuff for received subscription requests, allowed values are "accept" and "mutual", while it defaults to "none"
diff --git a/jaxl.php b/jaxl.php index 73b910a..0537089 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,788 +1,796 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * * @author abhinavsingh */ class RosterItem { public $jid = null; public $subscription = null; public $groups = array(); public $resources = array(); public $vcard = null; public function __construct($jid, $subscription, $groups) { $this->jid = $jid; $this->subscription = $subscription; $this->groups = $groups; } } /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.0-alpha-1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests - // "none" | "accept" | "accept_and_add" - public $subscription = "none"; + // "none" | "accept" | "mutual" + public $manage_subscribe = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { // env $this->cfg = $config; $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // initialize core modules $this->ev = new JAXLEvent(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if(!$host && !$port && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = $host; $this->cfg['port'] = $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function subscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribe') )); } public function subscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'subscribed') )); } public function unsubscribe($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribe') )); } public function unsubscribed($to) { $this->send($this->get_pres_pkt( array('to'=>$to, 'type'=>'unsubscribed') )); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect(($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port'])) { // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr."), will try again in ".$retry_after." seconds"); // TODO: use sigalrm instead // they usually doesn't gel well inside select loop sleep($retry_after); $this->start(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); if($pref_auth_exists) { // try prefered auth $mech = $pref_auth; } else { // choose one from available mechanisms foreach($mechs as $mech=>$any) { if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new RosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } + // if managing subscription requests + // we need to automate stuff here + if($stanza->type == "subscribe" && $this->manage_subscribe != "none") { + $this->subscribed($stanza->from); + if($this->manage_subscribe == "mutual") + $this->subscribe($stanza->from); + } + $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?>
jaxl/JAXL
c51347268556b42ef1cc3175b2be21da70c0422e
added subscription related methods inside JAXL class
diff --git a/examples/register_user.php b/examples/register_user.php index 9fc655f..4fbc950 100644 --- a/examples/register_user.php +++ b/examples/register_user.php @@ -1,138 +1,138 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 2) { echo "Usage: $argv[0] domain\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( 'jid' => $argv[1], - 'log_path' => JAXL_CWD.'/.jaxl/log/jaxl.log' + 'log_level' => JAXL_INFO )); $client->require_xep(array( '0077' // InBand Registration )); // // below are two states which become part of // our client's xmpp_stream lifecycle // consider as if these methods are directly // inside xmpp_stream state machine // // Note: $stanza = $args[0] is an instance of // JAXLXml in xmpp_stream state methods, // it is yet not ready for easy access // patterns available on XMPPStanza instances // function wait_for_register_response($event, $args) { global $client; if($event == 'end_stream') { exit; } else if($event == 'stanza_cb') { $stanza = $args[0]; if($stanza->name == 'iq') { if($stanza->attrs['type'] == 'result') { echo "registration successful".PHP_EOL."shutting down...".PHP_EOL; $client->end_stream(); return "logged_out"; } else if($stanza->attrs['type'] == 'error') { $error = $stanza->exists('error'); echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL; echo "error text: ".$error->exists('text')->text.PHP_EOL; echo "shutting down...".PHP_EOL; $client->end_stream(); return "logged_out"; } } } } function wait_for_register_form($event, $args) { global $client; $stanza = $args[0]; $query = $stanza->exists('query', NS_INBAND_REGISTER); if($query) { $form = array(); $instructions = $query->exists('instructions'); if($instructions) { echo $instructions->text.PHP_EOL; } foreach($query->childrens as $k=>$child) { if($child->name != 'instructions') { $form[$child->name] = readline($child->name.":"); } } $client->xeps['0077']->set_form($stanza->attrs['from'], $form); return "wait_for_register_response"; } else { $client->end_stream(); return "logged_out"; } } // // add necessary event callbacks here // $client->add_cb('on_stream_features', function($stanza) { global $client, $argv; $client->xeps['0077']->get_form($argv[1]); return "wait_for_register_form"; }); // // finally start configured xmpp stream // $client->start(); echo "done\n"; ?> diff --git a/jaxl.php b/jaxl.php index ebcb5d4..73b910a 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,764 +1,788 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * * @author abhinavsingh */ class RosterItem { public $jid = null; public $subscription = null; public $groups = array(); public $resources = array(); public $vcard = null; public function __construct($jid, $subscription, $groups) { $this->jid = $jid; $this->subscription = $subscription; $this->groups = $groups; } } /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.0-alpha-1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "accept_and_add" public $subscription = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { // env $this->cfg = $config; $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // initialize core modules $this->ev = new JAXLEvent(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if(!$host && !$port && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = $host; $this->cfg['port'] = $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } + public function subscribe($to) { + $this->send($this->get_pres_pkt( + array('to'=>$to, 'type'=>'subscribe') + )); + } + + public function subscribed($to) { + $this->send($this->get_pres_pkt( + array('to'=>$to, 'type'=>'subscribed') + )); + } + + public function unsubscribe($to) { + $this->send($this->get_pres_pkt( + array('to'=>$to, 'type'=>'unsubscribe') + )); + } + + public function unsubscribed($to) { + $this->send($this->get_pres_pkt( + array('to'=>$to, 'type'=>'unsubscribed') + )); + } + public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect(($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port'])) { // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr."), will try again in ".$retry_after." seconds"); // TODO: use sigalrm instead // they usually doesn't gel well inside select loop sleep($retry_after); $this->start(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( - 'unix://'.$this->get_sock_file_path(), - array(&$this, 'on_unix_sock_accept'), - array(&$this, 'on_unix_sock_request') + 'unix://'.$this->get_sock_file_path(), + array(&$this, 'on_unix_sock_accept'), + array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); if($pref_auth_exists) { // try prefered auth $mech = $pref_auth; } else { // choose one from available mechanisms foreach($mechs as $mech=>$any) { if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new RosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?>
jaxl/JAXL
07b6d0b6a5ee75acdbe4ba2fe55e99082cba1161
fixed typo inside xep-0030
diff --git a/xep/xep_0030.php b/xep/xep_0030.php index 1f9df48..2a9c7f8 100644 --- a/xep/xep_0030.php +++ b/xep/xep_0030.php @@ -1,92 +1,92 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; define('NS_DISCO_INFO', 'http://jabber.org/protocol/disco#info'); define('NS_DISCO_ITEMS', 'http://jabber.org/protocol/disco#items'); class XEP_0030 extends XMPPXep { // // abstract method // public function init() { return array( ); } // // api methods // public function get_info_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( array('type'=>'get', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$entity_jid), - new JAXLXml('iq', NS_DISCO_INFO) + new JAXLXml('query', NS_DISCO_INFO) ); } public function get_info($entity_jid, $callback=null) { $pkt = $this->get_info_pkt($entity_jid); if($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } public function get_items_pkt($entity_jid) { return $this->jaxl->get_iq_pkt( array('type'=>'get', 'from'=>$this->jaxl->full_jid->to_string(), 'to'=>$entity_jid), - new JAXLXml('iq', NS_DISCO_ITEMS) + new JAXLXml('query', NS_DISCO_ITEMS) ); } public function get_items($entity_jid, $callback=null) { $pkt = $this->get_items_pkt($entity_jid); if($callback) $this->jaxl->add_cb('on_stanza_id_'.$pkt->id, $callback); $this->jaxl->send($pkt); } // // event callbacks // } ?>
jaxl/JAXL
3c08c30e639b403244c2b01af8dbd5d0118f0d0c
added default values for show and priority inside set_status method
diff --git a/jaxl.php b/jaxl.php index 6d314ff..ebcb5d4 100644 --- a/jaxl.php +++ b/jaxl.php @@ -1,764 +1,764 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ date_default_timezone_set("UTC"); declare(ticks = 1); define('JAXL_CWD', dirname(__FILE__)); require_once JAXL_CWD.'/core/jaxl_exception.php'; require_once JAXL_CWD.'/core/jaxl_cli.php'; require_once JAXL_CWD.'/core/jaxl_loop.php'; require_once JAXL_CWD.'/xmpp/xmpp_stream.php'; require_once JAXL_CWD.'/core/jaxl_event.php'; require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/core/jaxl_socket_server.php'; /** * * @author abhinavsingh */ class RosterItem { public $jid = null; public $subscription = null; public $groups = array(); public $resources = array(); public $vcard = null; public function __construct($jid, $subscription, $groups) { $this->jid = $jid; $this->subscription = $subscription; $this->groups = $groups; } } /** * Jaxl class extends base XMPPStream class with following functionalities: * 1) Adds an event based wrapper over xmpp stream lifecycle * 2) Provides restart strategy and signal handling to ensure connectivity of xmpp stream * 3) Roster management as specified in XMPP-IM * 4) Management of XEP's inside xmpp stream lifecycle * 5) Adds a logging facility * 6) Adds a cron job facility in sync with connected xmpp stream timeline * * @author abhinavsingh * */ class JAXL extends XMPPStream { // lib meta info const version = '3.0.0-alpha-1'; const name = 'JAXL :: Jabber XMPP Library'; // cached init config array public $cfg = array(); // event callback engine for xmpp stream lifecycle protected $ev = null; // reference to various xep instance objects public $xeps = array(); // local cache of roster list public $roster = array(); // whether jaxl must also populate local roster cache with // received presence information about the contacts public $manage_roster = true; // what to do with presence sub requests // "none" | "accept" | "accept_and_add" public $subscription = "none"; // path variables public $log_level = JAXL_INFO; public $priv_dir; public $tmp_dir; public $log_dir; public $pid_dir; public $sock_dir; // ipc utils private $sock; private $cli; // env public $local_ip; public $pid; public $mode; // current status message public $status; // identity public $features = array(); public $category = 'client'; public $type = 'bot'; public $lang = 'en'; // after cth failed attempt // retry connect after k * $retry_interval seconds // where k is a random number between 0 and 2^c - 1. public $retry = true; private $retry_interval = 1; private $retry_attempt = 0; private $retry_max_interval = 32; // 2^5 seconds (means 5 max tries) public function __construct($config) { // env $this->cfg = $config; $this->mode = PHP_SAPI; $this->local_ip = gethostbyname(php_uname('n')); $this->pid = getmypid(); // initialize core modules $this->ev = new JAXLEvent(); // jid object $jid = @$this->cfg['jid'] ? new XMPPJid($this->cfg['jid']) : null; // handle signals if(extension_loaded('pcntl')) { pcntl_signal(SIGHUP, array($this, 'signal_handler')); pcntl_signal(SIGINT, array($this, 'signal_handler')); pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if(!$host && !$port && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = $host; $this->cfg['port'] = $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } - public function set_status($status, $show, $priority) { + public function set_status($status, $show='chat', $priority=10) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect(($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port'])) { // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr."), will try again in ".$retry_after." seconds"); // TODO: use sigalrm instead // they usually doesn't gel well inside select loop sleep($retry_after); $this->start(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); if($pref_auth_exists) { // try prefered auth $mech = $pref_auth; } else { // choose one from available mechanisms foreach($mechs as $mech=>$any) { if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { $groups[] = $group->text; } } $this->roster[$jid] = new RosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?>
jaxl/JAXL
4e54b0b7019ec7d38198f3f9e9780e1ec9efdba4
fixes #13
diff --git a/core/jaxl_xml.php b/core/jaxl_xml.php index 36b0d8f..a3e8b03 100644 --- a/core/jaxl_xml.php +++ b/core/jaxl_xml.php @@ -1,221 +1,221 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * * Usage: * ------ * JAXLXml($name, $ns, $attrs, $text) * JAXLXml($name, $ns, $attrs) * JAXLXml($name, $ns, $text) * JAXLXml($name, $attrs, $text) * JAXLXml($name, $attrs) * JAXLXml($name, $ns) * JAXLXml($name) * * @author abhinavsingh * */ class JAXLXml { public $name; public $ns = null; public $attrs = array(); public $text = null; public $childrens = array(); public $parent = null; public $rover = null; public function __construct() { $argv = func_get_args(); $argc = sizeof($argv); $this->name = $argv[0]; switch($argc) { case 4: $this->ns = $argv[1]; $this->attrs = $argv[2]; $this->text = $argv[3]; break; case 3: if(is_array($argv[1])) { $this->attrs = $argv[1]; $this->text = $argv[2]; } else { $this->ns = $argv[1]; if(is_array($argv[2])) { $this->attrs = $argv[2]; } else { $this->text = $argv[2]; } } break; case 2: if(is_array($argv[1])) { $this->attrs = $argv[1]; } else { $this->ns = $argv[1]; } break; default: break; } $this->rover = &$this; } public function __destruct() { } // merge new attrs with attributes of current rover public function attrs($attrs) { $this->rover->attrs = array_merge($this->rover->attrs, $attrs); return $this; } // pass a kv pair of attrs // this function return bool if all attribute // keys passed matches their respective values public function match_attrs($attrs) { $matches = true; foreach($attrs as $k=>$v) { if($this->attrs[$k] !== $v) { $matches = false; break; } } return $matches; } // update text of current rover public function t($text, $append=FALSE) { if(!$append) { $this->rover->text = $text; } else { if($this->rover->text === null) $this->rover->text = ''; $this->rover->text .= $text; } return $this; } // append a child node at current rover public function c($name, $ns=null, $attrs=array(), $text=null) { $node = new JAXLXml($name, $ns, $attrs, $text); $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } // append a JAXLXml object at current rover public function cnode($node) { $node->parent = &$this->rover; $this->rover->childrens[] = &$node; $this->rover = &$node; return $this; } // move rover to one step up public function up() { if($this->rover->parent) $this->rover = &$this->rover->parent; return $this; } // move rover back to top element public function top() { $this->rover = &$this; return $this; } // checks if a child with $name exists // return child XmlStanza if found otherwise false // NOTE: if multiple children exists with same name, // this function returns on first child check public function exists($name, $ns=null, $attrs=array()) { foreach($this->childrens as $child) { if($ns) { if($child->name == $name && $child->ns == $ns && $child->match_attrs($attrs)) return $child; } else if($child->name == $name && $child->match_attrs($attrs)) { return $child; } } return false; } // update child element public function update($name, $ns=null, $attrs=array(), $text=null) { foreach($this->childrens as $k=>$child) { if($child->name == $name) { $child->ns = $ns; $child->attrs($attrs); $child->text = $text; $this->childrens[$k] = $child; break; } } } // to string conversion public function to_string($parent_ns=null) { $xml = ''; $xml .= '<'.$this->name; if($this->ns && $this->ns != $parent_ns) $xml .= ' xmlns="'.$this->ns.'"'; - foreach($this->attrs as $k=>$v) if(!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.$v.'"'; + foreach($this->attrs as $k=>$v) if(!is_null($v) && $v !== FALSE) $xml .= ' '.$k.'="'.htmlspecialchars($v).'"'; $xml .= '>'; foreach($this->childrens as $child) $xml .= $child->to_string($this->ns); - if($this->text) $xml .= $this->text; + if($this->text) $xml .= htmlspecialchars($this->text); $xml .= '</'.$this->name.'>'; return $xml; } } ?>
jaxl/JAXL
0faa8951acd5e75ddf3a271b93696c4358b64a3e
linking examples inside readme
diff --git a/README.md b/README.md index b5572b9..72a393d 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,29 @@ Jaxl v3.x: ----------- Jaxl v3.x is a successor of v2.x (and is NOT backward compatible), carrying a lot of code from v2.x while throwing away the ugly parts. A lot of components have been re-written keeping in mind the feedback from the developer community over the last 4 years. Also Jaxl shares a few philosophies from my experience with erlang and python languages. Jaxl is an asynchronous, non-blocking I/O, event based PHP library for writing custom TCP/IP client and server implementations. From it's previous versions, library inherits a full blown stable support for XMPP protocol stack. In v3.0, support for HTTP protocol stack was also added. At the heart of every protocol stack sits a Core stack. It contains all the building blocks for everything that we aim to do with Jaxl library. Both XMPP and HTTP protocol stacks are written on top of the Core stack. Infact the source code of protocol implementations knows nothing about the standard (inbuilt) PHP socket and stream methods. +[Examples](https://github.com/abhinavsingh/JAXL/tree/v3.x/examples/) + [Documentation](http://jaxl.readthedocs.org/) [Group and Mailing List](https://groups.google.com/forum/#!forum/jaxl) [Create a bug/issue](https://github.com/abhinavsingh/JAXL/issues/new) [Author](http://abhinavsingh.com/) \ No newline at end of file
jaxl/JAXL
775b738735a1b1880dab32127f2201ba0ffe5d7c
added link to xmpp rest example explanation
diff --git a/examples/xmpp_rest.php b/examples/xmpp_rest.php index f1a2329..2504734 100644 --- a/examples/xmpp_rest.php +++ b/examples/xmpp_rest.php @@ -1,74 +1,76 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ +// View explanation for this example here: +// https://groups.google.com/d/msg/jaxl/QaGjZP4A2gY/n6SYutrBVxsJ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // initialize xmpp client require_once 'jaxl.php'; $xmpp = new JAXL(array( 'jid' => $argv[1], 'pass' => $argv[2] )); // register callbacks on required xmpp events $xmpp->add_cb('on_auth_success', function() { global $xmpp; _info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string()); }); // initialize http server require_once JAXL_CWD.'/http/http_server.php'; $http = new HTTPServer(); // add generic callback // you can also dispatch REST style callback // Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules $http->cb = function($request) { // For demo purposes we simply return xmpp client full jid global $xmpp; $request->ok($xmpp->full_jid->to_string()); }; // This will start main JAXLLoop, // hence we don't need to call $http->start() explicitly $xmpp->start(); ?>
jaxl/JAXL
f92670a1d739ce6243bf05ea746e9b4f0c68c6a1
in 7 lines of code, demonstrating how you can control your background XMPP daemons via a HTTP interface
diff --git a/examples/xmpp_rest.php b/examples/xmpp_rest.php new file mode 100644 index 0000000..f1a2329 --- /dev/null +++ b/examples/xmpp_rest.php @@ -0,0 +1,74 @@ +<?php +/** + * Jaxl (Jabber XMPP Library) + * + * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Abhinav Singh nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +if($argc < 3) { + echo "Usage: $argv[0] jid pass\n"; + exit; +} + +// initialize xmpp client +require_once 'jaxl.php'; +$xmpp = new JAXL(array( + 'jid' => $argv[1], + 'pass' => $argv[2] +)); + +// register callbacks on required xmpp events +$xmpp->add_cb('on_auth_success', function() { + global $xmpp; + _info("got on_auth_success cb, jid ".$xmpp->full_jid->to_string()); +}); + +// initialize http server +require_once JAXL_CWD.'/http/http_server.php'; +$http = new HTTPServer(); + +// add generic callback +// you can also dispatch REST style callback +// Refer: http://jaxl.readthedocs.org/en/latest/users/http_extensions.html#dispatch-rules +$http->cb = function($request) { + // For demo purposes we simply return xmpp client full jid + global $xmpp; + $request->ok($xmpp->full_jid->to_string()); +}; + +// This will start main JAXLLoop, +// hence we don't need to call $http->start() explicitly +$xmpp->start(); + +?> diff --git a/http/http_server.php b/http/http_server.php index c745f2a..e5f00b9 100644 --- a/http/http_server.php +++ b/http/http_server.php @@ -1,197 +1,197 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_logger.php'; require_once JAXL_CWD.'/http/http_dispatcher.php'; require_once JAXL_CWD.'/http/http_request.php'; // carriage return and line feed define('HTTP_CRLF', "\r\n"); // 1xx informational define('HTTP_100', "Continue"); define('HTTP_101', "Switching Protocols"); // 2xx success define('HTTP_200', "OK"); // 3xx redirection define('HTTP_301', 'Moved Permanently'); define('HTTP_304', 'Not Modified'); // 4xx client error define('HTTP_400', 'Bad Request'); define('HTTP_403', 'Forbidden'); define('HTTP_404', 'Not Found'); define('HTTP_405', 'Method Not Allowed'); define('HTTP_499', 'Client Closed Request'); // Nginx // 5xx server error define('HTTP_500', 'Internal Server Error'); define('HTTP_503', 'Service Unavailable'); class HTTPServer { private $server = null; - private $cb = null; + public $cb = null; private $dispatcher = null; private $requests = array(); public function __construct($port=9699, $address="127.0.0.1") { $path = 'tcp://'.$address.':'.$port; $this->server = new JAXLSocketServer( $path, array(&$this, 'on_accept'), array(&$this, 'on_request') ); $this->dispatcher = new HTTPDispatcher(); } public function __destruct() { $this->server = null; } public function dispatch($rules) { foreach($rules as $rule) { $this->dispatcher->add_rule($rule); } } public function start($cb=null) { $this->cb = $cb; JAXLLoop::run(); } public function on_accept($sock, $addr) { _debug("on_accept for client#$sock, addr:$addr"); // initialize new request obj $request = new HTTPRequest($sock, $addr); // setup sock cb $request->set_sock_cb( array(&$this->server, 'send'), array(&$this->server, 'read'), array(&$this->server, 'close') ); // cache request object $this->requests[$sock] = &$request; // reactive client for further read $this->server->read($sock); } public function on_request($sock, $raw) { _debug("on_request for client#$sock"); $request = $this->requests[$sock]; // 'wait_for_body' state is reached when ever // application calls recv_body() method // on received $request object if($request->state() == 'wait_for_body') { $request->body($raw); } else { // break on crlf $lines = explode(HTTP_CRLF, $raw); // parse request line if($request->state() == 'wait_for_request_line') { list($method, $resource, $version) = explode(" ", $lines[0]); $request->line($method, $resource, $version); unset($lines[0]); _info($request->ip." ".$request->method." ".$request->resource." ".$request->version); } // parse headers foreach($lines as $line) { $line_parts = explode(":", $line); if(sizeof($line_parts) > 1) { if(strlen($line_parts[0]) > 0) { $k = $line_parts[0]; unset($line_parts[0]); $v = implode(":", $line_parts); $request->set_header($k, $v); } } else if(strlen(trim($line_parts[0])) == 0) { $request->empty_line(); } // if exploded line array size is 1 // and thr is something in $line_parts[0] // must be request body else { $request->body($line); } } } // if request has reached 'headers_received' state? if($request->state() == 'headers_received') { // dispatch to any matching rule found _debug("delegating to dispatcher for further routing"); $dispatched = $this->dispatcher->dispatch($request); // if no dispatch rule matched call generic callback if(!$dispatched && $this->cb) { _debug("no dispatch rule matched, sending to generic callback"); call_user_func($this->cb, $request); } // else if not dispatched and not generic callbacked // send 404 not_found else if(!$dispatched) { // TODO: send 404 if no callback is registered for this request _debug("dropping request since no matching dispatch rule or generic callback was specified"); $request->not_found('404 Not Found'); } } // if state is not 'headers_received' // reactivate client socket for read event else { $this->server->read($sock); } } } ?>
jaxl/JAXL
a4b76e7ff9d474274f0eff9f596feaa1bdb62151
this is how JAXLPipe will be when complete
diff --git a/core/jaxl_pipe.php b/core/jaxl_pipe.php index 07e25c0..07880db 100644 --- a/core/jaxl_pipe.php +++ b/core/jaxl_pipe.php @@ -1,92 +1,99 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ require_once JAXL_CWD.'/core/jaxl_loop.php'; /** * bidirectional communication pipes for processes + * + * This is how this will be (when complete): + * $pipe = new JAXLPipe() will return an array of size 2 + * $pipe[0] represents the read end of the pipe + * $pipe[1] represents the write end of the pipe * + * Proposed functionality might even change (currently consider this as experimental) + * * @author abhinavsingh * */ class JAXLPipe { protected $name = null; protected $perm = 0600; protected $fd = null; public function __construct($name, $perm=0600) { $this->name = $name; $this->perm = $perm; $pipe_path = $this->get_pipe_file_path(); if(!file_exists($pipe_path)) { posix_mkfifo($pipe_path, $this->perm); $this->fd = fopen($pipe_path, 'r+'); if(!$this->fd) _error("unable to open pipe"); stream_set_blocking($this->fd, false); // watch for incoming data on pipe JAXLLoop::watch($this->fd, array( 'read' => array(&$this, 'on_read_ready') )); } else { _error("pipe with name $name already exists"); } } public function get_pipe_file_path() { return JAXL_CWD.'/.jaxl/pipes/jaxl_'.$this->name.'.pipe'; } public function __destruct() { @fclose($this->fd); @unlink($this->get_pipe_file_path()); _debug("unlinking pipe file"); } public function on_read_ready($fd) { $data = fread($fd, 1024); _debug($data); } } ?>
jaxl/JAXL
4bd4380a6a0c13df7987a3f73c53c6fdc3e618df
fixes #12
diff --git a/jaxl.php b/jaxl.php index 0a88e16..6d314ff 100644 --- a/jaxl.php +++ b/jaxl.php @@ -160,605 +160,605 @@ class JAXL extends XMPPStream { pcntl_signal(SIGTERM, array($this, 'signal_handler')); } // create .jaxl directory in JAXL_CWD // for our /tmp, /run and /log folders // overwrite these using jaxl config array $this->priv_dir = @$this->cfg['priv_dir'] ? $this->cfg['priv_dir'] : JAXL_CWD."/.jaxl"; $this->tmp_dir = $this->priv_dir."/tmp"; $this->pid_dir = $this->priv_dir."/run"; $this->log_dir = $this->priv_dir."/log"; $this->sock_dir = $this->priv_dir."/sock"; if(!is_dir($this->priv_dir)) mkdir($this->priv_dir); if(!is_dir($this->tmp_dir)) mkdir($this->tmp_dir); if(!is_dir($this->pid_dir)) mkdir($this->pid_dir); if(!is_dir($this->log_dir)) mkdir($this->log_dir); if(!is_dir($this->sock_dir)) mkdir($this->sock_dir); // setup logger if(isset($this->cfg['log_path'])) JAXLLogger::$path = $this->cfg['log_path']; //else JAXLLogger::$path = $this->log_dir."/jaxl.log"; if(isset($this->cfg['log_level'])) JAXLLogger::$level = $this->log_level = $this->cfg['log_level']; else JAXLLogger::$level = $this->log_level; // touch pid file if($this->mode == "cli") { touch($this->get_pid_file_path()); _info("created pid file ".$this->get_pid_file_path()); } // include mandatory xmpp xeps // service discovery and entity caps // are recommended for every xmpp entity $this->require_xep(array('0030', '0115')); // do dns lookup, update $cfg['host'] and $cfg['port'] if not already specified $host = @$this->cfg['host']; $port = @$this->cfg['port']; if(!$host && !$port && $jid) { // this dns lookup is blocking _info("dns srv lookup for ".$jid->domain); list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); } $this->cfg['host'] = $host; $this->cfg['port'] = $port; // choose appropriate transport // if 'bosh_url' cfg is defined include 0206 if(@$this->cfg['bosh_url']) { _debug("including bosh xep"); $this->require_xep('0206'); $transport = $this->xeps['0206']; } else { list($host, $port) = JAXLUtil::get_dns_srv($jid->domain); $stream_context = @$this->cfg['stream_context']; $transport = new JAXLSocketClient($stream_context); } // initialize xmpp stream with configured transport parent::__construct( $transport, $jid, @$this->cfg['pass'], @$this->cfg['resource'] ? 'jaxl#'.$this->cfg['resource'] : 'jaxl#'.md5(time()), @$this->cfg['force_tls'] ); } public function __destruct() { // delete pid file _info("cleaning up pid and unix sock files"); @unlink($this->get_pid_file_path()); @unlink($this->get_sock_file_path()); parent::__destruct(); } public function get_pid_file_path() { return $this->pid_dir."/jaxl_".$this->pid.".pid"; } public function get_sock_file_path() { return $this->sock_dir."/jaxl_".$this->pid.".sock"; } public function require_xep($xeps) { if(!is_array($xeps)) $xeps = array($xeps); foreach($xeps as $xep) { $filename = 'xep_'.$xep.'.php'; $classname = 'XEP_'.$xep; // include xep require_once JAXL_CWD.'/xep/'.$filename; $this->xeps[$xep] = new $classname($this); // add necessary requested callback on events foreach($this->xeps[$xep]->init() as $ev=>$cb) { $this->add_cb($ev, array($this->xeps[$xep], $cb)); } } } public function add_cb($ev, $cb, $pri=1) { return $this->ev->add($ev, $cb, $pri); } public function del_cb($ref) { $this->ev->del($ref); } public function set_status($status, $show, $priority) { $this->send($this->get_pres_pkt( array(), $status, $show, $priority )); } public function send_chat_msg($to, $body, $thread=null, $subject=null) { $msg = new XMPPMsg( array( 'type'=>'chat', 'to'=>$to, 'from'=>$this->full_jid->to_string() ), $body, $thread, $subject ); $this->send($msg); } public function get_vcard($jid=null, $cb=null) { $attrs = array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ); if($jid) { $jid = new XMPPJid($jid); $attrs['to'] = $jid->node."@".$jid->domain; } $pkt = $this->get_iq_pkt( $attrs, new JAXLXml('vCard', 'vcard-temp') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function get_roster($cb=null) { $pkt = $this->get_iq_pkt( array( 'type'=>'get', 'from'=>$this->full_jid->to_string() ), new JAXLXml('query', 'jabber:iq:roster') ); if($cb) $this->add_cb('on_stanza_id_'.$pkt->id, $cb); $this->send($pkt); } public function start($opts=array()) { // is bosh bot? if(@$this->cfg['bosh_url']) { $this->trans->session_start(); for(;;) { // while any of the curl request is pending // keep receiving response while(sizeof($this->trans->chs) != 0) { $this->trans->recv(); } // if no request in queue, ping bosh end point // and repeat recv $this->trans->ping(); } $this->trans->session_end(); return; } // is xmpp client or component? // if on_connect event have no callbacks // set default on_connect callback to $this->start_stream() // i.e. xmpp client mode if(!$this->ev->exists('on_connect')) $this->add_cb('on_connect', array($this, 'start_stream')); // connect to the destination host/port if($this->connect(($this->cfg['port'] == 5223 ? "ssl" : "tcp")."://".$this->cfg['host'].":".$this->cfg['port'])) { // emit $this->ev->emit('on_connect'); // parse opts if(@$opts['--with-debug-shell']) $this->enable_debug_shell(); if(@$opts['--with-unix-sock']) $this->enable_unix_sock(); // run main loop JAXLLoop::run(); // emit $this->ev->emit('on_disconnect'); } // if connection to the destination fails else { if($this->trans->errno == 61 || $this->trans->errno == 110 || $this->trans->errno == 111 ) { $retry_after = pow(2, $this->retry_attempt) * $this->retry_interval; $this->retry_attempt++; _debug("unable to connect with errno ".$this->trans->errno." (".$this->trans->errstr."), will try again in ".$retry_after." seconds"); // TODO: use sigalrm instead // they usually doesn't gel well inside select loop sleep($retry_after); $this->start(); } else { $this->ev->emit('on_connect_error', array( $this->trans->errno, $this->trans->errstr )); } } } // // callback methods // // signals callback handler // not for public api consumption public function signal_handler($sig) { $this->end_stream(); $this->disconnect(); $this->ev->emit('on_disconnect'); switch($sig) { // terminal line hangup case SIGHUP: _debug("got sighup"); break; // interrupt program case SIGINT: _debug("got sigint"); break; // software termination signal case SIGTERM: _debug("got sigterm"); break; } exit; } // called internally for ipc // not for public consumption public function on_unix_sock_accept($_c, $addr) { $this->sock->read($_c); } // this currently simply evals the incoming raw string // know what you are doing while in production public function on_unix_sock_request($_c, $_raw) { _debug("evaling raw string rcvd over unix sock: ".$_raw); $this->sock->send($_c, serialize(eval($_raw))); $this->sock->read($_c); } public function enable_unix_sock() { $this->sock = new JAXLSocketServer( 'unix://'.$this->get_sock_file_path(), array(&$this, 'on_unix_sock_accept'), array(&$this, 'on_unix_sock_request') ); } // this simply eval the incoming raw data // inside current jaxl environment // security is all upto you, no checks made here public function handle_debug_shell($_raw) { print_r(eval($_raw)); echo PHP_EOL; JAXLCli::prompt(); } protected function enable_debug_shell() { $this->cli = new JAXLCli(array(&$this, 'handle_debug_shell')); JAXLCli::prompt(); } // // abstract method implementation // protected function send_fb_challenge_response($challenge) { $this->send($this->get_fb_challenge_response_pkt($challenge)); } // refer https://developers.facebook.com/docs/chat/#jabber public function get_fb_challenge_response_pkt($challenge) { $stanza = new JAXLXml('response', NS_SASL); $challenge = base64_decode($challenge); $challenge = urldecode($challenge); parse_str($challenge, $challenge_arr); $response = http_build_query(array( 'method' => $challenge_arr['method'], 'nonce' => $challenge_arr['nonce'], 'access_token' => $this->cfg['fb_access_token'], 'api_key' => $this->cfg['fb_app_key'], 'call_id' => 0, 'v' => '1.0' )); $stanza->t(base64_encode($response)); return $stanza; } public function wait_for_fb_sasl_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $this->send_fb_challenge_response($challenge); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // someday this needs to go inside xmpp stream public function wait_for_cram_md5_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = base64_decode($stanza->text); $resp = new JAXLXml('response', NS_SASL); $resp->t(base64_encode($this->jid->to_string().' '.hash_hmac('md5', $challenge, $this->pass))); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } // http://tools.ietf.org/html/rfc5802#section-5 public function get_scram_sha1_response($pass, $challenge) { // it contains users iteration count i and the user salt // also server will append it's own nonce to the one we specified $decoded = $this->explode_data(base64_decode($challenge)); // r=,s=,i= $nonce = $decoded['r']; $salt = base64_decode($decoded['s']); $iteration = intval($decoded['i']); // SaltedPassword := Hi(Normalize(password), salt, i) $salted = JAXLUtil::pbkdf2($this->pass, $salt, $iteration); // ClientKey := HMAC(SaltedPassword, "Client Key") $client_key = hash_hmac('sha1', $salted, "Client Key", true); // StoredKey := H(ClientKey) $stored_key = hash('sha1', $client_key, true); // AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof $auth_message = ''; // ClientSignature := HMAC(StoredKey, AuthMessage) $signature = hash_hmac('sha1', $stored_key, $auth_message, true); // ClientProof := ClientKey XOR ClientSignature $client_proof = $client_key ^ $signature; $proof = 'c=biws,r='.$nonce.',p='.base64_encode($client_proof); return base64_encode($proof); } public function wait_for_scram_sha1_response($event, $args) { switch($event) { case "stanza_cb": $stanza = $args[0]; if($stanza->name == 'challenge' && $stanza->ns == NS_SASL) { $challenge = $stanza->text; $resp = new JAXLXml('response', NS_SASL); $resp->t($this->get_scram_sha1_response($this->pass, $challenge)); $this->send($resp); return "wait_for_sasl_response"; } else { _debug("got unhandled sasl response, should never happen here"); exit; } break; default: _debug("not catched $event, should never happen here"); exit; break; } } public function handle_auth_mechs($stanza, $mechanisms) { if($this->ev->exists('on_stream_features')) { return $this->ev->emit('on_stream_features', array($stanza)); } $mechs = array(); if($mechanisms) foreach($mechanisms->childrens as $mechanism) $mechs[$mechanism->text] = true; $pref_auth = @$this->cfg['auth_type'] ? $this->cfg['auth_type'] : 'PLAIN'; $pref_auth_exists = isset($mechs[$pref_auth]) ? true : false; _debug("pref_auth ".$pref_auth." ".($pref_auth_exists ? "exists" : "doesn't exists")); if($pref_auth_exists) { // try prefered auth $mech = $pref_auth; } else { // choose one from available mechanisms foreach($mechs as $mech=>$any) { if($mech == 'X-FACEBOOK-PLATFORM') { if(@$this->cfg['fb_access_token']) { break; } } else { break; } } _error("preferred auth type not supported, trying $mech"); } $this->send_auth_pkt($mech, @$this->jid ? $this->jid->to_string() : null, @$this->pass); if($pref_auth == 'X-FACEBOOK-PLATFORM') { return "wait_for_fb_sasl_response"; } else if($pref_auth == 'CRAM-MD5') { return "wait_for_cram_md5_response"; } else if($pref_auth == 'SCRAM-SHA-1') { return "wait_for_scram_sha1_response"; } } public function handle_auth_success() { // if not a component /*if(!@$this->xeps['0114']) { $this->xeps['0030']->get_info($this->full_jid->domain, array(&$this, 'handle_domain_info')); $this->xeps['0030']->get_items($this->full_jid->domain, array(&$this, 'handle_domain_items')); }*/ $this->ev->emit('on_auth_success'); } public function handle_auth_failure($reason) { $this->ev->emit('on_auth_failure', array( $reason )); } public function handle_stream_start($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_stream_start', array($stanza)); return array(@$this->cfg['bosh_url'] ? 'wait_for_stream_features' : 'connected', 1); } public function handle_iq($stanza) { $stanza = new XMPPStanza($stanza); // emit callback registered on stanza id's $emited = false; if($stanza->id && $this->ev->exists('on_stanza_id_'.$stanza->id)) { //_debug("on stanza id callbackd"); $emited = true; $this->ev->emit('on_stanza_id_'.$stanza->id, array($stanza)); } // catch roster list if($stanza->type == 'result' && ($query = $stanza->exists('query', 'jabber:iq:roster'))) { foreach($query->childrens as $child) { if($child->name == 'item') { $jid = $child->attrs['jid']; $subscription = $child->attrs['subscription']; $groups = array(); foreach($child->childrens as $group) { if($group->name == 'group') { - $groups[] = $group->name; + $groups[] = $group->text; } } $this->roster[$jid] = new RosterItem($jid, $subscription, $groups); } } // emit this event if not emited above if(!$emited) $this->ev->emit('on_roster_update'); } // if managing roster // catch contact vcard results if($this->manage_roster && $stanza->type == 'result' && ($query = $stanza->exists('vCard', 'vcard-temp'))) { if(@$this->roster[$stanza->from]) $this->roster[$stanza->from]->vcard = $query; } // on_get_iq, on_result_iq, and other events are only // emitted if on_stanza_id_{id} wasn't emitted above if(!$emited) $this->ev->emit('on_'.$stanza->type.'_iq', array($stanza)); } public function handle_presence($stanza) { $stanza = new XMPPStanza($stanza); // if managing roster // catch available/unavailable type stanza if($this->manage_roster) { $type = ($stanza->type ? $stanza->type : "available"); $jid = new XMPPJid($stanza->from); if($type == 'available') { $this->roster[$jid->bare]->resources[$jid->resource] = $stanza; } else if($type == 'unavailable') { if(@$this->roster[$jid->bare] && @$this->roster[$jid->bare]->resources[$jid->resource]) unset($this->roster[$jid->bare]->resources[$jid->resource]); } } $this->ev->emit('on_presence_stanza', array($stanza)); } public function handle_message($stanza) { $stanza = new XMPPStanza($stanza); $this->ev->emit('on_'.$stanza->type.'_message', array($stanza)); } // unhandled event and arguments bubbled up // TODO: in a lot of cases this will be called, need more checks public function handle_other($event, $args) { $stanza = $args[0]; $stanza = new XMPPStanza($stanza); $ev = 'on_'.$stanza->name.'_stanza'; if($this->ev->exists($ev)) { return $this->ev->emit($ev, array($stanza)); } else { _warning("event '".$event."' catched in handle_other with stanza name ".$stanza->name); } } public function handle_domain_info($stanza) { $query = $stanza->exists('query', NS_DISCO_INFO); foreach($query->childrens as $k=>$child) { if($child->name == 'identity') { //echo 'identity category:'.@$child->attrs['category'].', type:'.@$child->attrs['type'].', name:'.@$child->attrs['name'].PHP_EOL; } else if($child->name == 'x') { //echo 'x ns:'.$child->ns.PHP_EOL; } else if($child->name == 'feature') { //echo 'feature var:'.$child->attrs['var'].PHP_EOL; } } } public function handle_domain_items($stanza) { $query = $stanza->exists('query', NS_DISCO_ITEMS); foreach($query->childrens as $k=>$child) { if($child->name == 'item') { //echo 'item jid:'.@$child->attrs['jid'].', name:'.@$child->attrs['name'].', node:'.@$child->attrs['node'].PHP_EOL; } } } } ?>
jaxl/JAXL
986d48622a239b656769f2d693f3f207597b503f
first checkin of XMPP Ping XEP-0199, enabled by default inside echobot.php
diff --git a/examples/echo_bot.php b/examples/echo_bot.php index 3a7e94f..df7045d 100644 --- a/examples/echo_bot.php +++ b/examples/echo_bot.php @@ -1,138 +1,145 @@ <?php /** * Jaxl (Jabber XMPP Library) * * Copyright (c) 2009-2012, Abhinav Singh <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Abhinav Singh nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ if($argc < 3) { echo "Usage: $argv[0] jid pass\n"; exit; } // // initialize JAXL object with initial config // require_once 'jaxl.php'; $client = new JAXL(array( // (required) credentials 'jid' => $argv[1], 'pass' => $argv[2], // (optional) srv lookup is done if not provided //'host' => 'xmpp.domain.tld', // (optional) result from srv lookup used by default //'port' => 5222, // (optional) defaults to false //'force_tls' => true, // (optional) //'resource' => 'resource', // (optional) defaults to PLAIN if supported, else other methods will be automatically tried 'auth_type' => @$argv[3] ? $argv[3] : 'PLAIN', 'log_level' => JAXL_INFO )); +// +// required XEP's +// +$client->require_xep(array( + '0199' // XMPP Ping +)); + // // add necessary event callbacks here // $client->add_cb('on_auth_success', function() { global $client; _info("got on_auth_success cb, jid ".$client->full_jid->to_string()); // set status $client->set_status("available!", "dnd", 10); // fetch vcard $client->get_vcard(); // fetch roster list $client->get_roster(); }); // by default JAXL instance catches incoming roster list results and updates // roster list is parsed/cached and an event 'on_roster_update' is emitted $client->add_cb('on_roster_update', function() { //global $client; //print_r($client->roster); }); $client->add_cb('on_auth_failure', function($reason) { global $client; $client->send_end_stream(); _info("got on_auth_failure cb with reason $reason"); }); $client->add_cb('on_chat_message', function($stanza) { global $client; // echo back incoming chat message stanza $stanza->to = $stanza->from; $stanza->from = $client->full_jid->to_string(); $client->send($stanza); }); $client->add_cb('on_presence_stanza', function($stanza) { global $client; $type = ($stanza->type ? $stanza->type : "available"); $show = ($stanza->show ? $stanza->show : "???"); _info($stanza->from." is now ".$type." ($show)"); if($type == "available") { // fetch vcard $client->get_vcard($stanza->from); } }); $client->add_cb('on_disconnect', function() { _info("got on_disconnect cb"); }); // // finally start configured xmpp stream // $client->start(array( '--with-debug-shell' => true, '--with-unix-sock' => true )); echo "done\n"; ?> diff --git a/xep/xep_0199.php b/xep/xep_0199.php new file mode 100644 index 0000000..9896d60 --- /dev/null +++ b/xep/xep_0199.php @@ -0,0 +1,50 @@ +<?php + +require_once JAXL_CWD.'/xmpp/xmpp_xep.php'; + +define('NS_XMPP_PING', 'urn:xmpp:ping'); + +class XEP_0199 extends XMPPXep { + + // + // abstract method + // + + public function init() { + return array( + 'on_auth_success' => 'on_auth_success' + ); + } + + // + // api methods + // + + public function get_ping_pkt() { + $attrs = array( + 'type'=>'get', + 'from'=>$this->jaxl->full_jid->to_string(), + 'to'=>$this->jaxl->full_jid->domain + ); + + return $this->jaxl->get_iq_pkt( + $attrs, + new JAXLXml('ping', NS_XMPP_PING) + ); + } + + public function ping() { + $this->jaxl->send($this->get_ping_pkt()); + } + + // + // event callbacks + // + + public function on_auth_success() { + JAXLLoop::$clock->call_fun_periodic(30 * pow(10,6), array(&$this, 'ping')); + } + +} + +?>