repo
stringlengths 5
75
| commit
stringlengths 40
40
| message
stringlengths 6
18.2k
| diff
stringlengths 60
262k
|
---|---|---|---|
jaxl/JAXL | 8c67ef2ed964a32e02c8ca32fc9134016fe8c4e2 | args is optional while registering cron tabs | diff --git a/core/jaxl_clock.php b/core/jaxl_clock.php
index 2e90a01..adc6e80 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)");
+ //_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) {
+ public function tc($callback, $args=null) {
}
// callback after $time seconds
- public function call_fun_after($time, $callback, $args) {
+ 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
- public function call_fun_periodic($time, $callback, $args) {
+ 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]);
}
}
?>
|
jaxl/JAXL | 4cdee04452c5b1d3e54cccb01d19b458262534ad | added v3.x release notice on top of readme | diff --git a/README.md b/README.md
index 7e4f89c..9c6ffef 100644
--- a/README.md
+++ b/README.md
@@ -1,67 +1,69 @@
# JAXL (Jabber XMPP Client and Component Library in PHP)
+[Jaxl v3.x](https://github.com/abhinavsingh/JAXL/tree/v3.x) is out. It's fast, modular, clean, flexible, oops, event based. [Read More](https://github.com/abhinavsingh/JAXL/tree/v3.x)
+
Jaxl 2.x is an object oriented XMPP framework in PHP for developing real time applications
for browsers, desktops and hand held devices. Jaxl 2.x is a robust, flexible and easy to use
version of Jaxl 1.x series which was hosted at google code.
* More robust, flexible, scalable and easy to use with event mechanism for registering callbacks for xmpp events
* Integrated support for Real Time Web (XMPP over Bosh) application development
* Support for DIGEST-MD5, PLAIN, ANONYMOUS, X-FACEBOOK-PLATFORM authentication mechanisms
* 51 implemented XMPP extensions [(XEP's)](http://xmpp.org/extensions/) including MUC, PubSub, PEP, Jingle, File Transfer
* Setup dynamic number of parallel XMPP instance on the fly
* Monitoring, usage stat collection, rate limiting and production ready goodies
## Download
* For better experience download [latest stable tarball](http://code.google.com/p/jaxl/downloads/list) from *google code*
* The development version of Jaxl is hosted here at *Github*, have fun cloning the source code with Git
Warning: The development source code at Github is only intended for people that want to develop Jaxl or absolutely need the latest features still not available on the stable releases.
## Writing XMPP apps using JAXL library
* Download and extract inside `/path/to/jaxl`
* Jaxl library provide an event based mechanism exposing hooks like `jaxl_post_auth`
* Register callback(s) inside your app code for required events (see example below)
* Write your app logic inside callback'd methods
Here is how a simple send chat message app looks like using Jaxl library:
// Include and initialize Jaxl core
require_once '/path/to/jaxl/core/jaxl.class.php';
$jaxl = new JAXL(array(
'user'=>'username',
'pass'=>'password',
'host'=>'talk.google.com',
'domain'=>'gmail.com',
'authType'=>'PLAIN',
'logLevel'=>5
));
// Send message after successful authentication
function postAuth($payload, $jaxl) {
global $argv;
$jaxl->sendMessage($argv[1], $argv[2]);
$jaxl->shutdown();
}
// Register callback on required hook (callback'd method will always receive 2 params)
$jaxl->addPlugin('jaxl_post_auth', 'postAuth');
// Start Jaxl core
$jaxl->startCore('stream');
Run from command line:
php sendMessage.php "[email protected]" "This is a test message"
## Useful Links
* [PHP Documentation](http://jaxl.net/)
* [Developer Mailing List](http://groups.google.com/group/jaxl/)
* [Issue Tracker](http://code.google.com/p/jaxl/issues/list?can=1&q=&colspec=ID+Type+Status+Priority+Milestone+Owner+Summary&cells=tiles)
Generate Jaxl documentation on your system for quick reference:
phpdoc -o HTML:Smarty:PHP -ti "JAXL Documentation" -t /var/www/ -d xmpp/,xep/,env/,core/
|
jaxl/JAXL | 44e693b8fb4d2fab5a49514fe41cad2c6062a780 | Checkin for XEP 0166 (Jingle), 0167 (Jingle RTP Session), 0176 (Jingle ICE-UDP), 0234 (Jingle File), 0261 (Jingle In-band bytestream) | diff --git a/xep/jaxl.0166.php b/xep/jaxl.0166.php
new file mode 100644
index 0000000..b1ed516
--- /dev/null
+++ b/xep/jaxl.0166.php
@@ -0,0 +1,118 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-0166 : Jingle
+ */
+ class JAXL0166 {
+
+ public static $ns = 'urn:xmpp:jingle:1';
+
+ public static function init($jaxl) {
+ $jaxl->features[] = self::$ns;
+
+ JAXLXml::addTag('iq', 'j', '//iq/jingle/@xmlns');
+ JAXLXml::addTag('iq', 'jAction', '//iq/jingle/@action');
+ JAXLXml::addTag('iq', 'jSid', '//iq/jingle/@sid');
+ JAXLXml::addTag('iq', 'jInitiator', '//iq/jingle/@initiator');
+ JAXLXml::addTag('iq', 'jResponder', '//iq/jingle/@responder');
+ JAXLXml::addTag('iq', 'jcCreator', '//iq/jingle/content/@creator');
+ JAXLXml::addTag('iq', 'jcName', '//iq/jingle/content/@name');
+ JAXLXml::addTag('iq', 'jcDisposition', '//iq/jingle/content/@disposition');
+ JAXLXml::addTag('iq', 'jcSenders', '//iq/jingle/content/@senders');
+ JAXLXml::addTag('iq', 'jrCondition', '//iq/jingle/reason/*[1]/name()');
+ JAXLXml::addTag('iq', 'jrText', '//iq/jingle/reason/text');
+ }
+
+ public static function getReasonElement($condition, $text=false, $payload=false) {
+ $xml = '<reason>';
+ $xml .= '<'.$condition.'/>';
+ if($text) $xml .= '<text>'.$text.'</text>';
+ if($payload) $xml .= $payload;
+ $xml .= '</reason>';
+ return $xml;
+ }
+
+ public static function getContentElement($payload, $creator, $name, $disposition=false, $senders=false) {
+ $xml = '<content creator="" name=""';
+ if($disposition) $xml .= ' disposition=""';
+ if($senders) $xml .= ' senders=""';
+ $xml .= '>';
+ $xml .= $payload;
+ $xml .= '</content>';
+ return $xml;
+ }
+
+ public static function getJingleElement($payload, $action, $sid, $initiator=false, $responder=false) {
+ $xml = '<jingle xmlns="'.self::$ns.'" action="'.$action.'" sid="'.$sid.'"';
+ if($initiator) $xml .= ' initiator="'.$initiator.'"';
+ if($responder) $xml .= ' responder="'.$responder.'"';
+ $xml .= '>';
+ $xml .= $payload;
+ $xml .= '</jingle>';
+ return $xml;
+ }
+
+ public static function sessionInitiate($jaxl, $to, $payload, $sid, $initiator, $callback) {
+ $xml = self::getJingleElement($payload, 'session-initiate', $sid, $initiator);
+ return XMPPSend::iq($jaxl, 'set', $xml, $to, false, $callback);
+ }
+
+ public static function sessionAccept($jaxl, $to, $payload, $sid, $initiator, $responder, $callback) {
+ $xml = self::getJingleElement($payload, 'session-accept', $sid, $initiator, $responder);
+ return XMPPSend::iq($jaxl, 'set', $xml, $to, false, $callback);
+ }
+
+ public static function sessionTerminate($jaxl, $to, $payload, $sid, $initiator, $callback) {
+ $xml = self::getJingleElement($payload, 'session-terminate', $sid, $initiator);
+ return XMPPSend::iq($jaxl, 'set', $xml, $to, false, $callback);
+ }
+
+ public static function sendInfoMessage($jaxl, $to, $payload, $sid, $initiator, $callback) {
+ $xml = self::getJingleElement($payload, 'session-info', $sid, $initiator);
+ return XMPPSend::iq($jaxl, 'set', $xml, $to, false, $callback);
+ }
+
+ }
+
+?>
diff --git a/xep/jaxl.0167.php b/xep/jaxl.0167.php
new file mode 100644
index 0000000..6833d6a
--- /dev/null
+++ b/xep/jaxl.0167.php
@@ -0,0 +1,112 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-0167 : Jingle RTP Sessions
+ */
+ class JAXL0167 {
+
+ public static $ns = 'urn:xmpp:jingle:apps:rtp:1';
+
+ public static function init($jaxl) {
+ $jaxl->features[] = self::$ns;
+
+ JAXLXml::addTag('iq', 'jtpDescription', '//iq/jingle/content/description/@xmlns');
+ JAXLXml::addTag('iq', 'jtpMedia', '//iq/jingle/content/description/@media');
+ JAXLXml::addTag('iq', 'jtpSSRC', '//iq/jingle/content/description/@ssrc');
+
+ JAXLXml::addTag('iq', 'jtpPTypeId', '//iq/jingle/content/description/payload-type/@id');
+ JAXLXml::addTag('iq', 'jtpPTypeName', '//iq/jingle/content/description/payload-type/@name');
+ JAXLXml::addTag('iq', 'jtpPTypeClockRate', '//iq/jingle/content/description/payload-type/@clockrate');
+ JAXLXml::addTag('iq', 'jtpPTypeChannels', '//iq/jingle/content/description/payload-type/@channels');
+ JAXLXml::addTag('iq', 'jtpPTypeMAXPTime', '//iq/jingle/content/description/payload-type/@maxptime');
+ JAXLXml::addTag('iq', 'jtpPTypePTime', '//iq/jingle/content/description/payload-type/@ptime');
+
+ JAXLXml::addTag('iq', 'jtpEncryptReq', '//iq/jingle/content/description/encryption/@required');
+ JAXLXml::addTag('iq', 'jtpCryptoSuite', '//iq/jingle/content/description/encryption/crypto/@crypto-suite');
+ JAXLXml::addTag('iq', 'jtpCryptoKey', '//iq/jingle/content/description/encryption/crypto/@key-params');
+ JAXLXml::addTag('iq', 'jtpCryptoSession', '//iq/jingle/content/description/encryption/crypto/@session-params');
+ JAXLXml::addTag('iq', 'jtpCryptoTag', '//iq/jingle/content/description/encryption/crypto/@tag');
+
+ JAXLXml::addTag('iq', 'jtpBWType', '//iq/jingle/content/description/bandwidth/@type');
+ JAXLXml::addTag('iq', 'jtpBW', '//iq/jingle/content/description/bandwidth');
+
+ JAXLXml::addTag('iq', 'jtpPTypeParamName', '//iq/jingle/content/description/payload-type/parameter/@name');
+ JAXLXml::addTag('iq', 'jtpPTypeParamValue', '//iq/jingle/content/description/payload-type/parameter/@value');
+ }
+
+ public static function getDescriptionElement() {
+ $xml = '<description xmlns="" media="" ssrc="">';
+ $xml .= '<payload-type id="" name="" clockrate="" channels="" maxptime="" ptime="">';
+ $xml .= '<parameter name="" value=""/>';
+ $xml .= '</payload>';
+ $xml .= '<bandwidth type=""></bandwidth>';
+ $xml .= '<description>';
+ return $xml;
+ }
+
+ public static function active() {
+
+ }
+
+ public static function hold() {
+
+ }
+
+ public static function mute() {
+
+ }
+
+ public static function ringing() {
+
+ }
+
+ public static function sendAppParam() {
+ $xml = self::getDescriptionElement();
+ $xml = JAXL0166::getContentElement($xml, $creator, $name);
+ $xml = JAXL0166::getJingleElement($xml, 'description-info', $sid, $initiator);
+ }
+
+ }
+
+?>
diff --git a/xep/jaxl.0176.php b/xep/jaxl.0176.php
new file mode 100644
index 0000000..40079a6
--- /dev/null
+++ b/xep/jaxl.0176.php
@@ -0,0 +1,82 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-0176: Jingle ICE-UDP Transport Method
+ */
+ class JAXL0176 {
+
+ public static $ns = 'urn:xmpp:jingle:transports:ice-udp:1';
+
+ public static function init($jaxl) {
+ $jaxl->features[] = self::$ns;
+
+ JAXLXml::addTag('iq', 'jtpTrans', '//iq/jingle/content/transport/@xmlns');
+ JAXLXml::addTag('iq', 'jtpTransPWD', '//iq/jingle/content/transport/@pwd');
+ JAXLXml::addTag('iq', 'jtpTransUFrag', '//iq/jingle/content/transport/@ufrag');
+
+ JAXLXml::addTag('iq', 'jtpCandiComp', '//iq/jingle/content/transport/candidate/@component');
+ JAXLXml::addTag('iq', 'jtpCandiComp', '//iq/jingle/content/transport/candidate/@foundation');
+ JAXLXml::addTag('iq', 'jtpCandiComp', '//iq/jingle/content/transport/candidate/@generation');
+ JAXLXml::addTag('iq', 'jtpCandiComp', '//iq/jingle/content/transport/candidate/@id');
+ JAXLXml::addTag('iq', 'jtpCandiComp', '//iq/jingle/content/transport/candidate/@ip');
+ JAXLXml::addTag('iq', 'jtpCandiComp', '//iq/jingle/content/transport/candidate/@network');
+ JAXLXml::addTag('iq', 'jtpCandiComp', '//iq/jingle/content/transport/candidate/@port');
+ JAXLXml::addTag('iq', 'jtpCandiComp', '//iq/jingle/content/transport/candidate/@priority');
+ JAXLXml::addTag('iq', 'jtpCandiComp', '//iq/jingle/content/transport/candidate/@protocol');
+ JAXLXml::addTag('iq', 'jtpCandiComp', '//iq/jingle/content/transport/candidate/@rel-addr');
+ JAXLXml::addTag('iq', 'jtpCandiComp', '//iq/jingle/content/transport/candidate/@rel-port');
+ JAXLXml::addTag('iq', 'jtpCandiComp', '//iq/jingle/content/transport/candidate/@type');
+ }
+
+ public static function getTransportElement() {
+
+ }
+
+ public static function getCandidateElement() {
+
+ }
+
+ }
+
+?>
diff --git a/xep/jaxl.0234.php b/xep/jaxl.0234.php
new file mode 100644
index 0000000..292906d
--- /dev/null
+++ b/xep/jaxl.0234.php
@@ -0,0 +1,53 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-0234 : Jingle File Transfer
+ */
+ class JAXL0234 {
+
+ public static $ns = 'urn:xmpp:jingle:apps:file-transfer:1';
+
+ }
+
+?>
diff --git a/xep/jaxl.0261.php b/xep/jaxl.0261.php
new file mode 100644
index 0000000..a3f595c
--- /dev/null
+++ b/xep/jaxl.0261.php
@@ -0,0 +1,53 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-0261 : Jingle In-Band Bytestreams Transport Method
+ */
+ class JAXL0261 {
+
+ public static $ns = 'urn:xmpp:jingle:transports:ibb:1';
+
+ }
+
+?>
|
jaxl/JAXL | 3e0dfe3b16f83a96691fa611f3deecec5675de33 | Checkin for XEP-0096: Stream Initiated File Transfer Profile | diff --git a/xep/jaxl.0096.php b/xep/jaxl.0096.php
new file mode 100644
index 0000000..d3526f3
--- /dev/null
+++ b/xep/jaxl.0096.php
@@ -0,0 +1,142 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-0096: Stream Initiated File Transfer Profile
+ */
+ class JAXL0096 {
+
+ // map of id used to initiate negotiation and related data
+ public static $id = array();
+
+ public static $ns = 'http://jabber.org/protocol/si/profile/file-transfer';
+
+ public static function init($jaxl) {
+ $jaxl->requires(array(
+ 'JAXL0095', // Require Stream Initiation XEP
+ 'JAXL0047', // Require IBB
+ 'JAXL0065' // SOCKS5 Bytestream
+ ));
+ $jaxl->features[] = self::$ns;
+
+ JAXLXml::addTag('iq', 'file', '//iq/si/file/@xmlns');
+ JAXLXml::addTag('iq', 'fileSize', '//iq/si/file/@size');
+ JAXLXml::addTag('iq', 'fileName', '//iq/si/file/@name');
+ JAXLXml::addTag('iq', 'fileDate', '//iq/si/file/@date');
+ JAXLXml::addTag('iq', 'fileHash', '//iq/si/file/@hash');
+ JAXLXml::addTag('iq', 'fileDesc', '//iq/si/file/desc');
+ JAXLXml::addTag('iq', 'fileStreamMethod', '//iq/si/feature/x/field/value');
+ JAXLXml::addTag('iq', 'fileStreamMethods', '//iq/si/feature/x/field/option/value');
+
+ $jaxl->addPlugin('jaxl_get_iq_set', array('JAXL0096', 'getFile'));
+ }
+
+ public static function accept($jaxl, $to, $id, $method) {
+ $xml = '<file xmlns="'.self::$ns.'"/>';
+ $xml .= '<feature xmlns="http://jabber.org/protocol/feature-neg">';
+ $xml .= '<x xmlns="jabber:x:data" type="submit">';
+ $xml .= '<field var="stream-method">';
+ $xml .= '<value>'.$method.'</value>';
+ $xml .= '</field>';
+ $xml .= '</x>';
+ $xml .= '</feature>';
+ return JAXL0095::accept($jaxl, $to, $id, $xml);
+ }
+
+ public static function getFile($payload, $jaxl) {
+ if($payload['file'] == self::$ns) $jaxl->executePlugin('jaxl_get_file_request', $payload);
+ return $payload;
+ }
+
+ public static function sendFile($jaxl, $to, $file, $desc=false, $length=false, $offset=false, $siId=false, $siMime=false) {
+ if(!file_exists($file)) {
+ $jaxl->log("[[JAXL0096]] $file doesn't exists on the system");
+ return false;
+ }
+
+ $xml = '<file xmlns="'.self::$ns.'" name="'.basename($file).'" size="'.filesize($file).'">';
+ if($desc) $xml .= '<desc>'.$desc.'</desc>';
+ $xml .= '<range';
+ if($offset) $xml .= ' offset="'.$offset.'"';
+ if($length) $xml .= ' length="'.$length.'"';
+ $xml .= '/>';
+ $xml .= '</file>';
+ $xml .= '<feature xmlns="http://jabber.org/protocol/feature-neg">';
+ $xml .= '<x xmlns="jabber:x:data" type="form">';
+ $xml .= '<field var="stream-method" type="list-single">';
+ $xml .= '<option><value>http://jabber.org/protocol/bytestreams</value></option>';
+ $xml .= '<option><value>http://jabber.org/protocol/ibb</value></option>';
+ $xml .= '</field>';
+ $xml .= '</x>';
+ $xml .= '</feature>';
+
+ if(!$siId) $siId = md5($jaxl->clocked.$jaxl->jid.$to);
+ if(!$siMime) $siMime = 'application/octet-stream';
+
+ $id = JAXL0095::initiate($jaxl, $to, $xml, $siId, $siMime, self::$ns, array('JAXL0096', 'handleIQResult'));
+
+ self::$id[$id] = array(
+ 'file'=>$file,
+ 'length'=>$length,
+ 'offset'=>$offset,
+ 'siId'=>$siId,
+ 'to'=>$to
+ );
+ return $id;
+ }
+
+ public static function handleIQResult($payload, $jaxl) {
+ if(!isset(self::$id[$payload['id']]))
+ return $payload;
+
+ if($payload['fileStreamMethod'] == 'http://jabber.org/protocol/ibb')
+ $jaxl->JAXL0047('sendFile', self::$id[$payload['id']]);
+ else if($payload['fileStreamMethod'] == 'http://jabber.org/protocol/bytestreams')
+ $jaxl->JAXL0065('sendFile', self::$id[$payload['id']]);
+
+ unset(self::$id[$payload['id']]);
+ }
+
+ }
+
+?>
|
jaxl/JAXL | d580a103f8c621746068ba0d18370da84869ff4d | Checkin for XEP 0071 (XHTML-IM), 0095 (Stream Initiation) | diff --git a/xep/jaxl.0071.php b/xep/jaxl.0071.php
new file mode 100644
index 0000000..efb02bc
--- /dev/null
+++ b/xep/jaxl.0071.php
@@ -0,0 +1,60 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-0071 : XHTML-IM
+ */
+ class JAXL0071 {
+
+ public static $ns = 'http://jabber.org/protocol/xhtml-im';
+
+ public static function init($global) {
+ $jaxl->features[] = self::$ns;
+
+ JAXLXml::addTag('message', 'html', '//message/html/@xmlns');
+ JAXLXml::addTag('message', 'htmlBody', '//message/html/body');
+ }
+
+ }
+
+?>
diff --git a/xep/jaxl.0095.php b/xep/jaxl.0095.php
new file mode 100644
index 0000000..8927922
--- /dev/null
+++ b/xep/jaxl.0095.php
@@ -0,0 +1,74 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-0095: Stream Initiation
+ */
+ class JAXL0095 {
+
+ public static $ns = 'http://jabber.org/protocol/si';
+
+ public static function init($jaxl) {
+ $jaxl->features[] = self::$ns;
+
+ JAXLXml::addTag('iq', 'si', '//iq/si/@xmlns');
+ JAXLXml::addTag('iq', 'siId', '//iq/si/@id');
+ JAXLXml::addTag('iq', 'siMime', '//iq/si/@mime-type');
+ JAXLXml::addTag('iq', 'siProfile', '//iq/si/@profile');
+ }
+
+ public static function initiate($jaxl, $to, $payload, $siId, $siMime, $siProfile, $callback) {
+ $xml = '<si xmlns="'.self::$ns.'" id="'.$siId.'" mime-type="'.$siMime.'" profile="'.$siProfile.'">';
+ $xml .= $payload;
+ $xml .= '</si>';
+ return XMPPSend::iq($jaxl, 'set', $xml, $to, false, $callback);
+ }
+
+ public static function accept($jaxl, $to, $id, $payload) {
+ $payload = '<si xmlns="'.self::$ns.'">'.$payload.'</si>';
+ return XMPPSend::iq($jaxl, 'result', $payload, $to, false, false, $id);
+ }
+
+ }
+
+?>
|
jaxl/JAXL | a9b17bb287ce7e2110966339b9ad6c0622c6e6e8 | Checkin for RFC-1928 (SOCK5) implementation | diff --git a/core/jaxl.class.php b/core/jaxl.class.php
index 7220e87..5d7e1c3 100644
--- a/core/jaxl.class.php
+++ b/core/jaxl.class.php
@@ -1,579 +1,580 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
declare(ticks=1);
// Set JAXL_BASE_PATH if not already defined by application code
if(!@constant('JAXL_BASE_PATH'))
define('JAXL_BASE_PATH', dirname(dirname(__FILE__)));
/**
* Autoload method for Jaxl library and it's applications
*
* @param string|array $classNames core class name required in PHP environment
* @param object $jaxl Jaxl object which require these classes. Optional but always required while including implemented XEP's in PHP environment
*/
function jaxl_require($classNames, $jaxl=false) {
static $included = array();
$tagMap = array(
// core classes
'JAXLCron' => '/core/jaxl.cron.php',
'JAXLHTTPd' => '/core/jaxl.httpd.php',
'JAXLog' => '/core/jaxl.logger.php',
'JAXLXml' => '/core/jaxl.parser.php',
'JAXLPlugin' => '/core/jaxl.plugin.php',
'JAXLUtil' => '/core/jaxl.util.php',
'JAXLException' => '/core/jaxl.exception.php',
- 'XML' => '/core/jaxl.xml.php',
+ 'XML' => '/core/jaxl.xml.php',
+ 'S5B' => '/core/jaxl.s5b.php',
// xmpp classes
'XMPP' => '/xmpp/xmpp.class.php',
'XMPPGet' => '/xmpp/xmpp.get.php',
'XMPPSend' => '/xmpp/xmpp.send.php',
'XMPPAuth' => '/xmpp/xmpp.auth.php'
);
if(!is_array($classNames)) $classNames = array('0'=>$classNames);
foreach($classNames as $key => $className) {
$xep = substr($className, 4, 4);
if(substr($className, 0, 4) == 'JAXL'
&& is_numeric($xep)
) { // is XEP
if(!isset($included[$className])) {
require_once JAXL_BASE_PATH.'/xep/jaxl.'.$xep.'.php';
$included[$className] = true;
}
call_user_func(array('JAXL'.$xep, 'init'), $jaxl);
} // is Core file
else if(isset($tagMap[$className])) {
require_once JAXL_BASE_PATH.$tagMap[$className];
$included[$className] = true;
}
}
return;
}
// cnt of connected instances
global $jaxl_instance_cnt;
$jaxl_instance_cnt = 0;
// Include core classes and xmpp base
jaxl_require(array(
'JAXLog',
'JAXLUtil',
'JAXLPlugin',
'JAXLCron',
'JAXLException',
'XML',
'XMPP',
));
/**
* Jaxl class extending base XMPP class
*
* Jaxl library core is like any of your desktop Instant Messaging (IM) clients.
* Include Jaxl core in you application and start connecting and managing multiple XMPP accounts
* Packaged library is custom configured for running <b>single instance</b> Jaxl applications
*
* For connecting <b>multiple instance</b> XMPP accounts inside your application see documentation for
* <b>addCore()</b> method
*/
class JAXL extends XMPP {
/**
* Client version of the connected Jaxl instance
*/
const version = '2.1.2';
/**
* Client name of the connected Jaxl instance
*/
const name = 'Jaxl :: Jabber XMPP Client Library';
/**
* Custom config passed to Jaxl constructor
*
* @var array
*/
var $config = array();
/**
* Username of connecting Jaxl instance
*
* @var string
*/
var $user = false;
/**
* Password of connecting Jaxl instance
*
* @var string
*/
var $pass = false;
/**
* Hostname for the connecting Jaxl instance
*
* @var string
*/
var $host = 'localhost';
/**
* Port for the connecting Jaxl instance
*
* @var integer
*/
var $port = 5222;
/**
* Full JID of the connected Jaxl instance
*
* @var string
*/
var $jid = false;
/**
* Bare JID of the connected Jaxl instance
*
* @var string
*/
var $bareJid = false;
/**
* Domain for the connecting Jaxl instance
*
* @var string
*/
var $domain = 'localhost';
/**
* Resource for the connecting Jaxl instance
*
* @var string
*/
var $resource = false;
/**
* Local cache of roster list and related info maintained by Jaxl instance
*/
var $roster = array();
/**
* Default status of connected Jaxl instance
*/
var $status = 'Online using Jaxl library http://code.google.com/p/jaxl';
/**
* Jaxl will track presence stanza's and update local $roster cache
*/
var $trackPresence = true;
/**
* Configure Jaxl instance to auto-accept subscription requests
*/
var $autoSubscribe = false;
/**
* Log Level of the connected Jaxl instance
*
* @var integer
*/
var $logLevel = 1;
/**
* Enable/Disable automatic log rotation for this Jaxl instance
*
* @var bool|integer
*/
var $logRotate = false;
/**
* Absolute path of log file for this Jaxl instance
*/
var $logPath = '/var/log/jaxl.log';
/**
* Absolute path of pid file for this Jaxl instance
*/
var $pidPath = '/var/run/jaxl.pid';
/**
* Enable/Disable shutdown callback on SIGH terms
*
* @var bool
*/
var $sigh = true;
/**
* Process Id of the connected Jaxl instance
*
* @var bool|integer
*/
var $pid = false;
/**
* Mode of the connected Jaxl instance (cgi or cli)
*
* @var bool|string
*/
var $mode = false;
/**
* Jabber auth mechanism performed by this Jaxl instance
*
* @var false|string
*/
var $authType = false;
/**
* Jaxl instance dumps usage statistics periodically. Disabled if set to "false"
*
* @var bool|integer
*/
var $dumpStat = 300;
/**
* List of XMPP feature supported by this Jaxl instance
*
* @var array
*/
var $features = array();
/**
* XMPP entity category for the connected Jaxl instance
*
* @var string
*/
var $category = 'client';
/**
* XMPP entity type for the connected Jaxl instance
*
* @var string
*/
var $type = 'bot';
/**
* Default language of the connected Jaxl instance
*/
var $lang = 'en';
/**
* Location to system temporary folder
*/
var $tmpPath = null;
/**
* IP address of the host Jaxl instance is running upon.
* To be used by STUN client implementations.
*/
var $ip = null;
/**
* PHP OpenSSL module info
*/
var $openSSL = false;
var $instances = false;
/**
* @return string $name Returns name of this Jaxl client
*/
function getName() {
return JAXL::name;
}
/**
* @return float $version Returns version of this Jaxl client
*/
function getVersion() {
return JAXL::version;
}
/**
* Discover items
*/
function discoItems($jid, $callback, $node=false) {
$this->JAXL0030('discoItems', $jid, $this->jid, $callback, $node);
}
/**
* Discover info
*/
function discoInfo($jid, $callback, $node=false) {
$this->JAXL0030('discoInfo', $jid, $this->jid, $callback, $node);
}
/**
* Shutdown Jaxl instance cleanly
*
* shutdown method is auto invoked when Jaxl instance receives a SIGH term.
* Before cleanly shutting down this method callbacks registered using <b>jaxl_pre_shutdown</b> hook.
*
* @param mixed $signal This is passed as paramater to callbacks registered using <b>jaxl_pre_shutdown</b> hook
*/
function shutdown($signal=false) {
$this->log("[[JAXL]] Shutting down ...");
$this->executePlugin('jaxl_pre_shutdown', $signal);
if($this->stream) $this->endStream();
$this->stream = false;
}
/**
* Perform authentication for connecting Jaxl instance
*
* @param string $type Authentication mechanism to proceed with. Supported auth types are:
* - DIGEST-MD5
* - PLAIN
* - X-FACEBOOK-PLATFORM
* - ANONYMOUS
*/
function auth($type) {
$this->authType = $type;
return XMPPSend::startAuth($this);
}
/**
* Set status of the connected Jaxl instance
*
* @param bool|string $status
* @param bool|string $show
* @param bool|integer $priority
* @param bool $caps
*/
function setStatus($status=false, $show=false, $priority=false, $caps=false, $vcard=false) {
$child = array();
$child['status'] = ($status === false ? $this->status : $status);
$child['show'] = ($show === false ? 'chat' : $show);
$child['priority'] = ($priority === false ? 1 : $priority);
if($caps) $child['payload'] = $this->JAXL0115('getCaps', $this->features);
if($vcard) $child['payload'] .= $this->JAXL0153('getUpdateData', false);
return XMPPSend::presence($this, false, false, $child, false);
}
/**
* Send authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send authorization request
*/
function subscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribe');
}
/**
* Accept authorization request from $toJid
*
* @param string $toJid JID who's authorization request Jaxl instance wants to accept
*/
function subscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribed');
}
/**
* Send cancel authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send cancel authorization request
*/
function unsubscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribe');
}
/**
* Accept cancel authorization request from $toJid
*
* @param string $toJid JID who's cancel authorization request Jaxl instance wants to accept
*/
function unsubscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribed');
}
/**
* Retrieve connected Jaxl instance roster list from the server
*
* @param mixed $callback Method to be callback'd when roster list is received from the server
*/
function getRosterList($callback=false) {
$payload = '<query xmlns="jabber:iq:roster"/>';
if($callback === false) $callback = array($this, '_handleRosterList');
return XMPPSend::iq($this, "get", $payload, false, $this->jid, $callback);
}
/**
* Add a new jabber account in connected Jaxl instance roster list
*
* @param string $jid JID to be added in the roster list
* @param string $group Group name
* @param bool|string $name Name of JID to be added
*/
function addRoster($jid, $group, $name=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Update subscription of a jabber account in roster list
*
* @param string $jid JID to be updated inside roster list
* @param string $group Updated group name
* @param bool|string $subscription Updated subscription type
*/
function updateRoster($jid, $group, $name=false, $subscription=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
if($subscription) $payload .= ' subscription="'.$subscription.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Delete a jabber account from roster list
*
* @param string $jid JID to be removed from the roster list
*/
function deleteRoster($jid) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'" subscription="remove">';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Send an XMPP message
*
* @param string $to JID to whom message is sent
* @param string $message Message to be sent
* @param string $from (Optional) JID from whom this message should be sent
* @param string $type (Optional) Type of message stanza to be delivered
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessage($to, $message, $from=false, $type='chat', $id=false) {
$child = array();
$child['body'] = $message;
return XMPPSend::message($this, $to, $from, $child, $type, $id);
}
/**
* Send multiple XMPP messages in one go
*
* @param array $to array of JID's to whom this presence stanza should be send
* @param array $from (Optional) array of JID from whom this presence stanza should originate
* @param array $child (Optional) array of arrays specifying child objects of the stanza
* @param array $type (Optional) array of type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessages($to, $from=false, $child=false, $type='chat', $id=false) {
return XMPPSend::message($this, $to, $from, $child, $type);
}
/**
* Send an XMPP presence stanza
*
* @param string $to (Optional) JID to whom this presence stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param array $child (Optional) array specifying child objects of the stanza
* @param string $type (Optional) Type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendPresence($to=false, $from=false, $child=false, $type=false, $id=false) {
return XMPPSend::presence($this, $to, $from, $child, $type, $id);
}
/**
* Send an XMPP iq stanza
*
* @param string $type Type of iq stanza to send
* @param string $payload (Optional) XML string to be transmitted
* @param string $to (Optional) JID to whom this iq stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param string|array $callback (Optional) Callback method which will handle "result" type stanza rcved
* @param integer $id (Optional) Add an id attribute to transmitted stanza (auto-generated if not provided)
*/
function sendIQ($type, $payload=false, $to=false, $from=false, $callback=false, $id=false) {
return XMPPSend::iq($this, $type, $payload, $to, $from, $callback, $id);
}
/**
* Logs library core and application debug data into the log file
*
* @param string $log Datum to be logged
* @param integer $level Log level for passed datum
*/
function log($log, $level=1) {
JAXLog::log($log, $level, $this);
}
/**
* Instead of using jaxl_require method applications can use $jaxl->requires to include XEP's in PHP environment
*
* @param string $class Class name of the XEP to be included e.g. JAXL0045 for including XEP-0045 a.k.a. Multi-user chat
*/
function requires($class) {
jaxl_require($class, $this);
}
/**
* Use this method instead of JAXLPlugin::add to register a callback for connected instance only
*/
function addPlugin($hook, $callback, $priority=10) {
JAXLPlugin::add($hook, $callback, $priority, $this->uid);
}
/**
* Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
*/
function removePlugin($hook, $callback, $priority=10) {
JAXLPlugin::remove($hook, $callback, $priority, $this->uid);
}
/**
* Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
diff --git a/core/jaxl.s5b.php b/core/jaxl.s5b.php
new file mode 100644
index 0000000..7a45bd8
--- /dev/null
+++ b/core/jaxl.s5b.php
@@ -0,0 +1,123 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage core
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * Jaxl SOCKS5 class
+ * http://tools.ietf.org/html/rfc1928
+ */
+ class JAXLS5B {
+
+ var $socket = null;
+ var $connected = false;
+
+ /**
+ * Constructor connects to the server and sends a version identifier/method selection message
+ */
+ function __construct($ip, $port, $jaxl) {
+ if($this->socket = @fsockopen($ip, (int)$port, $errno, $errstr)) {
+ $jaxl->log("[[JAXLS5B]] Socket opened to $ip:$port");
+ // send version/identifier selection message
+ $pkt = pack("C3", 0x05, 0x01, 0x00);
+ $this->write($pkt);
+ $jaxl->log("[[JAXLS5B]] Sending selection message to $ip:$port");
+
+ // recv method selection message
+ $rcv = '';
+ while($buffer = $this->read()) {
+ $rcv .= $buffer;
+ $pkt = unpack("Cversion/Cmethod", $rcv);
+ if($pkt['version'] == 0x05 && $pkt['method'] == 0x00) {
+ $jaxl->log("[[JAXLS5B]] Selection message accepted by $ip:$port");
+ return true;
+ }
+ }
+
+ // close socket if method not accepted
+ $jaxl->log("[[JAXLS5B]] Selection message not accepted by $ip:$port");
+ fclose($this->socket);
+ }
+
+ $jaxl->log("[[JAXLS5B]] Unable to open socket to $ip:$port");
+ return false;
+ }
+
+ /**
+ * Connect method send request details and receive replies from the server
+ */
+ function connect($sid, $rJid, $tJid, $jaxl) {
+ if($this->socket) {
+ // send request detail pkt
+ $dstAddr = sha1($sid.$rJid.$tJid);
+ $pkt = pack("C5", 0x05, 0x01, 0x00, 0x03, strlen($dstAddr)).$dstAddr.pack("n", 0);
+ $this->write($pkt);
+ $jaxl->log("[[JAXLS5B]] Sending request detail packet to $dstAddr:0");
+
+ // recv server ack
+ $rcv = '';
+ while($buffer = fread($this->socket, 1024)) {
+ $rcv .= $buffer;
+ $pkt = unpack("Cversion/Cresult/Creg/Ctype/Lip/Sport", $rcv);
+ if($pkt['version'] == 0x05 && $pkt['result'] == 0x00) {
+ $jaxl->log("[[JAXLS5B]] Request detail packet accepted, S5B completed on $dstAddr:0");
+ $this->connected = true;
+ return true;
+ }
+ }
+ }
+
+ $jaxl->log("[[JAXLS5B]] Unable to complete S5B on $dstAddr:0");
+ $this->connected = false;
+ return false;
+ }
+
+ function read($bytes=1024) {
+ return fread($this->socket, $bytes);
+ }
+
+ function write($pkt) {
+ return fwrite($this->socket, $pkt);
+ }
+
+ }
+
+?>
|
jaxl/JAXL | 7d08e16d325d0b500c4d6a107aac0f6bc23d3d14 | Checking XEP 0012 (last activity), 0047 (in-band bytestream), 0065 (SOCKS5 ByteStream) | diff --git a/xep/jaxl.0012.php b/xep/jaxl.0012.php
new file mode 100644
index 0000000..421f0d3
--- /dev/null
+++ b/xep/jaxl.0012.php
@@ -0,0 +1,81 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /*
+ * XEP: 0012 Last Activity
+ * Version: 2.0
+ * Url: http://xmpp.org/extensions/xep-0012.html
+ */
+ class JAXL0012 {
+
+ public static $ns = 'jabber:iq:last';
+
+ public static function init() {
+ global $jaxl;
+ $jaxl->features[] = self::$ns;
+
+ JAXLPlugin::add('jaxl_get_iq_get', array('JAXL0012', 'getIq'));
+ }
+
+ public static function getLastActivity($to, $from, $callback) {
+ $payload = '';
+ $payload .= '<query xmlns="'.self::$ns.'"/>';
+ return XMPPSend::iq('get', $payload, $to, $from, $callback);
+ }
+
+ public static function getIq($arr) {
+ if(isset($arr['queryXmlns']) && $arr['queryXmlns'] == self::$ns) {
+ $payload = '';
+ $payload .= '<query xmlns="'.self::$ns.'" seconds="0">';
+ $payload .= '</query>';
+
+ return XMPPSend::iq('result', $payload, $arr['from'], $arr['to'], FALSE, $arr['id']);
+ }
+ else {
+ return $arr;
+ }
+ }
+
+ }
+
+?>
diff --git a/xep/jaxl.0047.php b/xep/jaxl.0047.php
new file mode 100644
index 0000000..70d9a21
--- /dev/null
+++ b/xep/jaxl.0047.php
@@ -0,0 +1,148 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-0047: In-Band Bytestreams
+ */
+ class JAXL0047 {
+
+ public static $id = array();
+ public static $ns = 'http://jabber.org/protocol/ibb';
+
+ public static function init($jaxl) {
+ $jaxl->features[] = self::$ns;
+
+ JAXLXml::addTag('iq', 'open', '//iq/open/@xmlns');
+ JAXLXml::addTag('iq', 'openSid', '//iq/open/@sid');
+ JAXLXml::addTag('iq', 'openBlkSize', '//iq/open/@block-size');
+ JAXLXml::addTag('iq', 'data', '//iq/data/@xmlns');
+ JAXLXml::addTag('iq', 'dataSid', '//iq/data/@sid');
+ JAXLXml::addTag('iq', 'dataSeq', '//iq/data/@seq');
+ JAXLXml::addTag('iq', 'dataEncoded', '//iq/data');
+ JAXLXml::addTag('iq', 'close', '//iq/close/@xmlns');
+ JAXLXml::addTag('iq', 'closeSid', '//iq/close/@sid');
+
+ $jaxl->addPlugin('jaxl_get_iq_set', array('JAXL0047', 'handleTransfer'));
+ }
+
+ public static function handleTransfer($payload, $jaxl) {
+ if($payload['open'] == self::$ns) {
+ $jaxl->log("[[JAXL0047]] File transfer opened for siId ".$payload['openSid']);
+ file_put_contents($jaxl->tmpPath.'/'.$payload['openSid'], '');
+ XMPPSend::iq($jaxl, 'result', '', $payload['from'], $payload['to'], false, $payload['id']);
+ }
+ else if($payload['data'] == self::$ns) {
+ $jaxl->log("[[JAXL0047]] Accepting transfer data for siId ".$payload['dataSid']);
+ $data = base64_decode($payload['dataEncoded']);
+ file_put_contents($jaxl->tmpPath.'/'.$payload['dataSid'], $data, FILE_APPEND);
+
+ XMPPSend::iq($jaxl, 'result', '', $payload['from'], $payload['to'], false, $payload['id']);
+ }
+ else if($payload['close'] == self::$ns) {
+ $jaxl->log("[[JAXL0047]] Transfer complete for siId ".$payload['closeSid']);
+ $jaxl->executePlugin('jaxl_post_file_request', array('tmp'=>$jaxl->tmpPath.'/'.$payload['closeSid']));
+ XMPPSend::iq($jaxl, 'result', '', $payload['from'], $payload['to'], false, $payload['id']);
+ }
+
+ return $payload;
+ }
+
+ public static function sendFile($jaxl, $payload) {
+ // initiate file request session
+ $jaxl->log("[[JAXL0047]] Opening file transfer with siId ".$payload['siId']);
+ $xml = '<open xmlns="'.self::$ns.'" block-size="4096" sid="'.$payload['siId'].'" stanza="iq"/>';
+ $id = XMPPSend::iq($jaxl, 'set', $xml, $payload['to'], false, array('JAXL0047', 'transferFile'));
+
+ self::$id[$id] = $payload;
+ self::$id[$id]['seq'] = 0;
+ self::$id[$id]['block-size'] = 4096;
+ self::$id[$id]['stanza'] = 'iq';
+
+ return $id;
+ }
+
+ public static function transferFile($payload, $jaxl) {
+ if(!isset(self::$id[$payload['id']]))
+ return $payload;
+
+ // iq id buffered for file transfer, transmit data
+ $fp = fopen(self::$id[$payload['id']]['file'], 'r');
+ fseek($fp, self::$id[$payload['id']]['seq']*self::$id[$payload['id']]['block-size']);
+ $data = fread($fp, self::$id[$payload['id']]['block-size']);
+ fclose($fp);
+
+ if(self::$id[$payload['id']]['seq'] == -1) {
+ $jaxl->log("[[JAXL0047]] File transfer complete for siId ".self::$id[$payload['id']]['siId']);
+ $jaxl->executePlugin('jaxl_post_file_transfer', self::$id[$payload['id']]);
+ unset(self::$id[$payload['id']]);
+ return;
+ }
+ else if(strlen($data) == 0) {
+ $jaxl->log("[[JAXL0047]] File transfer closed for siId ".self::$id[$payload['id']]['siId']);
+ $xml = '<close xmlns="'.self::$ns.'" sid="'.self::$id[$payload['id']]['siId'].'"/>';
+
+ $id = XMPPSend::iq($jaxl, 'set', $xml, self::$id[$payload['id']]['to'], false, array('JAXL0047', 'transferFile'));
+ self::$id[$id] = self::$id[$payload['id']];
+ self::$id[$id]['seq'] = -1;
+
+ unset(self::$id[$payload['id']]);
+ return $id;
+ }
+ else {
+ $jaxl->log("[[JAXL0047]] Transfering file data for seq ".self::$id[$payload['id']]['seq']." for siId ".self::$id[$payload['id']]['siId']);
+ $xml = '<data xmlns="'.self::$ns.'" seq="'.self::$id[$payload['id']]['seq'].'" sid="'.self::$id[$payload['id']]['siId'].'">';
+ $xml .= base64_encode($data);
+ $xml .= '</data>';
+
+ $id = XMPPSend::iq($jaxl, 'set', $xml, self::$id[$payload['id']]['to'], false, array('JAXL0047', 'transferFile'));
+ self::$id[$id] = self::$id[$payload['id']];
+ self::$id[$id]['seq'] = self::$id[$id]['seq']+1;
+
+ unset(self::$id[$payload['id']]);
+ return $id;
+ }
+ }
+
+ }
+
+?>
diff --git a/xep/jaxl.0065.php b/xep/jaxl.0065.php
new file mode 100644
index 0000000..83da959
--- /dev/null
+++ b/xep/jaxl.0065.php
@@ -0,0 +1,157 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-0065: SOCKS5 Bytestreams
+ */
+ class JAXL0065 {
+
+ public static $id = array();
+ public static $ns = 'http://jabber.org/protocol/bytestreams';
+
+ public static function init($jaxl) {
+ jaxl_require('JAXLS5B'); // SOCKS5
+ $jaxl->features[] = self::$ns;
+
+ JAXLXml::addTag('iq', 'streamSid', '//iq/query/@sid');
+ JAXLXml::addTag('iq', 'streamMode', '//iq/query/@mode');
+ JAXLXml::addTag('iq', 'streamHost', '//iq/query/streamhost/@host');
+ JAXLXml::addTag('iq', 'streamPort', '//iq/query/streamhost/@port');
+ JAXLXml::addTag('iq', 'streamJid', '//iq/query/streamhost/@jid');
+ JAXLXml::addTag('iq', 'streamHostUsed', '//iq/query/streamhost-used/@jid');
+
+ $jaxl->addPlugin('jaxl_get_iq_set', array('JAXL0065', 'getStreamHost'));
+ }
+
+ /**
+ * Method listens for incoming iq set packets. If incoming packet matches namespace:
+ * a) Establishes S5B with one of the stream host
+ * b) Notify requestor about user stream host
+ * c) Read S5B socket for data
+ */
+ public static function getStreamHost($payload, $jaxl) {
+ if($payload['queryXmlns'] == self::$ns) {
+ if(!is_array($payload['streamHost'])) $payload['streamHost'] = array($payload['streamHost']);
+ if(!is_array($payload['streamPort'])) $payload['streamPort'] = array($payload['streamPort']);
+ if(!is_array($payload['streamJid'])) $payload['streamJid'] = array($payload['streamJid']);
+
+ foreach($payload['streamHost'] as $key => $streamHost) {
+ $s5b = new JAXLS5B($streamHost, $payload['streamPort'][$key], $jaxl);
+ $s5b->connect($payload['streamSid'], $payload['from'], $payload['to'], $jaxl);
+ if($s5b->connected) {
+ // connected to proxy, use this streamHost
+ self::notifyRequestor($payload, $jaxl);
+
+ // read socket data
+ $jaxl->log("[[JAXL0065]] Using stream host $streamHost");
+ while($buffer = $s5b->read()) {
+ $jaxl->log("[[JAXL0065]] Reading 1024 bytes of data via proxy");
+ file_put_contents($jaxl->tmpPath.'/'.$payload['streamSid'], $buffer, FILE_APPEND);
+ }
+
+ unset($s5b);
+ $jaxl->executePlugin('jaxl_post_file_request', array('tmp'=>$jaxl->tmpPath.'/'.$payload['streamSid']));
+ break;
+ }
+ }
+ }
+ return $payload;
+ }
+
+ public static function notifyRequestor($payload, $jaxl) {
+ $xml = '<query xmlns="'.self::$ns.'" sid="'.$payload['streamSid'].'">';
+ $xml .= '<streamhost-used jid="'.$payload['streamJid'][0].'"/>';
+ $xml .= '</query>';
+ return XMPPSend::iq($jaxl, 'result', $xml, $payload['from'], $jaxl->jid, false, $payload['id']);
+ }
+
+ public static function sendFile($jaxl, $payload) {
+ $xml = '<query xmlns="'.self::$ns.'" sid="'.$payload['siId'].'">';
+ $xml .= '<streamhost host="127.0.1.1" jid="proxy.dev.jaxl.im" port="7777"/>';
+ $xml .= '</query>';
+ $id = XMPPSend::iq($jaxl, 'set', $xml, $payload['to'], $jaxl->jid, array('JAXL0065', 'establishS5B'));
+
+ self::$id[$id] = $payload;
+ return $id;
+ }
+
+ public static function establishS5B($payload, $jaxl) {
+ if(!isset(self::$id[$payload['id']]))
+ return $payload;
+
+ // establish S5B connection
+ $s5b = new JAXLS5B('127.0.1.1', 7777, $jaxl);
+ $s5b->connect($payload['streamSid'], $payload['to'], $payload['from'], $jaxl);
+ if($s5b->connected) {
+ // activate bytestream
+ $id = self::activateS5B('proxy.dev.jaxl.im', $payload['streamSid'], $payload['from'], $jaxl);
+ self::$id[$id] = self::$id[$payload['id']];
+ self::$id[$id]['s5b'] = &$s5b;
+ }
+
+ unset($s5b);
+ unset(self::$id[$payload['id']]);
+ return $payload;
+ }
+
+ public static function activateS5B($streamHost, $sid, $tJid, $jaxl) {
+ $xml = '<query xmlns="'.self::$ns.'" sid="'.$sid.'">';
+ $xml .= '<activate>'.$tJid.'</activate>';
+ $xml .= '</query>';
+ return XMPPSend::iq($jaxl, 'set', $xml, $streamHost, false, array('JAXL0065', 'transferFile'));
+ }
+
+ public static function transferFile($payload, $jaxl) {
+ // send data via proxy
+ $fh = fopen(self::$id[$payload['id']]['file'], 'r');
+ while($data = fread($fh, 1024)) {
+ $jaxl->log("[[JAXL0065]] Sending 1024 bytes of data via proxy");
+ self::$id[$payload['id']]['s5b']->write($data);
+ }
+ $jaxl->executePlugin('jaxl_post_file_transfer', null);
+ unset(self::$id[$payload['id']]);
+ }
+
+ }
+
+?>
|
jaxl/JAXL | 69537f88370d5fa9d0572c37cbb2db9137945c76 | Checking of google xep implementations (unfinished) | diff --git a/xep/google/jaxl.jingleinfo.php b/xep/google/jaxl.jingleinfo.php
new file mode 100644
index 0000000..7156b7e
--- /dev/null
+++ b/xep/google/jaxl.jingleinfo.php
@@ -0,0 +1,60 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-xxxx : Google JingleInfo
+ */
+ class JAXLJingleInfo {
+
+ public static $ns = 'google:jingleinfo';
+
+ public static function init($jaxl) {
+ $jaxl->features[] = self::$ns;
+
+ JAXLXml::addTag('iq', 'gStunHost', '//iq/query/stun/server/@host');
+ JAXLXml::addTag('iq', 'gStunUdp', '//iq/query/stun/server/@udp');
+ }
+
+ }
+
+?>
diff --git a/xep/google/jaxl.mailnotify.php b/xep/google/jaxl.mailnotify.php
new file mode 100644
index 0000000..11f83a8
--- /dev/null
+++ b/xep/google/jaxl.mailnotify.php
@@ -0,0 +1,79 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-xxxx : Google MailNotify
+ */
+ class JAXLMailNotify {
+
+ public static $ns = 'google:mail:notify';
+
+ public static function init($jaxl) {
+ $jaxl->features[] = self::$ns;
+
+ JAXLXml::addTag('iq', 'gMailResultTime', '//iq/mailbox/@result-time');
+ JAXLXml::addTag('iq', 'gMailUrl', '//iq/mailbox/@url');
+ JAXLXml::addTag('iq', 'gMailTotalMatched', '//iq/mailbox/@total-matched');
+ JAXLXml::addTag('iq', 'gMailTotalEstimate', '//iq/mailbox/@total-estimate');
+
+ JAXLXml::addTag('iq', 'gMailThreadTid', '//iq/mailbox/mail-thread-info/@tid');
+ JAXLXml::addTag('iq', 'gMailThreadParticipation', '//iq/mailbox/mail-thread-info/@participation');
+ JAXLXml::addTag('iq', 'gMailThreadMessages', '//iq/mailbox/mail-thread-info/@messages');
+ JAXLXml::addTag('iq', 'gMailThreadDate', '//iq/mailbox/mail-thread-info/@date');
+ JAXLXml::addTag('iq', 'gMailThreadUrl', '//iq/mailbox/mail-thread-info/@url');
+
+ JAXLXml::addTag('iq', 'gMailLabels', '//iq/mailbox/mail-thread-info/labels');
+ JAXLXml::addTag('iq', 'gMailSubject', '//iq/mailbox/mail-thread-info/subject');
+ JAXLXml::addTag('iq', 'gMailSnippet', '//iq/mailbox/mail-thread-info/snippet');
+
+ JAXLXml::addTag('iq', 'gMailSenderName', '//iq/mailbox/mail-thread-info/senders/@name');
+ JAXLXml::addTag('iq', 'gMailSenderAddress', '//iq/mailbox/mail-thread-info/senders/@address');
+ JAXLXml::addTag('iq', 'gMailSenderOriginator', '//iq/mailbox/mail-thread-info/senders/@originator');
+ JAXLXml::addTag('iq', 'gMailSenderUnread', '//iq/mailbox/mail-thread-info/senders/@unread');
+
+ JAXLXml::addTag('iq', 'gMailNotify', '//iq/new-mail/@xmlns');
+ }
+
+ }
+
+?>
diff --git a/xep/google/jaxl.nosave.php b/xep/google/jaxl.nosave.php
new file mode 100644
index 0000000..a855c4b
--- /dev/null
+++ b/xep/google/jaxl.nosave.php
@@ -0,0 +1,57 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-xxxx : Google NoSave
+ */
+ class JAXLNoSave {
+
+ public static $ns = 'google:nosave';
+
+ public static function init($jaxl) {
+ $jaxl->features[] = self::$ns;
+ }
+
+ }
+
+?>
diff --git a/xep/google/jaxl.roster.php b/xep/google/jaxl.roster.php
new file mode 100644
index 0000000..6d937a4
--- /dev/null
+++ b/xep/google/jaxl.roster.php
@@ -0,0 +1,57 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-xxxx : Google Roster
+ */
+ class JAXLRoster {
+
+ public static $ns = 'google:roster';
+
+ public static function init($jaxl) {
+ $jaxl->features[] = self::$ns;
+ }
+
+ }
+
+?>
diff --git a/xep/google/jaxl.setting.php b/xep/google/jaxl.setting.php
new file mode 100644
index 0000000..c0d8df9
--- /dev/null
+++ b/xep/google/jaxl.setting.php
@@ -0,0 +1,61 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-xxxx : Google Setting
+ */
+ class JAXLGoogleSetting {
+
+ public static $ns = 'google:setting';
+
+ public static function init($jaxl) {
+ $jaxl->features[] = self::$ns;
+
+ JAXLXml::addTag('iq', 'gAutoAccept', '//iq/usersetting/autoacceptsuggestions/@value');
+ JAXLXml::addTag('iq', 'gMailNotify', '//iq/usersetting/mailnotifications/@value');
+ JAXLXml::addTag('iq', 'gArchiveEnable', '//iq/usersetting/archivingenabled/@value');
+ }
+
+ }
+
+?>
diff --git a/xep/google/jaxl.sharedstatus.php b/xep/google/jaxl.sharedstatus.php
new file mode 100644
index 0000000..1edac13
--- /dev/null
+++ b/xep/google/jaxl.sharedstatus.php
@@ -0,0 +1,57 @@
+<?php
+/**
+ * Jaxl (Jabber XMPP Library)
+ *
+ * Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * * Neither the name of Abhinav Singh nor the names of his
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @package jaxl
+ * @subpackage xep
+ * @author Abhinav Singh <[email protected]>
+ * @copyright Abhinav Singh
+ * @link http://code.google.com/p/jaxl
+ */
+
+ /**
+ * XEP-xxxx : Google SharedStatus
+ */
+ class JAXLSharedStatus {
+
+ public static $ns = 'google:shared-status';
+
+ public static function init($jaxl) {
+ $jaxl->features[] = self::$ns;
+ }
+
+ }
+
+?>
|
jaxl/JAXL | cff169b61077da4cae12b55c53f08fab79b967be | Added some TO-DO for later release if this problem really is a problem | diff --git a/xep/jaxl.0124.php b/xep/jaxl.0124.php
index 6f45362..c872561 100644
--- a/xep/jaxl.0124.php
+++ b/xep/jaxl.0124.php
@@ -1,266 +1,266 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0124: Bosh Implementation
* Maintain various attributes like rid, sid across requests
*/
class JAXL0124 {
private static $buffer = array();
private static $sess = false;
public static function init($jaxl) {
// initialize working parameters for this jaxl instance
$jaxl->bosh = array(
'host' => 'localhost',
'port' => 5280,
'suffix'=> 'http-bind',
'out' => true,
'outheaders' => 'Content-type: application/json',
'cookie'=> array(
'ttl' => 3600,
'path' => '/',
'domain'=> false,
'https' => false,
'httponly' => true
),
'hold' => '1',
'wait' => '30',
'polling' => '0',
'version' => '1.6',
'xmppversion' => '1.0',
'secure'=> true,
'content' => 'text/xml; charset=utf-8',
'headers' => array('Accept-Encoding: gzip, deflate','Content-Type: text/xml; charset=utf-8'),
'xmlns' => 'http://jabber.org/protocol/httpbind',
'xmlnsxmpp' => 'urn:xmpp:xbosh',
'url' => 'http://localhost:5280/http-bind',
'session' => true
);
// parse user options
$jaxl->bosh['host'] = $jaxl->getConfigByPriority(@$jaxl->config['boshHost'], "JAXL_BOSH_HOST", $jaxl->bosh['host']);
$jaxl->bosh['port'] = $jaxl->getConfigByPriority(@$jaxl->config['boshPort'], "JAXL_BOSH_PORT", $jaxl->bosh['port']);
$jaxl->bosh['suffix'] = $jaxl->getConfigByPriority(@$jaxl->config['boshSuffix'], "JAXL_BOSH_SUFFIX", $jaxl->bosh['suffix']);
$jaxl->bosh['out'] = $jaxl->getConfigByPriority(@$jaxl->config['boshOut'], "JAXL_BOSH_OUT", $jaxl->bosh['out']);
$jaxl->bosh['session'] = $jaxl->getConfigByPriority(@$jaxl->config['boshSession'], "JAXL_BOSH_SESSION", $jaxl->bosh['session']);
$jaxl->bosh['url'] = "http://".$jaxl->bosh['host'].":".$jaxl->bosh['port']."/".$jaxl->bosh['suffix']."/";
// cookie params
$jaxl->bosh['cookie']['ttl'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieTTL'], "JAXL_BOSH_COOKIE_TTL", $jaxl->bosh['cookie']['ttl']);
$jaxl->bosh['cookie']['path'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookiePath'], "JAXL_BOSH_COOKIE_PATH", $jaxl->bosh['cookie']['path']);
$jaxl->bosh['cookie']['domain'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieDomain'], "JAXL_BOSH_COOKIE_DOMAIN", $jaxl->bosh['cookie']['domain']);
$jaxl->bosh['cookie']['https'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieHTTPS'], "JAXL_BOSH_COOKIE_HTTPS", $jaxl->bosh['cookie']['https']);
$jaxl->bosh['cookie']['httponly'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieHTTPOnly'], "JAXL_BOSH_COOKIE_HTTP_ONLY", $jaxl->bosh['cookie']['httponly']);
// start session
self::startSession($jaxl);
$jaxl->addPlugin('jaxl_post_bind', array('JAXL0124', 'postBind'));
$jaxl->addPlugin('jaxl_send_xml', array('JAXL0124', 'wrapBody'));
$jaxl->addPlugin('jaxl_pre_handler', array('JAXL0124', 'preHandler'));
$jaxl->addPlugin('jaxl_post_handler', array('JAXL0124', 'postHandler'));
$jaxl->addPlugin('jaxl_send_body', array('JAXL0124', 'sendBody'));
-
+
self::loadSession($jaxl);
}
public static function startSession($jaxl) {
if(!$jaxl->bosh['session']) {
$jaxl->log("[[JAXL0124]] Not starting session as forced by constructor config", 5);
return;
}
session_set_cookie_params(
$jaxl->bosh['cookie']['ttl'],
$jaxl->bosh['cookie']['path'],
$jaxl->bosh['cookie']['domain'],
$jaxl->bosh['cookie']['https'],
$jaxl->bosh['cookie']['httponly']
);
session_start();
}
public static function postHandler($payload, $jaxl) {
if(!$jaxl->bosh['out']) return $payload;
$payload = json_encode(self::$buffer);
$jaxl->log("[[BoshOut]]\n".$payload, 5);
header($jaxl->bosh['outheaders']);
echo $payload;
exit;
}
public static function postBind($payload, $jaxl) {
$jaxl->bosh['jid'] = $jaxl->jid;
$_SESSION['jaxl_auth'] = true;
return;
}
public static function out($payload) {
self::$buffer[] = $payload;
}
public static function loadSession($jaxl) {
$jaxl->bosh['rid'] = isset($_SESSION['jaxl_rid']) ? (string) $_SESSION['jaxl_rid'] : rand(1000, 10000);
$jaxl->bosh['sid'] = isset($_SESSION['jaxl_sid']) ? (string) $_SESSION['jaxl_sid'] : false;
$jaxl->lastid = isset($_SESSION['jaxl_id']) ? $_SESSION['jaxl_id'] : $jaxl->lastid;
$jaxl->jid = isset($_SESSION['jaxl_jid']) ? $_SESSION['jaxl_jid'] : $jaxl->jid;
$jaxl->log("[[JAXL0124]] Loading session data\n".json_encode($_SESSION), 5);
}
public static function saveSession($xml, $jaxl) {
if($_SESSION['jaxl_auth'] === true) {
$_SESSION['jaxl_rid'] = isset($jaxl->bosh['rid']) ? $jaxl->bosh['rid'] : false;
$_SESSION['jaxl_sid'] = isset($jaxl->bosh['sid']) ? $jaxl->bosh['sid'] : false;
$_SESSION['jaxl_jid'] = $jaxl->jid;
$_SESSION['jaxl_id'] = $jaxl->lastid;
if($jaxl->bosh['out'] && $jaxl->bosh['session']) {
session_write_close();
}
if(self::$sess && $jaxl->bosh['out']) {
list($body, $xml) = self::unwrapBody($xml);
$jaxl->log("[[JAXL0124]] Auth complete, sync now\n".json_encode($_SESSION), 5);
return self::out(array('jaxl'=>'jaxl', 'xml'=>urlencode($xml)));
}
else {
self::$sess = true;
$jaxl->log("[[JAXL0124]] Auth complete, commiting session now\n".json_encode($_SESSION), 5);
}
}
else {
$jaxl->log("[[JAXL0124]] Not authed yet, Not commiting session\n".json_encode($_SESSION), 5);
}
return $xml;
}
public static function wrapBody($xml, $jaxl) {
$body = trim($xml);
if(substr($body, 1, 4) != 'body') {
$body = '';
$body .= '<body rid="'.++$jaxl->bosh['rid'].'"';
$body .= ' sid="'.$jaxl->bosh['sid'].'"';
$body .= ' xmlns="http://jabber.org/protocol/httpbind">';
$body .= $xml;
$body .= "</body>";
$_SESSION['jaxl_rid'] = $jaxl->bosh['rid'];
}
return $body;
}
public static function sendBody($xml, $jaxl) {
$xml = self::saveSession($xml, $jaxl);
if($xml != false) {
$jaxl->log("[[XMPPSend]] body\n".$xml, 4);
$payload = JAXLUtil::curl($jaxl->bosh['url'], 'POST', $jaxl->bosh['headers'], $xml);
// curl error handling
if($payload['errno'] != 0) {
$log = "[[JAXL0124]] Curl errno ".$payload['errno']." encountered";
switch($payload['errno']) {
case 7:
$log .= ". Failed to connect with ".$jaxl->bosh['url'];
break;
case 52:
$log .= ". Empty response rcvd from bosh endpoint";
break;
default:
break;
}
-
+
$jaxl->executePlugin('jaxl_get_bosh_curl_error', $payload);
$jaxl->log($log);
}
$payload = $payload['content'];
$jaxl->handler($payload);
}
return $xml;
}
public static function unwrapBody($payload) {
if(substr($payload, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $payload, $m);
else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $payload, $m);
if(isset($m[1][0])) $body = "<body ".$m[1][0].">";
else $body = "<body>";
if(isset($m[2][0])) $payload = $m[2][0];
else $payload = '';
return array($body, $payload);
}
public static function preHandler($payload, $jaxl) {
if(substr($payload, 1, 4) == "body") {
list($body, $payload) = self::unwrapBody($payload);
if($payload == '') {
if($_SESSION['jaxl_auth'] === 'disconnect') {
$_SESSION['jaxl_auth'] = false;
$jaxl->executePlugin('jaxl_post_disconnect', $body);
}
else {
$jaxl->executePlugin('jaxl_get_empty_body', $body);
}
}
if($_SESSION['jaxl_auth'] === 'connect') {
$arr = $jaxl->xml->xmlize($body);
if(isset($arr["body"]["@"]["sid"])) {
$_SESSION['jaxl_auth'] = false;
$_SESSION['jaxl_sid'] = $arr["body"]["@"]["sid"];
$jaxl->bosh['sid'] = $arr["body"]["@"]["sid"];
$jaxl->log("[[JAXL0124]] Updated session to ".json_encode($_SESSION), 5);
}
}
}
return $payload;
}
}
?>
diff --git a/xmpp/xmpp.send.php b/xmpp/xmpp.send.php
index 5d9a7da..5b0f084 100644
--- a/xmpp/xmpp.send.php
+++ b/xmpp/xmpp.send.php
@@ -1,206 +1,216 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLUtil',
'JAXLog'
));
/**
* XMPP Send Class
* Provide methods for sending all kind of xmpp stream and stanza's
*/
class XMPPSend {
public static function startStream($jaxl) {
$xml = '<stream:stream xmlns:stream="http://etherx.jabber.org/streams" version="1.0" xmlns="jabber:client" to="'.$jaxl->domain.'" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">';
return $jaxl->sendXML($xml);
}
public static function endStream($jaxl) {
$xml = '</stream:stream>';
return $jaxl->sendXML($xml, true);
}
public static function startTLS($jaxl) {
$xml = '<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>';
return $jaxl->sendXML($xml);
}
public static function startAuth($jaxl) {
$type = $jaxl->authType;
$xml = '<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="'.$type.'">';
switch($type) {
case 'DIGEST-MD5':
break;
case 'PLAIN':
$xml .= base64_encode("\x00".$jaxl->user."\x00".$jaxl->pass);
break;
case 'ANONYMOUS':
break;
case 'X-FACEBOOK-PLATFORM':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
$xml .= base64_encode("n,,n=".$jaxl->user.",r=".base64_encode(JAXLUtil::generateNonce()));
break;
default:
break;
}
$xml .= '</auth>';
$jaxl->log("[[XMPPSend]] Performing Auth type: ".$type);
return $jaxl->sendXML($xml);
}
public static function startSession($jaxl, $callback) {
$payload = '<session xmlns="urn:ietf:params:xml:ns:xmpp-session"/>';
return self::iq($jaxl, "set", $payload, $jaxl->domain, false, $callback);
}
public static function startBind($jaxl, $callback) {
$payload = '<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">';
$payload .= '<resource>'.$jaxl->resource.'</resource>';
$payload .= '</bind>';
return self::iq($jaxl, "set", $payload, false, false, $callback);
}
public static function message($jaxl, $to, $from=false, $child=false, $type='normal', $id=false, $ns='jabber:client') {
$xml = '';
if(is_array($to)) {
foreach($to as $key => $value) {
$xml .= self::prepareMessage($jaxl, $to[$key], $from[$key], $child[$key], $type[$key], $id[$key], $ns[$key]);
}
}
else {
$xml .= self::prepareMessage($jaxl, $to, $from, $child, $type, $id, $ns);
}
$jaxl->executePlugin('jaxl_send_message', $xml);
return $jaxl->sendXML($xml);
}
public static function prepareMessage($jaxl, $to, $from, $child, $type, $id, $ns) {
$xml = '<message';
if($from) $xml .= ' from="'.$from.'"';
$xml .= ' to="'.htmlspecialchars($to).'"';
if($type) $xml .= ' type="'.$type.'"';
if($id) $xml .= ' id="'.$id.'"';
$xml .= '>';
if($child) {
if(isset($child['subject'])) $xml .= '<subject>'.JAXLUtil::xmlentities($child['subject']).'</subject>';
if(isset($child['body'])) $xml .= '<body>'.JAXLUtil::xmlentities($child['body']).'</body>';
if(isset($child['thread'])) $xml .= '<thread>'.$child['thread'].'</thread>';
if(isset($child['payload'])) $xml .= $child['payload'];
}
$xml .= '</message>';
return $xml;
}
public static function presence($jaxl, $to=false, $from=false, $child=false, $type=false, $id=false, $ns='jabber:client') {
$xml = '';
if(is_array($to)) {
foreach($to as $key => $value) {
$xml .= self::preparePresence($jaxl, $to[$key], $from[$key], $child[$key], $type[$key], $id[$key], $ns[$key]);
}
}
else {
$xml .= self::preparePresence($jaxl, $to, $from, $child, $type, $id, $ns);
}
$jaxl->executePlugin('jaxl_send_presence', $xml);
return $jaxl->sendXML($xml);
}
public static function preparePresence($jaxl, $to, $from, $child, $type, $id, $ns) {
$xml = '<presence';
if($type) $xml .= ' type="'.$type.'"';
if($from) $xml .= ' from="'.$from.'"';
if($to) $xml .= ' to="'.htmlspecialchars($to).'"';
if($id) $xml .= ' id="'.$id.'"';
$xml .= '>';
if($child) {
if(isset($child['show'])) $xml .= '<show>'.$child['show'].'</show>';
if(isset($child['status'])) $xml .= '<status>'.JAXLUtil::xmlentities($child['status']).'</status>';
if(isset($child['priority'])) $xml .= '<priority>'.$child['priority'].'</priority>';
if(isset($child['payload'])) $xml .= $child['payload'];
}
$xml.= '</presence>';
return $xml;
}
public static function iq($jaxl, $type, $payload=false, $to=false, $from=false, $callback=false, $id=false, $ns='jabber:client') {
if($type == 'get' || $type == 'set') {
$id = $jaxl->getId();
- if($callback) $jaxl->addPlugin('jaxl_get_iq_'.$id, $callback);
+
+ if($callback) {
+ $jaxl->addPlugin('jaxl_get_iq_'.$id, $callback);
+
+ // In bosh environment following scenario needs to be taken care:
+ // request-1 pinging for new data
+ // request-2 sends an iq get request
+ // request-1 receives iq result response
+ // callback registered during request-2 is unavailable in request-1 loop
+ // as a result user application doesn't receive any callback for data
+ }
}
$types = array('get','set','result','error');
$xml = '';
$xml .= '<iq';
$xml .= ' type="'.$type.'"';
$xml .= ' id="'.$id.'"';
if($to) $xml .= ' to="'.$to.'"';
if($from) $xml .= ' from="'.$from.'"';
$xml .= '>';
if($payload) $xml .= $payload;
$xml .= '</iq>';
$jaxl->sendXML($xml);
if($type == 'get' || $type == 'set') return $id;
else return true;
}
}
?>
|
jaxl/JAXL | e28605233f86eca234831961e06028de499a96bc | Forcing curl CURLOPT_ENCODING to gzip,deflate (boshchat now works with jabber.fr) | diff --git a/core/jaxl.util.php b/core/jaxl.util.php
index 4aed8ef..bf98856 100644
--- a/core/jaxl.util.php
+++ b/core/jaxl.util.php
@@ -1,215 +1,212 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl Utility Class
*/
class JAXLUtil {
- public static function curl($url, $type='GET', $headers=false, $data=false, $user=false, $pass=false) {
+ public static function curl($url, $type='GET', $headers=array(), $data=false, $user=false, $pass=false) {
$ch = curl_init($url);
-
- // added by Movim Project
- if(defined('JAXL_CURL_ASYNC') && JAXL_CURL_ASYNC) curl_setopt($ch, CURLOPT_TIMEOUT, 1);
-
+
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_HEADER, false);
- if($headers) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+ curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_VERBOSE, false);
if($type == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
if($user && $pass) {
curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$pass);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
}
$rs = array();
$rs['content'] = curl_exec($ch);
$rs['errno'] = curl_errno($ch);
$rs['errmsg'] = curl_error($ch);
$rs['header'] = curl_getinfo($ch);
curl_close($ch);
return $rs;
}
public static function isWin() {
return strtoupper(substr(PHP_OS,0,3)) == "WIN" ? true : false;
}
public static function pcntlEnabled() {
return extension_loaded('pcntl');
}
public static function sslEnabled() {
return extension_loaded('openssl');
}
public static function getTime() {
list($usec, $sec) = explode(" ", microtime());
return (float) $sec + (float) $usec;
}
public static function splitXML($xml) {
$xmlarr = array();
$temp = preg_split("/<(message|iq|presence|stream|proceed|challenge|success|failure)(?=[\:\s\>])/", $xml, -1, PREG_SPLIT_DELIM_CAPTURE);
for($a=1; $a<count($temp); $a=$a+2) $xmlarr[] = "<".$temp[$a].$temp[($a+1)];
return $xmlarr;
}
public static function explodeData($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 static function implodeData($data) {
$return = array();
foreach($data as $key => $value)
$return[] = $key . '="' . $value . '"';
return implode(',', $return);
}
public static function generateNonce() {
$str = '';
mt_srand((double) microtime()*10000000);
for($i=0; $i<32; $i++)
$str .= chr(mt_rand(0, 255));
return $str;
}
public static function encryptPassword($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)));
}
public static function hmacMD5($key, $data) {
if(strlen($key) > 64) $key = pack('H32', md5($key));
if(strlen($key) < 64) $key = str_pad($key, 64, chr(0));
$k_ipad = substr($key, 0, 64) ^ str_repeat(chr(0x36), 64);
$k_opad = substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64);
$inner = pack('H32', md5($k_ipad . $data));
$digest = md5($k_opad . $inner);
return $digest;
}
public static function pbkdf2($data, $secret, $iteration, $dkLen=32, $algo='sha1') {
$hLen = strlen(hash($algo, null, true));
$l = ceil($dkLen/$hLen);
$t = null;
for($i=1; $i<=$l; $i++) {
$f = $u = hash_hmac($algo, $s.pack('N', $i), $p, true);
for($j=1; $j<$c; $j++)
$f ^= ($u = hash_hmac($algo, $u, $p, true));
$t .= $f;
}
return substr($t, 0, $dk_len);
}
public static function getBareJid($jid) {
list($user,$domain,$resource) = self::splitJid($jid);
return ($user ? $user."@" : "").$domain;
}
public static function splitJid($jid) {
preg_match("/(?:([^\@]+)\@)?([^\/]+)(?:\/(.*))?$/",$jid,$matches);
return array($matches[1],$matches[2],@$matches[3]);
}
/*
* xmlentities method for PHP supporting
* 1) Rserved characters in HTML
* 2) ISO 8859-1 Symbols
* 3) ISO 8859-1 Characters
* 4) Math Symbols Supported by HTML
* 5) Greek Letters Supported by HTML
* 6) Other Entities Supported by HTML
*
* Credits:
* --------
* http://www.sourcerally.net/Scripts/39-Convert-HTML-Entities-to-XML-Entities
* http://www.w3schools.com/tags/ref_entities.asp
* http://www.w3schools.com/tags/ref_symbols.asp
*/
public static function xmlentities($str) {
$str = htmlentities($str, ENT_QUOTES, 'UTF-8');
$xml = array('"','&','&','<','>',' ','¡','¢','£','¤','¥','¦','§','¨','©','ª','«','¬','­','®','¯','°','±','²','³','´','µ','¶','·','¸','¹','º','»','¼','½','¾','¿','À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','×','Ø','Ù','Ú','Û','Ü','Ý','Þ','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô','õ','ö','÷','ø','ù','ú','û','ü','ý','þ','ÿ','∀','∂','∃','∅','∇','∈','∉','∋','∏','∑','−','∗','√','∝','∞','∠','∧','∨','∩','∪','∫','∴','∼','≅','≈','≠','≡','≤','≥','⊂','⊃','⊄','⊆','⊇','⊕','⊗','⊥','⋅','Α','Β','Γ','Δ','Ε','Ζ','Η','Θ','Ι','Κ','Λ','Μ','Ν','Ξ','Ο','Π','Ρ','Σ','Τ','Υ','Φ','Χ','Ψ','Ω','α','β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ','ς','σ','τ','υ','φ','χ','ψ','ω','ϑ','ϒ','ϖ','Œ','œ','Š','š','Ÿ','ƒ','ˆ','˜',' ',' ',' ','‌','‍','‎','‏','–','—','‘','’','‚','“','”','„','†','‡','•','…','‰','′','″','‹','›','‾','€','™','←','↑','→','↓','↔','↵','⌈','⌉','⌊','⌋','◊','♠','♣','♥','♦');
$html = array('"','&','&','<','>',' ','¡','¢','£','¤','¥','¦','§','¨','©','ª','«','¬','­','®','¯','°','±','²','³','´','µ','¶','·','¸','¹','º','»','¼','½','¾','¿','À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','×','Ø','Ù','Ú','Û','Ü','Ý','Þ','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô','õ','ö','÷','ø','ù','ú','û','ü','ý','þ','ÿ','∀','∂','∃','∅','∇','∈','∉','∋','∏','∑','−','∗','√','∝','∞','∠','∧','∨','∩','∪','∫','∴','∼','≅','≈','≠','≡','≤','≥','⊂','⊃','⊄','⊆','⊇','⊕','⊗','⊥','⋅','Α','Β','Γ','Δ','Ε','Ζ','Η','Θ','Ι','Κ','Λ','Μ','Ν','Ξ','Ο','Π','Ρ','Σ','Τ','Υ','Φ','Χ','Ψ','Ω','α','β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ','ς','σ','τ','υ','φ','χ','ψ','ω','ϑ','ϒ','ϖ','Œ','œ','Š','š','Ÿ','ƒ','ˆ','˜',' ',' ',' ','‌','‍','‎','‏','–','—','‘','’','‚','“','”','„','†','‡','•','…','‰','′','″','‹','›','‾','€','™','←','↑','→','↓','↔','↵','⌈','⌉','⌊','⌋','◊','♠','♣','♥','♦');
$str = str_replace($html,$xml,$str);
$str = str_ireplace($html,$xml,$str);
return $str;
}
}
?>
|
jaxl/JAXL | 005b6ce73bf8a6188d927bfa1e17f3089447962c | Fix for Call-time pass-by-reference | diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index 33ac7ec..8548f31 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,505 +1,505 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
var $streamBlocking = 1;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
/**
* Instance start time
*/
var $startTime = false;
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
/**
* Maximum rate at which XMPP stanza's can flow out
*/
var $sendRate = false;
/**
* Size of each packet to be read from the socket
*/
var $getPktSize = false;
/**
* Read select timeouts
*/
var $getSelectSecs = 1;
var $getSelectUsecs = 0;
/**
* Packet count and sizes
*/
var $totalRcvdPkt = 0;
var $totalRcvdSize = 0;
var $totalSentPkt = 0;
var $totalSentSize = 0;
/**
* Whether Jaxl core should return a SimpleXMLElement object of parsed string with callback payloads?
*/
var $getSXE = false;
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
$this->clocked = $this->startTime = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
$this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 4096;
$this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : .4;
$this->getSelectSecs = isset($config['getSelectSecs']) ? $config['getSelectSecs'] : 1;
$this->getSXE = isset($config['getSXE']) ? $config['getSXE'] : false;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
$this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
$this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
$this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
$this->executePlugin('jaxl_post_connect', $ret);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = $this->executePlugin('jaxl_get_id', ++$this->lastid);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
* $option = null (read until data is available)
* $option = integer (read for so many seconds)
*/
function getXML() {
// prepare select streams
$streams = array(); $jaxls = $this->instances['xmpp'];
foreach($jaxls as $cnt=>$jaxl) {
if($jaxl->stream) $streams[$cnt] = $jaxl->stream;
else unset($jaxls[$cnt]);
}
// get num changed streams
$read = $streams; $write = null; $except = null; $secs = $this->getSelectSecs; $usecs = $this->getSelectUsecs;
- if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
+ if(false === ($changed = @stream_select($read, $write, $except, $secs, $usecs))) {
$this->log("[[XMPPGet]] \nError while reading packet from stream", 1);
}
else {
if($changed == 0) $now = $this->clocked+$secs;
else $now = time();
foreach($read as $k=>$r) {
// get jaxl instance we are dealing with
$ret = $payload = '';
$key = array_search($r, $streams);
$jaxl = $jaxls[$key];
unset($jaxls[$key]);
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
}
// reload broken buffer
$payload = $jaxl->buffer;
$jaxl->buffer = '';
// read stream
$ret = @fread($jaxl->stream, $jaxl->getPktSize);
$bytes = strlen($ret);
$jaxl->totalRcvdSize += $bytes;
if(trim($ret) != '') $jaxl->log("[[XMPPGet]] ".$jaxl->getPktSize."\n".$ret, 4);
$ret = $jaxl->executePlugin('jaxl_get_xml', $ret);
$payload .= $ret;
// route packets
$jaxl->handler($payload);
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
foreach($jaxls as $jaxl) {
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
$payload = $jaxl->executePlugin('jaxl_get_xml', '');
}
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
}
unset($jaxls, $streams);
return $changed;
}
/**
* Send XMPP XML packet over connected stream
*/
function sendXML($xml='', $force=false) {
$xml = $this->executePlugin('jaxl_send_xml', $xml);
if($this->mode == "cgi") {
$this->executePlugin('jaxl_send_body', $xml);
}
else {
$currSendRate = ($this->totalSentSize/(JAXLUtil::getTime()-$this->lastSendTime))/1000000;
$this->obuffer .= $xml;
if($this->rateLimit
&& !$force
&& $this->lastSendTime
&& ($currSendRate > $this->sendRate)
) {
$this->log("[[XMPPSend]] rateLimit\nBufferSize:".strlen($this->obuffer).", maxSendRate:".$this->sendRate.", currSendRate:".$currSendRate, 5);
return 0;
}
$xml = $this->obuffer;
$this->obuffer = '';
$ret = ($xml == '') ? 0 : $this->_sendXML($xml);
return $ret;
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
if($this->stream && $xml != '') {
$read = array(); $write = array($this->stream); $except = array();
$secs = 0; $usecs = 200000;
- if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
+ if(false === ($changed = @stream_select($read, $write, $except, $secs, $usecs))) {
$this->log("[[XMPPSend]] \nError while trying to send packet", 5);
throw new JAXLException("[[XMPPSend]] \nError while trying to send packet");
return 0;
}
else if($changed > 0) {
$this->lastSendTime = JAXLUtil::getTime();
// this can be resource consuming for large payloads rcvd
$xmls = JAXLUtil::splitXML($xml);
$pktCnt = count($xmls);
$this->totalSentPkt += $pktCnt;
$ret = @fwrite($this->stream, $xml);
$this->totalSentSize += $ret;
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
return $ret;
}
else if($changed === 0) {
$this->obuffer .= $xml;
$this->log("[[XMPPSend]] Not ready for write, obuffer size:".strlen($this->obuffer), 1);
return 0;
}
else {
$this->obuffer .= $xml;
$this->log("[[XMPPSend]] Something horibly wrong here", 1);
return 0;
}
}
else if($xml == '') {
$this->log("[[XMPPSend]] Tried to send an empty stanza, not processing", 1);
return 0;
}
else {
$this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
return 0;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
if($payload == '' && $this->mode == 'cli') return '';
if($payload != '' && $this->mode == 'cgi') $this->log("[[XMPPGet]] \n".$payload, 4);
$payload = $this->executePlugin('jaxl_pre_handler', $payload);
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
$this->totalRcvdPkt += $pktCnt;
$buffer = array();
foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
$this->buffer .= $xml;
break;
}
}
if(substr($xml, 0, 7) == '<stream') $arr = $this->xml->xmlize($xml);
else $arr = JAXLXml::parse($xml, $this->getSXE);
if($arr === false) { $this->buffer .= $xml; continue; }
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
$jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
unset($buffer);
$this->executePlugin('jaxl_post_handler', $payload);
return $payload;
}
}
?>
|
jaxl/JAXL | 1d880a02be9e53b7552130fa3494203ea5e36c84 | Added xep-0077 inband registration | diff --git a/xep/jaxl.0077.php b/xep/jaxl.0077.php
index dd6e3d2..7ad24b0 100644
--- a/xep/jaxl.0077.php
+++ b/xep/jaxl.0077.php
@@ -1,57 +1,74 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0077 : In-Band Registration
*/
class JAXL0077 {
-
+
public static $ns = 'jabber:iq:register';
-
+
public static function init($jaxl) {
+ JAXLXml::addTag('iq', 'registerInstruction', '//iq/query/instructions');
+ JAXLXml::addTag('iq', 'registerUsername', '//iq/query/username');
+ JAXLXml::addTag('iq', 'registerPassword', '//iq/query/password');
$jaxl->features[] = self::$ns;
}
-
+
+ public static function getRegistrationForm($jaxl, $from, $to, $callback) {
+ $payload = '<query xmlns="'.self::$ns.'"/>';
+ return XMPPSend::iq($jaxl, 'get', $payload, $to, $from, $callback);
+ }
+
+ public static function register($jaxl, $from, $to, $callback, $fields) {
+ $payload = '<query xmlns="'.self::$ns.'">';
+ foreach($fields as $field=>$value) {
+ $payload .= '<'.$field.'>'.$value.'</'.$field.'>';
+ }
+ $payload .= '</query>';
+
+ return XMPPSend::iq($jaxl, 'set', $payload, $to, $from, $callback);
+ }
}
?>
|
jaxl/JAXL | e5cac0855b25b4d98e5d6645496b064337fac3c0 | Passing read/write arrays as references (some user facing problem while writing to socket) | diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index 131b5ce..33ac7ec 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,500 +1,505 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
var $streamBlocking = 1;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
/**
* Instance start time
*/
var $startTime = false;
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
/**
* Maximum rate at which XMPP stanza's can flow out
*/
var $sendRate = false;
/**
* Size of each packet to be read from the socket
*/
var $getPktSize = false;
/**
* Read select timeouts
*/
var $getSelectSecs = 1;
var $getSelectUsecs = 0;
/**
* Packet count and sizes
*/
var $totalRcvdPkt = 0;
var $totalRcvdSize = 0;
var $totalSentPkt = 0;
var $totalSentSize = 0;
/**
* Whether Jaxl core should return a SimpleXMLElement object of parsed string with callback payloads?
*/
var $getSXE = false;
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
$this->clocked = $this->startTime = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
$this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 4096;
$this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : .4;
$this->getSelectSecs = isset($config['getSelectSecs']) ? $config['getSelectSecs'] : 1;
$this->getSXE = isset($config['getSXE']) ? $config['getSXE'] : false;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
$this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
$this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
$this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
$this->executePlugin('jaxl_post_connect', $ret);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = $this->executePlugin('jaxl_get_id', ++$this->lastid);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
* $option = null (read until data is available)
* $option = integer (read for so many seconds)
*/
- function getXML() {
+ function getXML() {
// prepare select streams
$streams = array(); $jaxls = $this->instances['xmpp'];
foreach($jaxls as $cnt=>$jaxl) {
if($jaxl->stream) $streams[$cnt] = $jaxl->stream;
else unset($jaxls[$cnt]);
}
// get num changed streams
$read = $streams; $write = null; $except = null; $secs = $this->getSelectSecs; $usecs = $this->getSelectUsecs;
- if(false === ($changed = @stream_select($read, $write, $except, $secs, $usecs))) {
+ if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPGet]] \nError while reading packet from stream", 1);
}
else {
if($changed == 0) $now = $this->clocked+$secs;
else $now = time();
foreach($read as $k=>$r) {
// get jaxl instance we are dealing with
$ret = $payload = '';
$key = array_search($r, $streams);
$jaxl = $jaxls[$key];
unset($jaxls[$key]);
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
}
// reload broken buffer
$payload = $jaxl->buffer;
$jaxl->buffer = '';
// read stream
$ret = @fread($jaxl->stream, $jaxl->getPktSize);
$bytes = strlen($ret);
$jaxl->totalRcvdSize += $bytes;
if(trim($ret) != '') $jaxl->log("[[XMPPGet]] ".$jaxl->getPktSize."\n".$ret, 4);
$ret = $jaxl->executePlugin('jaxl_get_xml', $ret);
$payload .= $ret;
// route packets
$jaxl->handler($payload);
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
foreach($jaxls as $jaxl) {
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
$payload = $jaxl->executePlugin('jaxl_get_xml', '');
}
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
}
unset($jaxls, $streams);
return $changed;
}
/**
* Send XMPP XML packet over connected stream
*/
function sendXML($xml='', $force=false) {
$xml = $this->executePlugin('jaxl_send_xml', $xml);
if($this->mode == "cgi") {
$this->executePlugin('jaxl_send_body', $xml);
}
else {
$currSendRate = ($this->totalSentSize/(JAXLUtil::getTime()-$this->lastSendTime))/1000000;
$this->obuffer .= $xml;
if($this->rateLimit
&& !$force
&& $this->lastSendTime
&& ($currSendRate > $this->sendRate)
) {
$this->log("[[XMPPSend]] rateLimit\nBufferSize:".strlen($this->obuffer).", maxSendRate:".$this->sendRate.", currSendRate:".$currSendRate, 5);
return 0;
}
$xml = $this->obuffer;
$this->obuffer = '';
$ret = ($xml == '') ? 0 : $this->_sendXML($xml);
return $ret;
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
if($this->stream && $xml != '') {
$read = array(); $write = array($this->stream); $except = array();
$secs = 0; $usecs = 200000;
- if(false === ($changed = @stream_select($read, $write, $except, $secs, $usecs))) {
+ if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPSend]] \nError while trying to send packet", 5);
throw new JAXLException("[[XMPPSend]] \nError while trying to send packet");
return 0;
}
else if($changed > 0) {
$this->lastSendTime = JAXLUtil::getTime();
// this can be resource consuming for large payloads rcvd
$xmls = JAXLUtil::splitXML($xml);
$pktCnt = count($xmls);
$this->totalSentPkt += $pktCnt;
$ret = @fwrite($this->stream, $xml);
$this->totalSentSize += $ret;
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
return $ret;
}
- else {
+ else if($changed === 0) {
$this->obuffer .= $xml;
$this->log("[[XMPPSend]] Not ready for write, obuffer size:".strlen($this->obuffer), 1);
return 0;
}
+ else {
+ $this->obuffer .= $xml;
+ $this->log("[[XMPPSend]] Something horibly wrong here", 1);
+ return 0;
+ }
}
else if($xml == '') {
$this->log("[[XMPPSend]] Tried to send an empty stanza, not processing", 1);
return 0;
}
else {
$this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
return 0;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
if($payload == '' && $this->mode == 'cli') return '';
if($payload != '' && $this->mode == 'cgi') $this->log("[[XMPPGet]] \n".$payload, 4);
$payload = $this->executePlugin('jaxl_pre_handler', $payload);
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
$this->totalRcvdPkt += $pktCnt;
$buffer = array();
foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
$this->buffer .= $xml;
break;
}
}
if(substr($xml, 0, 7) == '<stream') $arr = $this->xml->xmlize($xml);
else $arr = JAXLXml::parse($xml, $this->getSXE);
if($arr === false) { $this->buffer .= $xml; continue; }
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
$jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
unset($buffer);
$this->executePlugin('jaxl_post_handler', $payload);
return $payload;
}
}
?>
|
jaxl/JAXL | f1fbfaeaecb0bf4dd3de11016ed7e33393ab1818 | fixing php pass-by-reference warnings for php 5.3 | diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index 20df9db..131b5ce 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,500 +1,500 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
var $streamBlocking = 1;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
/**
* Instance start time
*/
var $startTime = false;
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
/**
* Maximum rate at which XMPP stanza's can flow out
*/
var $sendRate = false;
/**
* Size of each packet to be read from the socket
*/
var $getPktSize = false;
/**
* Read select timeouts
*/
var $getSelectSecs = 1;
var $getSelectUsecs = 0;
/**
* Packet count and sizes
*/
var $totalRcvdPkt = 0;
var $totalRcvdSize = 0;
var $totalSentPkt = 0;
var $totalSentSize = 0;
/**
* Whether Jaxl core should return a SimpleXMLElement object of parsed string with callback payloads?
*/
var $getSXE = false;
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
$this->clocked = $this->startTime = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
$this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 4096;
$this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : .4;
$this->getSelectSecs = isset($config['getSelectSecs']) ? $config['getSelectSecs'] : 1;
$this->getSXE = isset($config['getSXE']) ? $config['getSXE'] : false;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
$this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
$this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
$this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
$this->executePlugin('jaxl_post_connect', $ret);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = $this->executePlugin('jaxl_get_id', ++$this->lastid);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
* $option = null (read until data is available)
* $option = integer (read for so many seconds)
*/
function getXML() {
// prepare select streams
$streams = array(); $jaxls = $this->instances['xmpp'];
foreach($jaxls as $cnt=>$jaxl) {
if($jaxl->stream) $streams[$cnt] = $jaxl->stream;
else unset($jaxls[$cnt]);
}
// get num changed streams
$read = $streams; $write = null; $except = null; $secs = $this->getSelectSecs; $usecs = $this->getSelectUsecs;
- if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
+ if(false === ($changed = @stream_select($read, $write, $except, $secs, $usecs))) {
$this->log("[[XMPPGet]] \nError while reading packet from stream", 1);
}
else {
if($changed == 0) $now = $this->clocked+$secs;
else $now = time();
foreach($read as $k=>$r) {
// get jaxl instance we are dealing with
$ret = $payload = '';
$key = array_search($r, $streams);
$jaxl = $jaxls[$key];
unset($jaxls[$key]);
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
}
// reload broken buffer
$payload = $jaxl->buffer;
$jaxl->buffer = '';
// read stream
$ret = @fread($jaxl->stream, $jaxl->getPktSize);
$bytes = strlen($ret);
$jaxl->totalRcvdSize += $bytes;
if(trim($ret) != '') $jaxl->log("[[XMPPGet]] ".$jaxl->getPktSize."\n".$ret, 4);
$ret = $jaxl->executePlugin('jaxl_get_xml', $ret);
$payload .= $ret;
// route packets
$jaxl->handler($payload);
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
foreach($jaxls as $jaxl) {
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
$payload = $jaxl->executePlugin('jaxl_get_xml', '');
}
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
}
unset($jaxls, $streams);
return $changed;
}
/**
* Send XMPP XML packet over connected stream
*/
function sendXML($xml='', $force=false) {
$xml = $this->executePlugin('jaxl_send_xml', $xml);
if($this->mode == "cgi") {
$this->executePlugin('jaxl_send_body', $xml);
}
else {
$currSendRate = ($this->totalSentSize/(JAXLUtil::getTime()-$this->lastSendTime))/1000000;
$this->obuffer .= $xml;
if($this->rateLimit
&& !$force
&& $this->lastSendTime
&& ($currSendRate > $this->sendRate)
) {
$this->log("[[XMPPSend]] rateLimit\nBufferSize:".strlen($this->obuffer).", maxSendRate:".$this->sendRate.", currSendRate:".$currSendRate, 5);
return 0;
}
$xml = $this->obuffer;
$this->obuffer = '';
$ret = ($xml == '') ? 0 : $this->_sendXML($xml);
return $ret;
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
if($this->stream && $xml != '') {
$read = array(); $write = array($this->stream); $except = array();
$secs = 0; $usecs = 200000;
- if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
+ if(false === ($changed = @stream_select($read, $write, $except, $secs, $usecs))) {
$this->log("[[XMPPSend]] \nError while trying to send packet", 5);
throw new JAXLException("[[XMPPSend]] \nError while trying to send packet");
return 0;
}
else if($changed > 0) {
$this->lastSendTime = JAXLUtil::getTime();
// this can be resource consuming for large payloads rcvd
$xmls = JAXLUtil::splitXML($xml);
$pktCnt = count($xmls);
$this->totalSentPkt += $pktCnt;
$ret = @fwrite($this->stream, $xml);
$this->totalSentSize += $ret;
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
return $ret;
}
else {
$this->obuffer .= $xml;
$this->log("[[XMPPSend]] Not ready for write, obuffer size:".strlen($this->obuffer), 1);
return 0;
}
}
else if($xml == '') {
$this->log("[[XMPPSend]] Tried to send an empty stanza, not processing", 1);
return 0;
}
else {
$this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
return 0;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
if($payload == '' && $this->mode == 'cli') return '';
if($payload != '' && $this->mode == 'cgi') $this->log("[[XMPPGet]] \n".$payload, 4);
$payload = $this->executePlugin('jaxl_pre_handler', $payload);
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
$this->totalRcvdPkt += $pktCnt;
$buffer = array();
foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
$this->buffer .= $xml;
break;
}
}
if(substr($xml, 0, 7) == '<stream') $arr = $this->xml->xmlize($xml);
else $arr = JAXLXml::parse($xml, $this->getSXE);
if($arr === false) { $this->buffer .= $xml; continue; }
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
$jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
unset($buffer);
$this->executePlugin('jaxl_post_handler', $payload);
return $payload;
}
}
?>
|
jaxl/JAXL | 80d43338f801cb201b10770e561607d3c3e7a07c | Improved httpd class and related changed in core jaxl class. Also fixed a few typos inside core classes | diff --git a/core/jaxl.class.php b/core/jaxl.class.php
index 9c119ae..3234204 100644
--- a/core/jaxl.class.php
+++ b/core/jaxl.class.php
@@ -129,788 +129,774 @@
/**
* Client name of the connected Jaxl instance
*/
const name = 'Jaxl :: Jabber XMPP Client Library';
/**
* Custom config passed to Jaxl constructor
*
* @var array
*/
var $config = array();
/**
* Username of connecting Jaxl instance
*
* @var string
*/
var $user = false;
/**
* Password of connecting Jaxl instance
*
* @var string
*/
var $pass = false;
/**
* Hostname for the connecting Jaxl instance
*
* @var string
*/
var $host = 'localhost';
/**
* Port for the connecting Jaxl instance
*
* @var integer
*/
var $port = 5222;
/**
* Full JID of the connected Jaxl instance
*
* @var string
*/
var $jid = false;
/**
* Bare JID of the connected Jaxl instance
*
* @var string
*/
var $bareJid = false;
/**
* Domain for the connecting Jaxl instance
*
* @var string
*/
var $domain = 'localhost';
/**
* Resource for the connecting Jaxl instance
*
* @var string
*/
var $resource = false;
/**
* Local cache of roster list and related info maintained by Jaxl instance
*/
var $roster = array();
/**
* Jaxl will track presence stanza's and update local $roster cache
*/
var $trackPresence = true;
/**
* Configure Jaxl instance to auto-accept subscription requests
*/
var $autoSubscribe = false;
/**
* Log Level of the connected Jaxl instance
*
* @var integer
*/
var $logLevel = 1;
/**
* Enable/Disable automatic log rotation for this Jaxl instance
*
* @var bool|integer
*/
var $logRotate = false;
/**
* Absolute path of log file for this Jaxl instance
*/
var $logPath = '/var/log/jaxl.log';
/**
* Absolute path of pid file for this Jaxl instance
*/
var $pidPath = '/var/run/jaxl.pid';
/**
* Enable/Disable shutdown callback on SIGH terms
*
* @var bool
*/
var $sigh = true;
/**
* Process Id of the connected Jaxl instance
*
* @var bool|integer
*/
var $pid = false;
/**
* Mode of the connected Jaxl instance (cgi or cli)
*
* @var bool|string
*/
var $mode = false;
/**
* Jabber auth mechanism performed by this Jaxl instance
*
* @var false|string
*/
var $authType = false;
/**
* Jaxl instance dumps usage statistics periodically. Disabled if set to "false"
*
* @var bool|integer
*/
var $dumpStat = 300;
/**
* List of XMPP feature supported by this Jaxl instance
*
* @var array
*/
var $features = array();
/**
* XMPP entity category for the connected Jaxl instance
*
* @var string
*/
var $category = 'client';
/**
* XMPP entity type for the connected Jaxl instance
*
* @var string
*/
var $type = 'bot';
/**
* Default language of the connected Jaxl instance
*/
var $lang = 'en';
/**
* Location to system temporary folder
*/
var $tmpPath = null;
/**
* IP address of the host Jaxl instance is running upon.
* To be used by STUN client implementations.
*/
var $ip = null;
/**
* PHP OpenSSL module info
*/
var $openSSL = false;
var $instances = false;
/**
* @return string $name Returns name of this Jaxl client
*/
function getName() {
return JAXL::name;
}
/**
* @return float $version Returns version of this Jaxl client
*/
function getVersion() {
return JAXL::version;
}
/**
* Discover items
*/
function discoItems($jid, $callback, $node=false) {
$this->JAXL0030('discoItems', $jid, $this->jid, $callback, $node);
}
/**
* Discover info
*/
function discoInfo($jid, $callback, $node=false) {
$this->JAXL0030('discoInfo', $jid, $this->jid, $callback, $node);
}
/**
* Shutdown Jaxl instance cleanly
*
* shutdown method is auto invoked when Jaxl instance receives a SIGH term.
* Before cleanly shutting down this method callbacks registered using <b>jaxl_pre_shutdown</b> hook.
*
* @param mixed $signal This is passed as paramater to callbacks registered using <b>jaxl_pre_shutdown</b> hook
*/
function shutdown($signal=false) {
$this->log("[[JAXL]] Shutting down ...");
$this->executePlugin('jaxl_pre_shutdown', $signal);
if($this->stream) $this->endStream();
$this->stream = false;
}
/**
* Perform authentication for connecting Jaxl instance
*
* @param string $type Authentication mechanism to proceed with. Supported auth types are:
* - DIGEST-MD5
* - PLAIN
* - X-FACEBOOK-PLATFORM
* - ANONYMOUS
*/
function auth($type) {
$this->authType = $type;
return XMPPSend::startAuth($this);
}
/**
* Set status of the connected Jaxl instance
*
* @param bool|string $status
* @param bool|string $show
* @param bool|integer $priority
* @param bool $caps
*/
function setStatus($status=false, $show=false, $priority=false, $caps=false, $vcard=false) {
$child = array();
$child['status'] = ($status === false ? 'Online using Jaxl library http://code.google.com/p/jaxl' : $status);
$child['show'] = ($show === false ? 'chat' : $show);
$child['priority'] = ($priority === false ? 1 : $priority);
if($caps) $child['payload'] = $this->JAXL0115('getCaps', $this->features);
if($vcard) $child['payload'] .= $this->JAXL0153('getUpdateData', false);
return XMPPSend::presence($this, false, false, $child, false);
}
/**
* Send authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send authorization request
*/
function subscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribe');
}
/**
* Accept authorization request from $toJid
*
* @param string $toJid JID who's authorization request Jaxl instance wants to accept
*/
function subscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribed');
}
/**
* Send cancel authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send cancel authorization request
*/
function unsubscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribe');
}
/**
* Accept cancel authorization request from $toJid
*
* @param string $toJid JID who's cancel authorization request Jaxl instance wants to accept
*/
function unsubscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribed');
}
/**
* Retrieve connected Jaxl instance roster list from the server
*
* @param mixed $callback Method to be callback'd when roster list is received from the server
*/
function getRosterList($callback=false) {
$payload = '<query xmlns="jabber:iq:roster"/>';
if($callback === false) $callback = array($this, '_handleRosterList');
return XMPPSend::iq($this, "get", $payload, false, $this->jid, $callback);
}
/**
* Add a new jabber account in connected Jaxl instance roster list
*
* @param string $jid JID to be added in the roster list
* @param string $group Group name
* @param bool|string $name Name of JID to be added
*/
function addRoster($jid, $group, $name=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Update subscription of a jabber account in roster list
*
* @param string $jid JID to be updated inside roster list
* @param string $group Updated group name
* @param bool|string $subscription Updated subscription type
*/
function updateRoster($jid, $group, $name=false, $subscription=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
if($subscription) $payload .= ' subscription="'.$subscription.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Delete a jabber account from roster list
*
* @param string $jid JID to be removed from the roster list
*/
function deleteRoster($jid) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'" subscription="remove">';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Send an XMPP message
*
* @param string $to JID to whom message is sent
* @param string $message Message to be sent
* @param string $from (Optional) JID from whom this message should be sent
* @param string $type (Optional) Type of message stanza to be delivered
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessage($to, $message, $from=false, $type='chat', $id=false) {
$child = array();
$child['body'] = $message;
return XMPPSend::message($this, $to, $from, $child, $type, $id);
}
/**
* Send multiple XMPP messages in one go
*
* @param array $to array of JID's to whom this presence stanza should be send
* @param array $from (Optional) array of JID from whom this presence stanza should originate
* @param array $child (Optional) array of arrays specifying child objects of the stanza
* @param array $type (Optional) array of type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessages($to, $from=false, $child=false, $type='chat', $id=false) {
return XMPPSend::message($this, $to, $from, $child, $type);
}
/**
* Send an XMPP presence stanza
*
* @param string $to (Optional) JID to whom this presence stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param array $child (Optional) array specifying child objects of the stanza
* @param string $type (Optional) Type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendPresence($to=false, $from=false, $child=false, $type=false, $id=false) {
return XMPPSend::presence($this, $to, $from, $child, $type, $id);
}
/**
* Send an XMPP iq stanza
*
* @param string $type Type of iq stanza to send
* @param string $payload (Optional) XML string to be transmitted
* @param string $to (Optional) JID to whom this iq stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param string|array $callback (Optional) Callback method which will handle "result" type stanza rcved
* @param integer $id (Optional) Add an id attribute to transmitted stanza (auto-generated if not provided)
*/
function sendIQ($type, $payload=false, $to=false, $from=false, $callback=false, $id=false) {
return XMPPSend::iq($this, $type, $payload, $to, $from, $callback, $id);
}
/**
* Logs library core and application debug data into the log file
*
* @param string $log Datum to be logged
* @param integer $level Log level for passed datum
*/
function log($log, $level=1) {
JAXLog::log($log, $level, $this);
}
/**
* Instead of using jaxl_require method applications can use $jaxl->requires to include XEP's in PHP environment
*
* @param string $class Class name of the XEP to be included e.g. JAXL0045 for including XEP-0045 a.k.a. Multi-user chat
*/
function requires($class) {
jaxl_require($class, $this);
}
/**
* Use this method instead of JAXLPlugin::add to register a callback for connected instance only
*/
function addPlugin($hook, $callback, $priority=10) {
JAXLPlugin::add($hook, $callback, $priority, $this->uid);
}
/**
* Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
*/
function removePlugin($hook, $callback, $priority=10) {
JAXLPlugin::remove($hook, $callback, $priority, $this->uid);
}
/**
* Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
*/
function executePlugin($hook, $payload) {
return JAXLPlugin::execute($hook, $payload, $this);
}
/**
* Add another jaxl instance in a running core
*/
function addCore($jaxl) {
$jaxl->addPlugin('jaxl_post_connect', array($jaxl, 'startStream'));
$jaxl->connect();
$this->instances['xmpp'][] = $jaxl;
}
/**
* Starts Jaxl Core
*
* This method should be called after Jaxl initialization and hook registration inside your application code
* Optionally, you can pass 'jaxl_post_connect' and 'jaxl_get_auth_mech' response type directly to this method
* In that case application code SHOULD NOT register callbacks to above mentioned hooks
*
* @param string $arg[0] Optionally application code can pre-choose what Jaxl core should do after establishing socket connection.
* Following are the valid options:
* a) startStream
* b) startComponent
* c) startBosh
*/
function startCore(/* $mode, $param1, $param2, ... */) {
$argv = func_get_args();
$mode = $argv[0];
if($mode) {
switch($mode) {
case 'stream':
$this->addPlugin('jaxl_post_connect', array($this, 'startStream'));
break;
case 'component':
$this->addPlugin('jaxl_post_connect', array($this, 'startComponent'));
break;
case 'bosh':
$this->startBosh();
break;
default:
break;
}
}
if($this->mode == 'cli') {
try {
if($this->connect()) {
while($this->stream) {
$this->getXML();
}
}
}
catch(JAXLException $e) {
die($e->getMessage());
}
/* Exit Jaxl after end of loop */
exit;
}
}
- /**
- * Starts a socket server at 127.0.0.1:port
- *
- * startHTTPd converts Jaxl instance into a Jaxl socket server (may or may not be a HTTP server)
- * Same Jaxl socket server instance <b>SHOULD NOT</b> be used for XMPP communications.
- * Instead separate "new Jaxl();" instances should be created for such XMPP communications.
- */
- function startHTTPd($port, $maxq) {
- JAXLHTTPd::start(array(
- 'port' => $port,
- 'maxq' => $maxq
- ));
- }
-
/**
* Start instance in bosh mode
*/
function startBosh() {
$this->JAXL0206('startStream');
}
/**
* Start instance in component mode
*/
function startComponent($payload, $jaxl) {
$this->JAXL0114('startStream', $payload);
}
/**
* Jaxl core constructor
*
* Jaxl instance configures itself using the constants inside your application jaxl.ini.
* However, passed array of configuration options overrides the value inside jaxl.ini.
* If no configuration are found or passed for a particular value,
* Jaxl falls back to default config options.
*
* @param $config Array of configuration options
* @todo Use DNS SRV lookup to set $jaxl->host from provided domain info
*/
function __construct($config=array()) {
global $jaxl_instance_cnt;
parent::__construct($config);
$this->uid = ++$jaxl_instance_cnt;
$this->ip = gethostbyname(php_uname('n'));
$this->config = $config;
$this->pid = getmypid();
/* Mandatory params to be supplied either by jaxl.ini constants or constructor $config array */
$this->user = $this->getConfigByPriority(@$config['user'], "JAXL_USER_NAME", $this->user);
$this->pass = $this->getConfigByPriority(@$config['pass'], "JAXL_USER_PASS", $this->pass);
$this->domain = $this->getConfigByPriority(@$config['domain'], "JAXL_HOST_DOMAIN", $this->domain);
$this->bareJid = $this->user."@".$this->domain;
/* Optional params if not configured using jaxl.ini or $config take default values */
$this->host = $this->getConfigByPriority(@$config['host'], "JAXL_HOST_NAME", $this->domain);
$this->port = $this->getConfigByPriority(@$config['port'], "JAXL_HOST_PORT", $this->port);
$this->resource = $this->getConfigByPriority(@$config['resource'], "JAXL_USER_RESC", "jaxl.".$this->uid.".".$this->clocked);
$this->logLevel = $this->getConfigByPriority(@$config['logLevel'], "JAXL_LOG_LEVEL", $this->logLevel);
$this->logRotate = $this->getConfigByPriority(@$config['logRotate'], "JAXL_LOG_ROTATE", $this->logRotate);
$this->logPath = $this->getConfigByPriority(@$config['logPath'], "JAXL_LOG_PATH", $this->logPath);
if(!file_exists($this->logPath) && !touch($this->logPath)) throw new JAXLException("Log file ".$this->logPath." doesn't exists");
$this->pidPath = $this->getConfigByPriority(@$config['pidPath'], "JAXL_PID_PATH", $this->pidPath);
$this->mode = $this->getConfigByPriority(@$config['mode'], "JAXL_MODE", (PHP_SAPI == "cli") ? PHP_SAPI : "cgi");
if($this->mode == "cli" && !file_exists($this->pidPath) && !touch($this->pidPath)) throw new JAXLException("Pid file ".$this->pidPath." doesn't exists");
/* Resolve temporary folder path */
if(function_exists('sys_get_temp_dir')) $this->tmpPath = sys_get_temp_dir();
$this->tmpPath = $this->getConfigByPriority(@$config['tmpPath'], "JAXL_TMP_PATH", $this->tmpPath);
if($this->tmpPath && !file_exists($this->tmpPath)) throw new JAXLException("Tmp directory ".$this->tmpPath." doesn't exists");
/* Handle pre-choosen auth type mechanism */
$this->authType = $this->getConfigByPriority(@$config['authType'], "JAXL_AUTH_TYPE", $this->authType);
if($this->authType) $this->addPlugin('jaxl_get_auth_mech', array($this, 'doAuth'));
/* Presence handling */
$this->trackPresence = isset($config['trackPresence']) ? $config['trackPresence'] : true;
$this->autoSubscribe = isset($config['autoSubscribe']) ? $config['autoSubscribe'] : false;
$this->addPlugin('jaxl_get_presence', array($this, '_handlePresence'), 0);
/* Optional params which can be configured only via constructor $config */
$this->sigh = isset($config['sigh']) ? $config['sigh'] : true;
$this->dumpStat = isset($config['dumpStat']) ? $config['dumpStat'] : 300;
/* Configure instance for platforms */
$this->configure($config);
/* Initialize xml to array class (will deprecate in future) */
$this->xml = new XML();
/* Initialize JAXLCron and register core jobs */
JAXLCron::init($this);
if($this->dumpStat) JAXLCron::add(array($this, 'dumpStat'), $this->dumpStat);
if($this->logRotate) JAXLCron::add(array('JAXLog', 'logRotate'), $this->logRotate);
/* include recommended XEP's for every XMPP entity */
$this->requires(array(
'JAXL0030', // service discovery
'JAXL0128' // entity capabilities
));
/* initialize multi-core instance holder */
- if($jaxl_instance_cnt == 1) $this->instances = array('xmpp'=>array(),'http'=>array());
+ if($jaxl_instance_cnt == 1) $this->instances = array('xmpp'=>array());
$this->instances['xmpp'][] = $this;
}
/**
* Return Jaxl instance config param depending upon user choice and default values
*/
function getConfigByPriority($config, $constant, $default) {
return ($config === null) ? (@constant($constant) === null ? $default : constant($constant)) : $config;
}
/**
* Configures Jaxl instance to run across various platforms (*nix/windows)
*
* Configure method tunes connecting Jaxl instance for
* OS compatibility, SSL support and dependencies over PHP methods
*/
protected function configure() {
// register shutdown function
if(!JAXLUtil::isWin() && JAXLUtil::pcntlEnabled() && $this->sigh) {
pcntl_signal(SIGTERM, array($this, "shutdown"));
pcntl_signal(SIGINT, array($this, "shutdown"));
$this->log("[[JAXL]] Registering callbacks for CTRL+C and kill.", 4);
}
else {
$this->log("[[JAXL]] No callbacks registered for CTRL+C and kill.", 4);
}
// check Jaxl dependency on PHP extension in cli mode
if($this->mode == "cli") {
if(($this->openSSL = JAXLUtil::sslEnabled()))
$this->log("[[JAXL]] OpenSSL extension is loaded.", 4);
else
$this->log("[[JAXL]] OpenSSL extension not loaded.", 4);
if(!function_exists('fsockopen'))
throw new JAXLException("[[JAXL]] Requires fsockopen method");
if(@is_writable($this->pidPath))
file_put_contents($this->pidPath, $this->pid);
}
// check Jaxl dependency on PHP extension in cgi mode
if($this->mode == "cgi") {
if(!function_exists('curl_init'))
throw new JAXLException("[[JAXL]] Requires CURL PHP extension");
if(!function_exists('json_encode'))
throw new JAXLException("[[JAXL]] Requires JSON PHP extension.");
}
}
/**
* Dumps Jaxl instance usage statistics
*
* Jaxl instance periodically calls this methods every JAXL::$dumpStat seconds.
*/
function dumpStat() {
$stat = "[[JAXL]] Memory:".round(memory_get_usage()/pow(1024,2), 2)."Mb";
if(function_exists('memory_get_peak_usage')) $stat .= ", PeakMemory:".round(memory_get_peak_usage()/pow(1024,2), 2)."Mb";
$stat .= ", obuffer: ".strlen($this->obuffer);
$stat .= ", buffer: ".strlen($this->buffer);
$stat .= ", RcvdRate: ".$this->totalRcvdSize/$this->clock."Kb";
$stat .= ", SentRate: ".$this->totalSentSize/$this->clock."Kb";
$this->log($stat, 1);
}
/**
* Magic method for calling XEP's included by the JAXL instance
*
* Application <b>should never</b> call an XEP method directly using <code>JAXL0045::joinRoom()</code>
* instead use <code>$jaxl->JAXL0045('joinRoom', $param1, ..)</code> to call methods provided by included XEP's
*
* @param string $xep XMPP extension (XEP) class name e.g. JAXL0045 for XEP-0045 a.k.a. Multi-User chat extension
* @param array $param Array of parameters where $param[0]='methodName' is the method called inside JAXL0045 class
*
* @return mixed $return Return value of called XEP method
*/
function __call($xep, $param) {
$method = array_shift($param);
array_unshift($param, $this);
if(substr($xep, 0, 4) == 'JAXL') {
$xep = substr($xep, 4, 4);
if(is_numeric($xep)
&& class_exists('JAXL'.$xep)
) {
$this->log("[[JAXL]] Calling JAXL$xep method ".$method, 5);
return call_user_func_array(array('JAXL'.$xep, $method), $param);
}
else { $this->log("[[JAXL]] JAXL$xep Doesn't exists in the environment"); }
}
else {
$this->log("[[JAXL]] Call to an unidentified XEP");
}
}
/**
* Perform pre-choosen auth type for the Jaxl instance
*/
function doAuth($mechanism) {
return XMPPSend::startAuth($this);
}
/**
* Adds a node (if doesn't exists) for $jid inside local $roster cache
*/
function _addRosterNode($jid, $inRoster=true) {
if(!isset($this->roster[$jid]))
$this->roster[$jid] = array(
'groups'=>array(),
'name'=>'',
'subscription'=>'',
'presence'=>array(),
'inRoster'=>$inRoster
);
return;
}
/**
* Core method that accepts retrieved roster list and manage local cache
*/
function _handleRosterList($payload, $jaxl) {
if(@is_array($payload['queryItemJid'])) {
foreach($payload['queryItemJid'] as $key=>$jid) {
$this->_addRosterNode($jid);
$this->roster[$jid]['groups'] = @$payload['queryItemGrp'][$key];
$this->roster[$jid]['name'] = @$payload['queryItemName'][$key];
$this->roster[$jid]['subscription'] = @$payload['queryItemSub'][$key];
}
}
else {
$jid = @$payload['queryItemJid'];
$this->_addRosterNode($jid);
$this->roster[$jid]['groups'] = @$payload['queryItemGrp'];
$this->roster[$jid]['name'] = @$payload['queryItemName'];
$this->roster[$jid]['subscription'] = @$payload['queryItemSub'];
}
$this->executePlugin('jaxl_post_roster_update', $payload);
return $payload;
}
/**
* Tracks all incoming presence stanza's
*/
function _handlePresence($payloads, $jaxl) {
foreach($payloads as $payload) {
if($this->trackPresence) {
// update local $roster cache
$jid = JAXLUtil::getBareJid($payload['from']);
$this->_addRosterNode($jid, false);
if(!isset($this->roster[$jid]['presence'][$payload['from']])) $this->roster[$jid]['presence'][$payload['from']] = array();
$this->roster[$jid]['presence'][$payload['from']]['type'] = $payload['type'] == '' ? 'available' : $payload['type'];
$this->roster[$jid]['presence'][$payload['from']]['status'] = $payload['status'];
$this->roster[$jid]['presence'][$payload['from']]['show'] = $payload['show'];
$this->roster[$jid]['presence'][$payload['from']]['priority'] = $payload['priority'];
}
if($payload['type'] == 'subscribe'
&& $this->autoSubscribe
) {
$this->subscribed($payload['from']);
$this->subscribe($payload['from']);
$this->executePlugin('jaxl_post_subscription_request', $payload);
}
else if($payload['type'] == 'subscribed') {
$this->executePlugin('jaxl_post_subscription_accept', $payload);
}
}
return $payloads;
}
}
?>
diff --git a/core/jaxl.httpd.php b/core/jaxl.httpd.php
index b99b3af..8f837f4 100644
--- a/core/jaxl.httpd.php
+++ b/core/jaxl.httpd.php
@@ -1,253 +1,255 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// JAXLHTTPd server meta
define('JAXL_HTTPd_SERVER_NAME', 'JAXLHTTPd');
define('JAXL_HTTPd_SERVER_VERSION', '0.0.1');
// JAXLHTTPd settings
define('JAXL_HTTPd_MAXQ', 20);
define('JAXL_HTTPd_SELECT_TIMEOUT', 1);
// Jaxl core dependency
jaxl_require(array(
'JAXLPlugin'
));
// Simple socket select server
class JAXLHTTPd {
// HTTP request/response code list
- public static $headers = array(
+ var $headers = array(
100 => "100 Continue",
200 => "200 OK",
201 => "201 Created",
204 => "204 No Content",
206 => "206 Partial Content",
300 => "300 Multiple Choices",
301 => "301 Moved Permanently",
302 => "302 Found",
303 => "303 See Other",
304 => "304 Not Modified",
307 => "307 Temporary Redirect",
400 => "400 Bad Request",
401 => "401 Unauthorized",
403 => "403 Forbidden",
404 => "404 Not Found",
405 => "405 Method Not Allowed",
406 => "406 Not Acceptable",
408 => "408 Request Timeout",
410 => "410 Gone",
413 => "413 Request Entity Too Large",
414 => "414 Request URI Too Long",
415 => "415 Unsupported Media Type",
416 => "416 Requested Range Not Satisfiable",
417 => "417 Expectation Failed",
500 => "500 Internal Server Error",
501 => "501 Method Not Implemented",
503 => "503 Service Unavailable",
506 => "506 Variant Also Negotiates"
);
// server instance
- private static $httpd = null;
+ var $httpd = null;
// server settings
- private static $settings = null;
+ var $settings = null;
// connected socket id
- private static $id = null;
+ var $id = null;
// list of connected clients
- private static $clients = null;
+ var $clients = null;
- public static function shutdown() {
- JAXLPlugin::execute('jaxl_httpd_pre_shutdown');
- exit;
- }
-
- private static function reset($options) {
- self::$settings = array(
- 'port' => isset($options['port']) ? $options['port'] : 5290,
- 'maxq' => isset($options['maxq']) ? $options['maxq'] : 20,
- 'pid' => getmypid(),
- 'since' => time()
- );
- }
-
- public static function start($options) {
- self::reset($options);
+ function __construct($options) {
+ $this->reset($options);
pcntl_signal(SIGTERM, array("JAXLHTTPd", "shutdown"));
pcntl_signal(SIGINT, array("JAXLHTTPd", "shutdown"));
$options = getopt("p:b:");
foreach($options as $opt=>$val) {
switch($opt) {
case 'p':
- self::$settings['port'] = $val;
+ $this->settings['port'] = $val;
break;
case 'b':
- self::$settings['maxq'] = $val;
+ $this->settings['maxq'] = $val;
default:
break;
}
}
- self::$httpd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
- socket_set_option(self::$httpd, SOL_SOCKET, SO_REUSEADDR, 1);
- socket_bind(self::$httpd, 0, self::$settings['port']);
- socket_listen(self::$httpd, self::$settings['maxq']);
+ $this->httpd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
+ socket_set_option($this->httpd, SOL_SOCKET, SO_REUSEADDR, 1);
+ socket_bind($this->httpd, 0, $this->settings['port']);
+ socket_listen($this->httpd, $this->settings['maxq']);
- self::$id = self::getResourceID(self::$httpd);
- self::$clients = array("0#".self::$settings['port']=>self::$httpd);
- echo "JAXLHTTPd listening on port ".self::$settings['port'].PHP_EOL;
-
+ $this->id = $this->getResourceID($this->httpd);
+ $this->clients = array("0#".$this->settings['port']=>$this->httpd);
+ echo "JAXLHTTPd listening on port ".$this->settings['port'].PHP_EOL;
+ }
+
+ function read() {
while(true) {
- $read = self::$clients;
+ $read = $this->clients;
$ns = @socket_select($read, $write=null, $except=null, JAXL_HTTPd_SELECT_TIMEOUT);
if($ns) foreach($read as $read_socket) {
- $accept_id = self::getResourceID($read_socket);
+ $accept_id = $this->getResourceID($read_socket);
- if(self::$id == $accept_id) {
+ if($this->id == $accept_id) {
$sock = socket_accept($read_socket);
socket_getpeername($sock, $ip, $port);
- self::$clients[$ip."#".$port] = $sock;
+ $this->clients[$ip."#".$port] = $sock;
//echo "Accepted new connection from ".$ip."#".$port.PHP_EOL;
continue;
}
else {
socket_getpeername($read_socket, $ip, $port);
$data = trim(socket_read($read_socket, 1024));
if($data == "") {
- self::close($ip, $port);
+ $this->close($ip, $port);
}
else {
//echo "Recv data from ".$ip."#".$port.PHP_EOL;
- $request = self::parseRequest($data, array(
+ $request = $this->parseRequest($data, array(
'ip' => $ip,
'port' => $port
));
if($request['meta']['protocol'] == 'HTTP') {
JAXLPlugin::execute('jaxl_httpd_get_http_request', $request);
}
else {
JAXLPlugin::execute('jaxl_httpd_get_sock_request', $request);
}
}
}
}
JAXLPlugin::execute('jaxl_httpd_post_read');
}
}
- public static function send($response) {
- $raw = self::prepareResponse($response['meta'], $response['header']);
- @socket_write(self::$clients[$response['client']['ip']."#".$response['client']['port']], $raw);
+ function send($response) {
+ $raw = $this->prepareResponse($response['meta'], $response['header']);
+ @socket_write($this->clients[$response['client']['ip']."#".$response['client']['port']], $raw);
}
- public static function close($ip, $port) {
- @socket_close(self::$clients[$ip."#".$port]);
- unset(self::$clients[$ip."#".$port]);
+ function close($ip, $port) {
+ @socket_close($this->clients[$ip."#".$port]);
+ unset($this->clients[$ip."#".$port]);
}
- private static function parseRequest($raw, $client) {
- list($meta, $headers) = self::parseHeader($raw);
+ function parseRequest($raw, $client) {
+ list($meta, $headers) = $this->parseHeader($raw);
$request = array(
'meta' => $meta,
'header'=> $headers,
'client'=> $client
);
return $request;
}
- private static function parseHeader($raw) {
+ function parseHeader($raw) {
$raw = explode("\r\n", $raw);
list($method, $path, $protocol) = explode(" ", array_shift($raw));
list($protocol, $version) = explode("/", $protocol);
$meta = array(
'method'=>trim($method),
'path'=>trim($path),
'protocol'=>trim($protocol),
'version'=>trim($version)
);
$headers = array();
foreach($raw as $header) {
$header = trim($header);
if($header == "") {
break;
}
else if(strpos($header, ":") != false) {
$key = strtoupper(strtok($header, ":"));
$val = trim(strtok(""));
$headers[$key] = $val;
}
}
$meta['body'] = substr(array_pop($raw), 0, $headers['CONTENT-LENGTH']);
return array($meta, $headers);
}
- private static function prepareResponse($meta, $headers) {
+ function prepareResponse($meta, $headers) {
$raw = '';
- $raw .= $meta['protocol']."/".$meta['version']." ".self::$headers[$meta['code']]."\r\n";
+ $raw .= $meta['protocol']."/".$meta['version']." ".$this->headers[$meta['code']]."\r\n";
$raw .= "Server: ".JAXL_HTTPd_SERVER_NAME."/".JAXL_HTTPd_SERVER_VERSION."\r\n";
$raw .= "Date: ".gmdate("D, d M Y H:i:s T")."\r\n";
foreach($headers as $key => $val) $raw .= $key.": ".$val."\r\n";
$raw .= "\r\n";
$raw .= $meta['body'];
return $raw;
}
- private static function getResourceID($socket) {
+ function getResourceID($socket) {
return (int)preg_replace("/Resource id #(\d+)/i", "$1", (string)$socket);
}
+
+ function shutdown() {
+ JAXLPlugin::execute('jaxl_httpd_pre_shutdown');
+ exit;
+ }
+
+ function reset($options) {
+ $this->settings = array(
+ 'port' => isset($options['port']) ? $options['port'] : 5290,
+ 'maxq' => isset($options['maxq']) ? $options['maxq'] : 20,
+ 'pid' => getmypid(),
+ 'since' => time()
+ );
+ }
}
?>
diff --git a/core/jaxl.plugin.php b/core/jaxl.plugin.php
index 1c6ee9d..0538f7a 100644
--- a/core/jaxl.plugin.php
+++ b/core/jaxl.plugin.php
@@ -1,121 +1,122 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl Plugin Framework
*/
class JAXLPlugin {
/**
* Registry of all registered hooks
*/
public static $registry = array();
/**
* Register callback on hook
*
* @param string $hook
* @param string|array $callback A valid callback inside your application code
* @param integer $priority (>0) When more than one callbacks is attached on hook, they are called in priority order or which ever was registered first
* @param integer $uid random id $jaxl->uid of connected Jaxl instance, $uid=0 means callback registered for all connected instances
*/
public static function add($hook, $callback, $priority=10, $uid=0) {
if(!isset(self::$registry[$uid]))
self::$registry[$uid] = array();
if(!isset(self::$registry[$uid][$hook]))
self::$registry[$uid][$hook] = array();
if(!isset(self::$registry[$uid][$hook][$priority]))
self::$registry[$uid][$hook][$priority] = array();
array_push(self::$registry[$uid][$hook][$priority], $callback);
}
/**
* Removes a previously registered callback on hook
*
* @param string $hook
* @param string|array $callback
* @param integer $priority
* @param integer $uid random id $jaxl->uid of connected Jaxl instance, $uid=0 means callback registered for all connected instances
*/
public static function remove($hook, $callback, $priority=10, $uid=0) {
if(($key = array_search($callback, self::$registry[$uid][$hook][$priority])) !== FALSE)
unset(self::$registry[$uid][$hook][$priority][$key]);
if(count(self::$registry[$uid][$hook][$priority]) == 0)
unset(self::$registry[$uid][$hook][$priority]);
if(count(self::$registry[$uid][$hook]) == 0)
unset(self::$registry[$uid][$hook]);
}
/*
* Method calls previously registered callbacks on executing hook
*
* @param string $hook
* @param mixed $payload
* @param object $jaxl
* @param array $filter
*/
public static function execute($hook, $payload=null, $jaxl=false, $filter=false) {
- $uids = array($jaxl->uid, 0);
+ if($jaxl) $uids = array($jaxl->uid, 0);
+ else $uids = array(0);
foreach($uids as $uid) {
if(isset(self::$registry[$uid][$hook]) && count(self::$registry[$uid][$hook]) > 0) {
foreach(self::$registry[$uid][$hook] as $priority) {
foreach($priority as $callback) {
if($filter === false || (is_array($filter) && in_array($callback[0], $filter))) {
- $jaxl->log("[[JAXLPlugin]] Executing hook $hook for uid $uid", 7);
+ if($jaxl) $jaxl->log("[[JAXLPlugin]] Executing hook $hook for uid $uid", 7);
$payload = call_user_func($callback, $payload, $jaxl);
}
}
}
}
}
return $payload;
}
}
?>
diff --git a/xep/jaxl.0163.php b/xep/jaxl.0163.php
index f3099be..762cda3 100644
--- a/xep/jaxl.0163.php
+++ b/xep/jaxl.0163.php
@@ -1,59 +1,59 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0163 : Personal Eventing Protocol
*/
class JAXL0163 {
public static function init($jaxl) {
$jaxl->requires('JAXL0060');
}
- public static publishItem($jaxl, $from, $node, $item) {
+ public static function publishItem($jaxl, $from, $node, $item) {
return JAXL0060::publishItem($jaxl, false, $from, $node, $item);
}
}
?>
diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index 46893d6..20df9db 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,497 +1,500 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
var $streamBlocking = 1;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
/**
* Instance start time
*/
var $startTime = false;
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
/**
* Maximum rate at which XMPP stanza's can flow out
*/
var $sendRate = false;
/**
* Size of each packet to be read from the socket
*/
var $getPktSize = false;
/**
* Read select timeouts
*/
- var $getSelectSecs = 5;
+ var $getSelectSecs = 1;
var $getSelectUsecs = 0;
/**
* Packet count and sizes
*/
var $totalRcvdPkt = 0;
var $totalRcvdSize = 0;
var $totalSentPkt = 0;
var $totalSentSize = 0;
/**
* Whether Jaxl core should return a SimpleXMLElement object of parsed string with callback payloads?
*/
var $getSXE = false;
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
$this->clocked = $this->startTime = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
$this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 4096;
$this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : .4;
- $this->getSelectSecs = isset($config['getSelectSecs']) ? $config['getSelectSecs'] : 5;
+ $this->getSelectSecs = isset($config['getSelectSecs']) ? $config['getSelectSecs'] : 1;
$this->getSXE = isset($config['getSXE']) ? $config['getSXE'] : false;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
$this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
$this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
$this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
$this->executePlugin('jaxl_post_connect', $ret);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = $this->executePlugin('jaxl_get_id', ++$this->lastid);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
* $option = null (read until data is available)
* $option = integer (read for so many seconds)
*/
function getXML() {
// prepare select streams
$streams = array(); $jaxls = $this->instances['xmpp'];
foreach($jaxls as $cnt=>$jaxl) {
if($jaxl->stream) $streams[$cnt] = $jaxl->stream;
else unset($jaxls[$cnt]);
}
// get num changed streams
$read = $streams; $write = null; $except = null; $secs = $this->getSelectSecs; $usecs = $this->getSelectUsecs;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
- $this->log("[[XMPPGet]] \nError while reading packet from stream", 5);
+ $this->log("[[XMPPGet]] \nError while reading packet from stream", 1);
}
else {
- $this->log("[[XMPPGet]] $changed streams ready for read out of total ".sizeof($streams)." streams", 7);
if($changed == 0) $now = $this->clocked+$secs;
else $now = time();
foreach($read as $k=>$r) {
// get jaxl instance we are dealing with
$ret = $payload = '';
$key = array_search($r, $streams);
$jaxl = $jaxls[$key];
unset($jaxls[$key]);
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
}
- // reload pending buffer
+ // reload broken buffer
$payload = $jaxl->buffer;
$jaxl->buffer = '';
// read stream
$ret = @fread($jaxl->stream, $jaxl->getPktSize);
- if(trim($ret) != '') $jaxl->log("[[XMPPGet]] \n".$ret, 4);
- $jaxl->totalRcvdSize = strlen($ret);
+ $bytes = strlen($ret);
+ $jaxl->totalRcvdSize += $bytes;
+ if(trim($ret) != '') $jaxl->log("[[XMPPGet]] ".$jaxl->getPktSize."\n".$ret, 4);
$ret = $jaxl->executePlugin('jaxl_get_xml', $ret);
$payload .= $ret;
// route packets
$jaxl->handler($payload);
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
foreach($jaxls as $jaxl) {
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
$payload = $jaxl->executePlugin('jaxl_get_xml', '');
}
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
}
unset($jaxls, $streams);
return $changed;
}
/**
* Send XMPP XML packet over connected stream
*/
function sendXML($xml='', $force=false) {
$xml = $this->executePlugin('jaxl_send_xml', $xml);
if($this->mode == "cgi") {
$this->executePlugin('jaxl_send_body', $xml);
}
else {
$currSendRate = ($this->totalSentSize/(JAXLUtil::getTime()-$this->lastSendTime))/1000000;
$this->obuffer .= $xml;
if($this->rateLimit
&& !$force
&& $this->lastSendTime
&& ($currSendRate > $this->sendRate)
) {
$this->log("[[XMPPSend]] rateLimit\nBufferSize:".strlen($this->obuffer).", maxSendRate:".$this->sendRate.", currSendRate:".$currSendRate, 5);
return 0;
}
$xml = $this->obuffer;
$this->obuffer = '';
- return ($xml == '') ? 0 : $this->_sendXML($xml);
+ $ret = ($xml == '') ? 0 : $this->_sendXML($xml);
+ return $ret;
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
if($this->stream && $xml != '') {
$read = array(); $write = array($this->stream); $except = array();
- $secs = null; $usecs = null;
+ $secs = 0; $usecs = 200000;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPSend]] \nError while trying to send packet", 5);
throw new JAXLException("[[XMPPSend]] \nError while trying to send packet");
return 0;
}
else if($changed > 0) {
$this->lastSendTime = JAXLUtil::getTime();
+
+ // this can be resource consuming for large payloads rcvd
$xmls = JAXLUtil::splitXML($xml);
$pktCnt = count($xmls);
$this->totalSentPkt += $pktCnt;
$ret = @fwrite($this->stream, $xml);
$this->totalSentSize += $ret;
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
return $ret;
}
else {
- $this->log("[[XMPPSend]] Failed\n".$xml);
- throw new JAXLException("[[XMPPSend]] \nFailed");
+ $this->obuffer .= $xml;
+ $this->log("[[XMPPSend]] Not ready for write, obuffer size:".strlen($this->obuffer), 1);
return 0;
}
}
else if($xml == '') {
$this->log("[[XMPPSend]] Tried to send an empty stanza, not processing", 1);
return 0;
}
else {
$this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
return 0;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
if($payload == '' && $this->mode == 'cli') return '';
if($payload != '' && $this->mode == 'cgi') $this->log("[[XMPPGet]] \n".$payload, 4);
$payload = $this->executePlugin('jaxl_pre_handler', $payload);
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
$this->totalRcvdPkt += $pktCnt;
$buffer = array();
foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
$this->buffer .= $xml;
break;
}
}
if(substr($xml, 0, 7) == '<stream') $arr = $this->xml->xmlize($xml);
else $arr = JAXLXml::parse($xml, $this->getSXE);
if($arr === false) { $this->buffer .= $xml; continue; }
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
$jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
unset($buffer);
$this->executePlugin('jaxl_post_handler', $payload);
return $payload;
}
}
?>
diff --git a/xmpp/xmpp.send.php b/xmpp/xmpp.send.php
index 8c94212..5d9a7da 100644
--- a/xmpp/xmpp.send.php
+++ b/xmpp/xmpp.send.php
@@ -1,206 +1,206 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLUtil',
'JAXLog'
));
/**
* XMPP Send Class
* Provide methods for sending all kind of xmpp stream and stanza's
*/
class XMPPSend {
public static function startStream($jaxl) {
$xml = '<stream:stream xmlns:stream="http://etherx.jabber.org/streams" version="1.0" xmlns="jabber:client" to="'.$jaxl->domain.'" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">';
return $jaxl->sendXML($xml);
}
public static function endStream($jaxl) {
$xml = '</stream:stream>';
return $jaxl->sendXML($xml, true);
}
public static function startTLS($jaxl) {
$xml = '<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>';
return $jaxl->sendXML($xml);
}
public static function startAuth($jaxl) {
$type = $jaxl->authType;
$xml = '<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="'.$type.'">';
switch($type) {
case 'DIGEST-MD5':
break;
case 'PLAIN':
$xml .= base64_encode("\x00".$jaxl->user."\x00".$jaxl->pass);
break;
case 'ANONYMOUS':
break;
case 'X-FACEBOOK-PLATFORM':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
$xml .= base64_encode("n,,n=".$jaxl->user.",r=".base64_encode(JAXLUtil::generateNonce()));
break;
default:
break;
}
$xml .= '</auth>';
$jaxl->log("[[XMPPSend]] Performing Auth type: ".$type);
return $jaxl->sendXML($xml);
}
public static function startSession($jaxl, $callback) {
$payload = '<session xmlns="urn:ietf:params:xml:ns:xmpp-session"/>';
return self::iq($jaxl, "set", $payload, $jaxl->domain, false, $callback);
}
public static function startBind($jaxl, $callback) {
$payload = '<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">';
$payload .= '<resource>'.$jaxl->resource.'</resource>';
$payload .= '</bind>';
return self::iq($jaxl, "set", $payload, false, false, $callback);
}
public static function message($jaxl, $to, $from=false, $child=false, $type='normal', $id=false, $ns='jabber:client') {
$xml = '';
if(is_array($to)) {
foreach($to as $key => $value) {
$xml .= self::prepareMessage($jaxl, $to[$key], $from[$key], $child[$key], $type[$key], $id[$key], $ns[$key]);
}
}
else {
$xml .= self::prepareMessage($jaxl, $to, $from, $child, $type, $id, $ns);
}
$jaxl->executePlugin('jaxl_send_message', $xml);
return $jaxl->sendXML($xml);
}
- private static function prepareMessage($jaxl, $to, $from, $child, $type, $id, $ns) {
+ public static function prepareMessage($jaxl, $to, $from, $child, $type, $id, $ns) {
$xml = '<message';
if($from) $xml .= ' from="'.$from.'"';
$xml .= ' to="'.htmlspecialchars($to).'"';
if($type) $xml .= ' type="'.$type.'"';
if($id) $xml .= ' id="'.$id.'"';
$xml .= '>';
if($child) {
if(isset($child['subject'])) $xml .= '<subject>'.JAXLUtil::xmlentities($child['subject']).'</subject>';
if(isset($child['body'])) $xml .= '<body>'.JAXLUtil::xmlentities($child['body']).'</body>';
if(isset($child['thread'])) $xml .= '<thread>'.$child['thread'].'</thread>';
if(isset($child['payload'])) $xml .= $child['payload'];
}
$xml .= '</message>';
return $xml;
}
public static function presence($jaxl, $to=false, $from=false, $child=false, $type=false, $id=false, $ns='jabber:client') {
$xml = '';
if(is_array($to)) {
foreach($to as $key => $value) {
$xml .= self::preparePresence($jaxl, $to[$key], $from[$key], $child[$key], $type[$key], $id[$key], $ns[$key]);
}
}
else {
$xml .= self::preparePresence($jaxl, $to, $from, $child, $type, $id, $ns);
}
$jaxl->executePlugin('jaxl_send_presence', $xml);
return $jaxl->sendXML($xml);
}
- private static function preparePresence($jaxl, $to, $from, $child, $type, $id, $ns) {
+ public static function preparePresence($jaxl, $to, $from, $child, $type, $id, $ns) {
$xml = '<presence';
if($type) $xml .= ' type="'.$type.'"';
if($from) $xml .= ' from="'.$from.'"';
if($to) $xml .= ' to="'.htmlspecialchars($to).'"';
if($id) $xml .= ' id="'.$id.'"';
$xml .= '>';
if($child) {
if(isset($child['show'])) $xml .= '<show>'.$child['show'].'</show>';
if(isset($child['status'])) $xml .= '<status>'.JAXLUtil::xmlentities($child['status']).'</status>';
if(isset($child['priority'])) $xml .= '<priority>'.$child['priority'].'</priority>';
if(isset($child['payload'])) $xml .= $child['payload'];
}
$xml.= '</presence>';
return $xml;
}
public static function iq($jaxl, $type, $payload=false, $to=false, $from=false, $callback=false, $id=false, $ns='jabber:client') {
if($type == 'get' || $type == 'set') {
$id = $jaxl->getId();
if($callback) $jaxl->addPlugin('jaxl_get_iq_'.$id, $callback);
}
$types = array('get','set','result','error');
$xml = '';
$xml .= '<iq';
$xml .= ' type="'.$type.'"';
$xml .= ' id="'.$id.'"';
if($to) $xml .= ' to="'.$to.'"';
if($from) $xml .= ' from="'.$from.'"';
$xml .= '>';
if($payload) $xml .= $payload;
$xml .= '</iq>';
$jaxl->sendXML($xml);
if($type == 'get' || $type == 'set') return $id;
else return true;
}
}
?>
|
jaxl/JAXL | b69f68982a250c7908165452cb6f3961a9ad0114 | Removed logging of empty pky rcvd after stream_select() timeout, also enabled XMPPGet logging in cgi mode | diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index 9404bfa..46893d6 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,496 +1,497 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
var $streamBlocking = 1;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
/**
* Instance start time
*/
var $startTime = false;
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
/**
* Maximum rate at which XMPP stanza's can flow out
*/
var $sendRate = false;
/**
* Size of each packet to be read from the socket
*/
var $getPktSize = false;
/**
* Read select timeouts
*/
var $getSelectSecs = 5;
var $getSelectUsecs = 0;
/**
* Packet count and sizes
*/
var $totalRcvdPkt = 0;
var $totalRcvdSize = 0;
var $totalSentPkt = 0;
var $totalSentSize = 0;
/**
* Whether Jaxl core should return a SimpleXMLElement object of parsed string with callback payloads?
*/
var $getSXE = false;
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
$this->clocked = $this->startTime = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
$this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 4096;
$this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : .4;
$this->getSelectSecs = isset($config['getSelectSecs']) ? $config['getSelectSecs'] : 5;
$this->getSXE = isset($config['getSXE']) ? $config['getSXE'] : false;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
$this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
$this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
$this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
$this->executePlugin('jaxl_post_connect', $ret);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = $this->executePlugin('jaxl_get_id', ++$this->lastid);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
* $option = null (read until data is available)
* $option = integer (read for so many seconds)
*/
function getXML() {
// prepare select streams
$streams = array(); $jaxls = $this->instances['xmpp'];
foreach($jaxls as $cnt=>$jaxl) {
if($jaxl->stream) $streams[$cnt] = $jaxl->stream;
else unset($jaxls[$cnt]);
}
// get num changed streams
$read = $streams; $write = null; $except = null; $secs = $this->getSelectSecs; $usecs = $this->getSelectUsecs;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPGet]] \nError while reading packet from stream", 5);
}
else {
$this->log("[[XMPPGet]] $changed streams ready for read out of total ".sizeof($streams)." streams", 7);
if($changed == 0) $now = $this->clocked+$secs;
else $now = time();
foreach($read as $k=>$r) {
// get jaxl instance we are dealing with
$ret = $payload = '';
$key = array_search($r, $streams);
$jaxl = $jaxls[$key];
unset($jaxls[$key]);
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
}
// reload pending buffer
$payload = $jaxl->buffer;
$jaxl->buffer = '';
// read stream
$ret = @fread($jaxl->stream, $jaxl->getPktSize);
- if($ret != '') $jaxl->log("[[XMPPGet]] \n".$ret, 4);
+ if(trim($ret) != '') $jaxl->log("[[XMPPGet]] \n".$ret, 4);
$jaxl->totalRcvdSize = strlen($ret);
$ret = $jaxl->executePlugin('jaxl_get_xml', $ret);
$payload .= $ret;
// route packets
$jaxl->handler($payload);
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
foreach($jaxls as $jaxl) {
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
$payload = $jaxl->executePlugin('jaxl_get_xml', '');
}
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
}
unset($jaxls, $streams);
return $changed;
}
/**
* Send XMPP XML packet over connected stream
*/
function sendXML($xml='', $force=false) {
$xml = $this->executePlugin('jaxl_send_xml', $xml);
if($this->mode == "cgi") {
$this->executePlugin('jaxl_send_body', $xml);
}
else {
$currSendRate = ($this->totalSentSize/(JAXLUtil::getTime()-$this->lastSendTime))/1000000;
$this->obuffer .= $xml;
if($this->rateLimit
&& !$force
&& $this->lastSendTime
&& ($currSendRate > $this->sendRate)
) {
$this->log("[[XMPPSend]] rateLimit\nBufferSize:".strlen($this->obuffer).", maxSendRate:".$this->sendRate.", currSendRate:".$currSendRate, 5);
return 0;
}
$xml = $this->obuffer;
$this->obuffer = '';
return ($xml == '') ? 0 : $this->_sendXML($xml);
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
if($this->stream && $xml != '') {
$read = array(); $write = array($this->stream); $except = array();
$secs = null; $usecs = null;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPSend]] \nError while trying to send packet", 5);
throw new JAXLException("[[XMPPSend]] \nError while trying to send packet");
return 0;
}
else if($changed > 0) {
$this->lastSendTime = JAXLUtil::getTime();
$xmls = JAXLUtil::splitXML($xml);
$pktCnt = count($xmls);
$this->totalSentPkt += $pktCnt;
$ret = @fwrite($this->stream, $xml);
$this->totalSentSize += $ret;
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
return $ret;
}
else {
$this->log("[[XMPPSend]] Failed\n".$xml);
throw new JAXLException("[[XMPPSend]] \nFailed");
return 0;
}
}
else if($xml == '') {
$this->log("[[XMPPSend]] Tried to send an empty stanza, not processing", 1);
return 0;
}
else {
$this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
return 0;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
if($payload == '' && $this->mode == 'cli') return '';
+ if($payload != '' && $this->mode == 'cgi') $this->log("[[XMPPGet]] \n".$payload, 4);
$payload = $this->executePlugin('jaxl_pre_handler', $payload);
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
$this->totalRcvdPkt += $pktCnt;
$buffer = array();
foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
$this->buffer .= $xml;
break;
}
}
if(substr($xml, 0, 7) == '<stream') $arr = $this->xml->xmlize($xml);
else $arr = JAXLXml::parse($xml, $this->getSXE);
if($arr === false) { $this->buffer .= $xml; continue; }
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
$jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
unset($buffer);
$this->executePlugin('jaxl_post_handler', $payload);
return $payload;
}
}
?>
|
jaxl/JAXL | 8915a7d3d25d932e03c3deae4fd98ba53f577b73 | Jaxl core mode can be passed as constructor parameter, see preFetchXMPP.php for example usage | diff --git a/core/jaxl.class.php b/core/jaxl.class.php
index c4bec10..9c119ae 100644
--- a/core/jaxl.class.php
+++ b/core/jaxl.class.php
@@ -174,737 +174,743 @@
var $jid = false;
/**
* Bare JID of the connected Jaxl instance
*
* @var string
*/
var $bareJid = false;
/**
* Domain for the connecting Jaxl instance
*
* @var string
*/
var $domain = 'localhost';
/**
* Resource for the connecting Jaxl instance
*
* @var string
*/
var $resource = false;
/**
* Local cache of roster list and related info maintained by Jaxl instance
*/
var $roster = array();
/**
* Jaxl will track presence stanza's and update local $roster cache
*/
var $trackPresence = true;
/**
* Configure Jaxl instance to auto-accept subscription requests
*/
var $autoSubscribe = false;
/**
* Log Level of the connected Jaxl instance
*
* @var integer
*/
var $logLevel = 1;
/**
* Enable/Disable automatic log rotation for this Jaxl instance
*
* @var bool|integer
*/
var $logRotate = false;
/**
* Absolute path of log file for this Jaxl instance
*/
var $logPath = '/var/log/jaxl.log';
/**
* Absolute path of pid file for this Jaxl instance
*/
var $pidPath = '/var/run/jaxl.pid';
/**
* Enable/Disable shutdown callback on SIGH terms
*
* @var bool
*/
var $sigh = true;
/**
* Process Id of the connected Jaxl instance
*
* @var bool|integer
*/
var $pid = false;
/**
* Mode of the connected Jaxl instance (cgi or cli)
*
* @var bool|string
*/
var $mode = false;
/**
* Jabber auth mechanism performed by this Jaxl instance
*
* @var false|string
*/
var $authType = false;
/**
* Jaxl instance dumps usage statistics periodically. Disabled if set to "false"
*
* @var bool|integer
*/
var $dumpStat = 300;
/**
* List of XMPP feature supported by this Jaxl instance
*
* @var array
*/
var $features = array();
/**
* XMPP entity category for the connected Jaxl instance
*
* @var string
*/
var $category = 'client';
/**
* XMPP entity type for the connected Jaxl instance
*
* @var string
*/
var $type = 'bot';
/**
* Default language of the connected Jaxl instance
*/
var $lang = 'en';
/**
* Location to system temporary folder
*/
var $tmpPath = null;
/**
* IP address of the host Jaxl instance is running upon.
* To be used by STUN client implementations.
*/
var $ip = null;
/**
* PHP OpenSSL module info
*/
var $openSSL = false;
var $instances = false;
/**
* @return string $name Returns name of this Jaxl client
*/
function getName() {
return JAXL::name;
}
/**
* @return float $version Returns version of this Jaxl client
*/
function getVersion() {
return JAXL::version;
}
/**
* Discover items
*/
function discoItems($jid, $callback, $node=false) {
$this->JAXL0030('discoItems', $jid, $this->jid, $callback, $node);
}
/**
* Discover info
*/
function discoInfo($jid, $callback, $node=false) {
$this->JAXL0030('discoInfo', $jid, $this->jid, $callback, $node);
}
/**
* Shutdown Jaxl instance cleanly
*
* shutdown method is auto invoked when Jaxl instance receives a SIGH term.
* Before cleanly shutting down this method callbacks registered using <b>jaxl_pre_shutdown</b> hook.
*
* @param mixed $signal This is passed as paramater to callbacks registered using <b>jaxl_pre_shutdown</b> hook
*/
function shutdown($signal=false) {
$this->log("[[JAXL]] Shutting down ...");
$this->executePlugin('jaxl_pre_shutdown', $signal);
if($this->stream) $this->endStream();
$this->stream = false;
}
/**
* Perform authentication for connecting Jaxl instance
*
* @param string $type Authentication mechanism to proceed with. Supported auth types are:
* - DIGEST-MD5
* - PLAIN
* - X-FACEBOOK-PLATFORM
* - ANONYMOUS
*/
function auth($type) {
$this->authType = $type;
return XMPPSend::startAuth($this);
}
/**
* Set status of the connected Jaxl instance
*
* @param bool|string $status
* @param bool|string $show
* @param bool|integer $priority
* @param bool $caps
*/
function setStatus($status=false, $show=false, $priority=false, $caps=false, $vcard=false) {
$child = array();
$child['status'] = ($status === false ? 'Online using Jaxl library http://code.google.com/p/jaxl' : $status);
$child['show'] = ($show === false ? 'chat' : $show);
$child['priority'] = ($priority === false ? 1 : $priority);
if($caps) $child['payload'] = $this->JAXL0115('getCaps', $this->features);
if($vcard) $child['payload'] .= $this->JAXL0153('getUpdateData', false);
return XMPPSend::presence($this, false, false, $child, false);
}
/**
* Send authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send authorization request
*/
function subscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribe');
}
/**
* Accept authorization request from $toJid
*
* @param string $toJid JID who's authorization request Jaxl instance wants to accept
*/
function subscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribed');
}
/**
* Send cancel authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send cancel authorization request
*/
function unsubscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribe');
}
/**
* Accept cancel authorization request from $toJid
*
* @param string $toJid JID who's cancel authorization request Jaxl instance wants to accept
*/
function unsubscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribed');
}
/**
* Retrieve connected Jaxl instance roster list from the server
*
* @param mixed $callback Method to be callback'd when roster list is received from the server
*/
function getRosterList($callback=false) {
$payload = '<query xmlns="jabber:iq:roster"/>';
if($callback === false) $callback = array($this, '_handleRosterList');
return XMPPSend::iq($this, "get", $payload, false, $this->jid, $callback);
}
/**
* Add a new jabber account in connected Jaxl instance roster list
*
* @param string $jid JID to be added in the roster list
* @param string $group Group name
* @param bool|string $name Name of JID to be added
*/
function addRoster($jid, $group, $name=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Update subscription of a jabber account in roster list
*
* @param string $jid JID to be updated inside roster list
* @param string $group Updated group name
* @param bool|string $subscription Updated subscription type
*/
function updateRoster($jid, $group, $name=false, $subscription=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
if($subscription) $payload .= ' subscription="'.$subscription.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Delete a jabber account from roster list
*
* @param string $jid JID to be removed from the roster list
*/
function deleteRoster($jid) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'" subscription="remove">';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Send an XMPP message
*
* @param string $to JID to whom message is sent
* @param string $message Message to be sent
* @param string $from (Optional) JID from whom this message should be sent
* @param string $type (Optional) Type of message stanza to be delivered
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessage($to, $message, $from=false, $type='chat', $id=false) {
$child = array();
$child['body'] = $message;
return XMPPSend::message($this, $to, $from, $child, $type, $id);
}
/**
* Send multiple XMPP messages in one go
*
* @param array $to array of JID's to whom this presence stanza should be send
* @param array $from (Optional) array of JID from whom this presence stanza should originate
* @param array $child (Optional) array of arrays specifying child objects of the stanza
* @param array $type (Optional) array of type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessages($to, $from=false, $child=false, $type='chat', $id=false) {
return XMPPSend::message($this, $to, $from, $child, $type);
}
/**
* Send an XMPP presence stanza
*
* @param string $to (Optional) JID to whom this presence stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param array $child (Optional) array specifying child objects of the stanza
* @param string $type (Optional) Type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendPresence($to=false, $from=false, $child=false, $type=false, $id=false) {
return XMPPSend::presence($this, $to, $from, $child, $type, $id);
}
/**
* Send an XMPP iq stanza
*
* @param string $type Type of iq stanza to send
* @param string $payload (Optional) XML string to be transmitted
* @param string $to (Optional) JID to whom this iq stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param string|array $callback (Optional) Callback method which will handle "result" type stanza rcved
* @param integer $id (Optional) Add an id attribute to transmitted stanza (auto-generated if not provided)
*/
function sendIQ($type, $payload=false, $to=false, $from=false, $callback=false, $id=false) {
return XMPPSend::iq($this, $type, $payload, $to, $from, $callback, $id);
}
/**
* Logs library core and application debug data into the log file
*
* @param string $log Datum to be logged
* @param integer $level Log level for passed datum
*/
function log($log, $level=1) {
JAXLog::log($log, $level, $this);
}
/**
* Instead of using jaxl_require method applications can use $jaxl->requires to include XEP's in PHP environment
*
* @param string $class Class name of the XEP to be included e.g. JAXL0045 for including XEP-0045 a.k.a. Multi-user chat
*/
function requires($class) {
jaxl_require($class, $this);
}
/**
* Use this method instead of JAXLPlugin::add to register a callback for connected instance only
*/
function addPlugin($hook, $callback, $priority=10) {
JAXLPlugin::add($hook, $callback, $priority, $this->uid);
}
/**
* Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
*/
function removePlugin($hook, $callback, $priority=10) {
JAXLPlugin::remove($hook, $callback, $priority, $this->uid);
}
/**
* Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
*/
function executePlugin($hook, $payload) {
return JAXLPlugin::execute($hook, $payload, $this);
}
/**
* Add another jaxl instance in a running core
*/
function addCore($jaxl) {
$jaxl->addPlugin('jaxl_post_connect', array($jaxl, 'startStream'));
$jaxl->connect();
$this->instances['xmpp'][] = $jaxl;
}
/**
* Starts Jaxl Core
*
* This method should be called after Jaxl initialization and hook registration inside your application code
* Optionally, you can pass 'jaxl_post_connect' and 'jaxl_get_auth_mech' response type directly to this method
* In that case application code SHOULD NOT register callbacks to above mentioned hooks
*
* @param string $arg[0] Optionally application code can pre-choose what Jaxl core should do after establishing socket connection.
* Following are the valid options:
* a) startStream
* b) startComponent
* c) startBosh
*/
function startCore(/* $mode, $param1, $param2, ... */) {
$argv = func_get_args();
$mode = $argv[0];
if($mode) {
switch($mode) {
case 'stream':
$this->addPlugin('jaxl_post_connect', array($this, 'startStream'));
break;
case 'component':
$this->addPlugin('jaxl_post_connect', array($this, 'startComponent'));
break;
case 'bosh':
$this->startBosh();
break;
default:
break;
}
}
if($this->mode == 'cli') {
try {
if($this->connect()) {
while($this->stream) {
$this->getXML();
}
}
}
catch(JAXLException $e) {
die($e->getMessage());
}
/* Exit Jaxl after end of loop */
exit;
}
}
/**
* Starts a socket server at 127.0.0.1:port
*
* startHTTPd converts Jaxl instance into a Jaxl socket server (may or may not be a HTTP server)
* Same Jaxl socket server instance <b>SHOULD NOT</b> be used for XMPP communications.
* Instead separate "new Jaxl();" instances should be created for such XMPP communications.
*/
function startHTTPd($port, $maxq) {
JAXLHTTPd::start(array(
'port' => $port,
'maxq' => $maxq
));
}
/**
* Start instance in bosh mode
*/
function startBosh() {
$this->JAXL0206('startStream');
}
/**
* Start instance in component mode
*/
function startComponent($payload, $jaxl) {
$this->JAXL0114('startStream', $payload);
}
/**
* Jaxl core constructor
*
* Jaxl instance configures itself using the constants inside your application jaxl.ini.
* However, passed array of configuration options overrides the value inside jaxl.ini.
* If no configuration are found or passed for a particular value,
* Jaxl falls back to default config options.
*
* @param $config Array of configuration options
* @todo Use DNS SRV lookup to set $jaxl->host from provided domain info
*/
function __construct($config=array()) {
global $jaxl_instance_cnt;
parent::__construct($config);
$this->uid = ++$jaxl_instance_cnt;
$this->ip = gethostbyname(php_uname('n'));
- $this->mode = (PHP_SAPI == "cli") ? PHP_SAPI : "cgi";
$this->config = $config;
$this->pid = getmypid();
/* Mandatory params to be supplied either by jaxl.ini constants or constructor $config array */
$this->user = $this->getConfigByPriority(@$config['user'], "JAXL_USER_NAME", $this->user);
$this->pass = $this->getConfigByPriority(@$config['pass'], "JAXL_USER_PASS", $this->pass);
$this->domain = $this->getConfigByPriority(@$config['domain'], "JAXL_HOST_DOMAIN", $this->domain);
$this->bareJid = $this->user."@".$this->domain;
/* Optional params if not configured using jaxl.ini or $config take default values */
$this->host = $this->getConfigByPriority(@$config['host'], "JAXL_HOST_NAME", $this->domain);
$this->port = $this->getConfigByPriority(@$config['port'], "JAXL_HOST_PORT", $this->port);
$this->resource = $this->getConfigByPriority(@$config['resource'], "JAXL_USER_RESC", "jaxl.".$this->uid.".".$this->clocked);
$this->logLevel = $this->getConfigByPriority(@$config['logLevel'], "JAXL_LOG_LEVEL", $this->logLevel);
$this->logRotate = $this->getConfigByPriority(@$config['logRotate'], "JAXL_LOG_ROTATE", $this->logRotate);
$this->logPath = $this->getConfigByPriority(@$config['logPath'], "JAXL_LOG_PATH", $this->logPath);
if(!file_exists($this->logPath) && !touch($this->logPath)) throw new JAXLException("Log file ".$this->logPath." doesn't exists");
$this->pidPath = $this->getConfigByPriority(@$config['pidPath'], "JAXL_PID_PATH", $this->pidPath);
+ $this->mode = $this->getConfigByPriority(@$config['mode'], "JAXL_MODE", (PHP_SAPI == "cli") ? PHP_SAPI : "cgi");
if($this->mode == "cli" && !file_exists($this->pidPath) && !touch($this->pidPath)) throw new JAXLException("Pid file ".$this->pidPath." doesn't exists");
/* Resolve temporary folder path */
if(function_exists('sys_get_temp_dir')) $this->tmpPath = sys_get_temp_dir();
$this->tmpPath = $this->getConfigByPriority(@$config['tmpPath'], "JAXL_TMP_PATH", $this->tmpPath);
if($this->tmpPath && !file_exists($this->tmpPath)) throw new JAXLException("Tmp directory ".$this->tmpPath." doesn't exists");
/* Handle pre-choosen auth type mechanism */
$this->authType = $this->getConfigByPriority(@$config['authType'], "JAXL_AUTH_TYPE", $this->authType);
if($this->authType) $this->addPlugin('jaxl_get_auth_mech', array($this, 'doAuth'));
/* Presence handling */
$this->trackPresence = isset($config['trackPresence']) ? $config['trackPresence'] : true;
$this->autoSubscribe = isset($config['autoSubscribe']) ? $config['autoSubscribe'] : false;
$this->addPlugin('jaxl_get_presence', array($this, '_handlePresence'), 0);
/* Optional params which can be configured only via constructor $config */
$this->sigh = isset($config['sigh']) ? $config['sigh'] : true;
$this->dumpStat = isset($config['dumpStat']) ? $config['dumpStat'] : 300;
/* Configure instance for platforms */
$this->configure($config);
/* Initialize xml to array class (will deprecate in future) */
$this->xml = new XML();
/* Initialize JAXLCron and register core jobs */
JAXLCron::init($this);
if($this->dumpStat) JAXLCron::add(array($this, 'dumpStat'), $this->dumpStat);
if($this->logRotate) JAXLCron::add(array('JAXLog', 'logRotate'), $this->logRotate);
/* include recommended XEP's for every XMPP entity */
$this->requires(array(
'JAXL0030', // service discovery
'JAXL0128' // entity capabilities
));
/* initialize multi-core instance holder */
if($jaxl_instance_cnt == 1) $this->instances = array('xmpp'=>array(),'http'=>array());
$this->instances['xmpp'][] = $this;
}
/**
* Return Jaxl instance config param depending upon user choice and default values
*/
function getConfigByPriority($config, $constant, $default) {
return ($config === null) ? (@constant($constant) === null ? $default : constant($constant)) : $config;
}
/**
* Configures Jaxl instance to run across various platforms (*nix/windows)
*
* Configure method tunes connecting Jaxl instance for
* OS compatibility, SSL support and dependencies over PHP methods
*/
protected function configure() {
// register shutdown function
if(!JAXLUtil::isWin() && JAXLUtil::pcntlEnabled() && $this->sigh) {
pcntl_signal(SIGTERM, array($this, "shutdown"));
pcntl_signal(SIGINT, array($this, "shutdown"));
$this->log("[[JAXL]] Registering callbacks for CTRL+C and kill.", 4);
}
else {
$this->log("[[JAXL]] No callbacks registered for CTRL+C and kill.", 4);
}
// check Jaxl dependency on PHP extension in cli mode
if($this->mode == "cli") {
if(($this->openSSL = JAXLUtil::sslEnabled()))
$this->log("[[JAXL]] OpenSSL extension is loaded.", 4);
else
$this->log("[[JAXL]] OpenSSL extension not loaded.", 4);
if(!function_exists('fsockopen'))
throw new JAXLException("[[JAXL]] Requires fsockopen method");
if(@is_writable($this->pidPath))
file_put_contents($this->pidPath, $this->pid);
}
// check Jaxl dependency on PHP extension in cgi mode
if($this->mode == "cgi") {
if(!function_exists('curl_init'))
throw new JAXLException("[[JAXL]] Requires CURL PHP extension");
if(!function_exists('json_encode'))
throw new JAXLException("[[JAXL]] Requires JSON PHP extension.");
}
}
/**
* Dumps Jaxl instance usage statistics
*
* Jaxl instance periodically calls this methods every JAXL::$dumpStat seconds.
*/
function dumpStat() {
$stat = "[[JAXL]] Memory:".round(memory_get_usage()/pow(1024,2), 2)."Mb";
if(function_exists('memory_get_peak_usage')) $stat .= ", PeakMemory:".round(memory_get_peak_usage()/pow(1024,2), 2)."Mb";
$stat .= ", obuffer: ".strlen($this->obuffer);
$stat .= ", buffer: ".strlen($this->buffer);
$stat .= ", RcvdRate: ".$this->totalRcvdSize/$this->clock."Kb";
$stat .= ", SentRate: ".$this->totalSentSize/$this->clock."Kb";
$this->log($stat, 1);
}
/**
* Magic method for calling XEP's included by the JAXL instance
*
* Application <b>should never</b> call an XEP method directly using <code>JAXL0045::joinRoom()</code>
* instead use <code>$jaxl->JAXL0045('joinRoom', $param1, ..)</code> to call methods provided by included XEP's
*
* @param string $xep XMPP extension (XEP) class name e.g. JAXL0045 for XEP-0045 a.k.a. Multi-User chat extension
* @param array $param Array of parameters where $param[0]='methodName' is the method called inside JAXL0045 class
*
* @return mixed $return Return value of called XEP method
*/
function __call($xep, $param) {
$method = array_shift($param);
array_unshift($param, $this);
if(substr($xep, 0, 4) == 'JAXL') {
$xep = substr($xep, 4, 4);
if(is_numeric($xep)
&& class_exists('JAXL'.$xep)
- ) { return call_user_func_array(array('JAXL'.$xep, $method), $param); }
+ ) {
+ $this->log("[[JAXL]] Calling JAXL$xep method ".$method, 5);
+ return call_user_func_array(array('JAXL'.$xep, $method), $param);
+ }
else { $this->log("[[JAXL]] JAXL$xep Doesn't exists in the environment"); }
}
+ else {
+ $this->log("[[JAXL]] Call to an unidentified XEP");
+ }
}
/**
* Perform pre-choosen auth type for the Jaxl instance
*/
function doAuth($mechanism) {
return XMPPSend::startAuth($this);
}
/**
* Adds a node (if doesn't exists) for $jid inside local $roster cache
*/
function _addRosterNode($jid, $inRoster=true) {
if(!isset($this->roster[$jid]))
$this->roster[$jid] = array(
'groups'=>array(),
'name'=>'',
'subscription'=>'',
'presence'=>array(),
'inRoster'=>$inRoster
);
return;
}
/**
* Core method that accepts retrieved roster list and manage local cache
*/
function _handleRosterList($payload, $jaxl) {
if(@is_array($payload['queryItemJid'])) {
foreach($payload['queryItemJid'] as $key=>$jid) {
$this->_addRosterNode($jid);
$this->roster[$jid]['groups'] = @$payload['queryItemGrp'][$key];
$this->roster[$jid]['name'] = @$payload['queryItemName'][$key];
$this->roster[$jid]['subscription'] = @$payload['queryItemSub'][$key];
}
}
else {
$jid = @$payload['queryItemJid'];
$this->_addRosterNode($jid);
$this->roster[$jid]['groups'] = @$payload['queryItemGrp'];
$this->roster[$jid]['name'] = @$payload['queryItemName'];
$this->roster[$jid]['subscription'] = @$payload['queryItemSub'];
}
$this->executePlugin('jaxl_post_roster_update', $payload);
return $payload;
}
/**
* Tracks all incoming presence stanza's
*/
function _handlePresence($payloads, $jaxl) {
foreach($payloads as $payload) {
if($this->trackPresence) {
// update local $roster cache
$jid = JAXLUtil::getBareJid($payload['from']);
$this->_addRosterNode($jid, false);
if(!isset($this->roster[$jid]['presence'][$payload['from']])) $this->roster[$jid]['presence'][$payload['from']] = array();
$this->roster[$jid]['presence'][$payload['from']]['type'] = $payload['type'] == '' ? 'available' : $payload['type'];
$this->roster[$jid]['presence'][$payload['from']]['status'] = $payload['status'];
$this->roster[$jid]['presence'][$payload['from']]['show'] = $payload['show'];
$this->roster[$jid]['presence'][$payload['from']]['priority'] = $payload['priority'];
}
if($payload['type'] == 'subscribe'
&& $this->autoSubscribe
) {
$this->subscribed($payload['from']);
$this->subscribe($payload['from']);
$this->executePlugin('jaxl_post_subscription_request', $payload);
}
else if($payload['type'] == 'subscribed') {
$this->executePlugin('jaxl_post_subscription_accept', $payload);
}
}
return $payloads;
}
}
?>
|
jaxl/JAXL | e37acfb2679d8dfae59461e4f67412985c3c06c7 | No log if empty pkt rcvd from stream after timeout event | diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index 17e0ee7..9404bfa 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,496 +1,496 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
var $streamBlocking = 1;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
/**
* Instance start time
*/
var $startTime = false;
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
/**
* Maximum rate at which XMPP stanza's can flow out
*/
var $sendRate = false;
/**
* Size of each packet to be read from the socket
*/
var $getPktSize = false;
/**
* Read select timeouts
*/
var $getSelectSecs = 5;
var $getSelectUsecs = 0;
/**
* Packet count and sizes
*/
var $totalRcvdPkt = 0;
var $totalRcvdSize = 0;
var $totalSentPkt = 0;
var $totalSentSize = 0;
/**
* Whether Jaxl core should return a SimpleXMLElement object of parsed string with callback payloads?
*/
var $getSXE = false;
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
$this->clocked = $this->startTime = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
$this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 4096;
$this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : .4;
$this->getSelectSecs = isset($config['getSelectSecs']) ? $config['getSelectSecs'] : 5;
$this->getSXE = isset($config['getSXE']) ? $config['getSXE'] : false;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
$this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
$this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
$this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
$this->executePlugin('jaxl_post_connect', $ret);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = $this->executePlugin('jaxl_get_id', ++$this->lastid);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
* $option = null (read until data is available)
* $option = integer (read for so many seconds)
*/
function getXML() {
// prepare select streams
$streams = array(); $jaxls = $this->instances['xmpp'];
foreach($jaxls as $cnt=>$jaxl) {
if($jaxl->stream) $streams[$cnt] = $jaxl->stream;
else unset($jaxls[$cnt]);
}
// get num changed streams
$read = $streams; $write = null; $except = null; $secs = $this->getSelectSecs; $usecs = $this->getSelectUsecs;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPGet]] \nError while reading packet from stream", 5);
}
else {
$this->log("[[XMPPGet]] $changed streams ready for read out of total ".sizeof($streams)." streams", 7);
if($changed == 0) $now = $this->clocked+$secs;
else $now = time();
foreach($read as $k=>$r) {
// get jaxl instance we are dealing with
$ret = $payload = '';
$key = array_search($r, $streams);
$jaxl = $jaxls[$key];
unset($jaxls[$key]);
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
}
// reload pending buffer
$payload = $jaxl->buffer;
$jaxl->buffer = '';
// read stream
$ret = @fread($jaxl->stream, $jaxl->getPktSize);
- $jaxl->log("[[XMPPGet]] \n".$ret, 4);
+ if($ret != '') $jaxl->log("[[XMPPGet]] \n".$ret, 4);
$jaxl->totalRcvdSize = strlen($ret);
$ret = $jaxl->executePlugin('jaxl_get_xml', $ret);
$payload .= $ret;
// route packets
$jaxl->handler($payload);
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
foreach($jaxls as $jaxl) {
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
$payload = $jaxl->executePlugin('jaxl_get_xml', '');
}
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
}
unset($jaxls, $streams);
return $changed;
}
/**
* Send XMPP XML packet over connected stream
*/
function sendXML($xml='', $force=false) {
$xml = $this->executePlugin('jaxl_send_xml', $xml);
if($this->mode == "cgi") {
$this->executePlugin('jaxl_send_body', $xml);
}
else {
$currSendRate = ($this->totalSentSize/(JAXLUtil::getTime()-$this->lastSendTime))/1000000;
$this->obuffer .= $xml;
if($this->rateLimit
&& !$force
&& $this->lastSendTime
&& ($currSendRate > $this->sendRate)
) {
$this->log("[[XMPPSend]] rateLimit\nBufferSize:".strlen($this->obuffer).", maxSendRate:".$this->sendRate.", currSendRate:".$currSendRate, 5);
return 0;
}
$xml = $this->obuffer;
$this->obuffer = '';
return ($xml == '') ? 0 : $this->_sendXML($xml);
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
if($this->stream && $xml != '') {
$read = array(); $write = array($this->stream); $except = array();
$secs = null; $usecs = null;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPSend]] \nError while trying to send packet", 5);
throw new JAXLException("[[XMPPSend]] \nError while trying to send packet");
return 0;
}
else if($changed > 0) {
$this->lastSendTime = JAXLUtil::getTime();
$xmls = JAXLUtil::splitXML($xml);
$pktCnt = count($xmls);
$this->totalSentPkt += $pktCnt;
$ret = @fwrite($this->stream, $xml);
$this->totalSentSize += $ret;
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
return $ret;
}
else {
$this->log("[[XMPPSend]] Failed\n".$xml);
throw new JAXLException("[[XMPPSend]] \nFailed");
return 0;
}
}
else if($xml == '') {
$this->log("[[XMPPSend]] Tried to send an empty stanza, not processing", 1);
return 0;
}
else {
$this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
return 0;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
if($payload == '' && $this->mode == 'cli') return '';
$payload = $this->executePlugin('jaxl_pre_handler', $payload);
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
$this->totalRcvdPkt += $pktCnt;
$buffer = array();
foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
$this->buffer .= $xml;
break;
}
}
if(substr($xml, 0, 7) == '<stream') $arr = $this->xml->xmlize($xml);
else $arr = JAXLXml::parse($xml, $this->getSXE);
if($arr === false) { $this->buffer .= $xml; continue; }
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
$jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
unset($buffer);
$this->executePlugin('jaxl_post_handler', $payload);
return $payload;
}
}
?>
|
jaxl/JAXL | a049a43ed7b6a73b90626aa523e181082c2b188c | Added option to pass getSXE option to Jaxl constructor (Whether Jaxl core should return a SimpleXMLElement object of parsed string with callback payloads) | diff --git a/CHANGELOG b/CHANGELOG
index 14e6ee1..02f9c3d 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,318 +1,319 @@
version 2.1.2
-------------
+- Added option to pass getSXE option to Jaxl constructor (Whether Jaxl core should return a SimpleXMLElement object of parsed string with callback payloads)
- Better handling for multi-instance jaxl applications (Use JAXL::addCore to add new instance)
Simple method of issuing unique id to each connected jaxl instance
Improved dumpStat cron to include send/rcv rate, buffer sizes in stats
Core logged class prefix log data with instance uid, pid and current clock
Parse class return false if unable to parse as xml for recv'd xmpp packet
Lots of core improvement in XMPP base class related to performance and multi-instance app handling
- Updated core class files to make use of JAXL::executePlugin method instead of JAXLPlugin::execute method
- XMPP base class now make use of socket_select() to poll opened stream efficiently (getting rid of annoying sleep)
Updated JAXLCron method to adjust to new core changes
- Added hook for jaxl_get_bosh_curl_error which is called when bosh end point returns a non-zero errno
Updated Jaxl core session variable names to avoid clash with existing session vars
Updated boshchat.php to make use of jaxl_get_bosh_curl_error to disconnect intelligently
- PHP CMS looking to integrate Jaxl in their core can now force disable auto start of php session by Jaxl core
Simple pass 'boshSession' as false with jaxl constructor config array
- Entire Jaxl core including xmpp/, xep/ and core/ class files now make use of JAXL::addPlugin instead of JAXLPlugin to register per instance callbacks
- JAXLPlugin can now register a callback for a dedicated jaxl instance in a multi-instance jaxl application
Class functionality remains backward compatible.
- JAXLog class now also dump connect instance uid per log line
- XMPP instance iq id now defaults to a random value between 1 and 9
Also added jaxl_get_id event hook for apps to customize iq id for the connected Jaxl instance
Also as compared to default numeric iq id, Jaxl core now uses hex iq id's
- Every jaxl instance per php process id now generate it's own unique id JAXL::$uid
- Jaxl core doesn't go for a session if it's optional as indicated by the xmpp server
- Fixed boshChat postBind issues as reported by issue#26 (http://code.google.com/p/jaxl/issues/detail?id=26)
- Fixed jaxl constructor config read warning and XEP 0114 now make use of JAXL::getConfigByPriority method
- Removed warning while reading user config inside Jaxl constructor
Upgraded Jaxl Parser class which was malfunctioning on CentOS PHP 5.1.6 (cli)
- Added bosh error response handling and appropriate logging inside XMPP over Bosh core files
- Code cleanup inside jaxl logger class.
Fixed getConfigByPriority method which was malfunctioning in specific cases
- JAXLog class now using inbuild php function (error_log)
- Checking in first version of XEP-0016 (Privacy Lists), XEP-0055 (Jabber Search), XEP-0077 (In-Band Registration), XEP-0144 (Roster Item Exchange), XEP-0153 (vCard-Based Avatars), XEP-0237 (Roster Versioning)
- On auth faliure core doesn't throw exception since XMPP over Bosh apps are not held inside a try catch block (a better fix may be possible in future)
- XMPP over BOSH xep wasn't passing back Jaxl instance obj for jaxl_post_disconnect hook, fixed that for clean disconnect
- Jaxl core attempts to create log and pid files if doesn't already exists
Also instead of die() core throws relevant exception message wherever required
XMPP base classes throws relevant exception with message wherever required
- First commit of JAXLException class. JAXL core now uses JAXLException
- Jaxl constructor dies if logPath, pidPath and tmpPath doesn't exists on the system
- Core updates JAXL::resource after successful binding to match resource assigned by the connecting server
- Updated echobot sample example to make use of autoSubscribe core feature
Also registers callback for jaxl_post_subscription_request and jaxl_post_subscription_accept hooks
- Updated echobot and boshchat application to use in memory roster cache maintained by Jaxl core.
App files should register callback on hook jaxl_post_roster_update to get notified everytime local roster cache is updated
- Added provision for local roster cache management inside Jaxl core.
Retrived roster lists are cached in memory (see updated echobot.php sample example).
Also added provision for presence tracking (JAXL::trackPresence).
If enabled Jaxl core keep a track of jid availability and update local roster cache accordingly.
Also added provision for auto-accept subscription (JAXL::autoSubscribe).
- Removed XMPP::isConnected variable which used to tell status of connected socket stream.
This is equivalent to checking XMPP:stream variable for true/false
- Added a (kind of) buggy support for '/xml()' inside parser xpath
- If Jaxl instance has being configured for auto periodic ping (XEP-0199), pings are holded till auth completion.
Also if server responds 'feature-not-implemented' for first ping XEP-0199 automatically deleted periodic ping cron tab
- Corrected handling of error type iq stanza's (removed jaxl_get_iq_error hook)
- Added iq error code xpath inside JAXLXml class
- Completed missing JAXLCron::delete method for removing a previously registered cron tab
- Checking in first version of XEP-0049 (Private XML Storage) (not yet tested)
- Checking in first version of XEP-0191 (Simple Communication Blocking) (not yet tested)
- Added JAXL_PING_INTERVAL configuration option inside jaxl.ini
- XEP-0199 (XMPP Ping) can now automatically ping the connected server periodically for keeping connection alive on long running bots
(see echobot.php sample app for usage)
- Updated JAXLCron::add method to accept a number of arguments while adding bckgrnd jobs
These list of arguments is passed back to the application method
- Updated IQ handling inside XEP-0202 which wasn't returning iq stanza back resulting in no ping/pong
- Updated echobot to show usage of JAXL::discoItems and JAXL::discoInfo inside application code
- Added tagMap xpath for service identity and feature nodes in service discovery resultset
- JAXL core now auto includes XEP-0128 along with XEP-0030 on startup.
Also added two methods JAXL::discoItems and JAXL::discoInfo for service discovery
- Checking in first version of XEP-0128 (Service Discovery Extension)
- Fixed bug where message and presence stanza builder were not using passed id value as attribute
- Removed jaxl_pre_curl event hook which was only used internally by XEP-0124
- Jaxl now shutdown gracefully is encryption is required and openssl PHP module is not loaded in the environment
- For every registered callback on XMPP hooks, callback'd method will receive two params.
A payload and reference of Jaxl instance for whom XMPP event has occured.
Updated sample application code to use passed back Jaxl instance reference instead of global jaxl variable.
- As a library convention XEP's exposing user space configuration parameters via JAXL constructor SHOULD utilize JAXL::getConfigByPriority method
Added JAXL_TMP_PATH option inside jaxl.ini
- Jaxl::tmp is now Jaxl::tmpPath. Also added Jaxl config param to specify custom tmp path location
Jaxl client also self detect the IP of the host it is running upon (to be used by STUN/TURN utilities in Jingle negotitation)
- Removed JAXLUtil::includePath and JAXLUtil::getAppFilePath methods which are now redundant after removing jaxl.ini and jaxl.conf from lib core
- Removed global defines JAXL_BASE_PATH, JAXL_APP_BASE_PATH, JAXL_BOSH_APP_ABS_PATH from inside jaxl.ini (No more required by apps to specify these values)
- Removing env/jaxl.php and env/jaxl.conf (were required if you run your apps using `jaxl` command line utility)
Updated env/jaxl.ini so that projects can now directly include their app setting via jaxl.ini (before including core/jaxl.class.php)
- Added JAXL::bareJid public variable for usage inside applications.
XMPP base class now return bool on socket connect completion (used by PHPUnit test cases)
- Removing build.sh file from library for next release
Users should simply download, extract, include and write their app code without caring about the build script from 2.1.2 release
- As a library convention to include XEP's use JAXL::requires() method, while to include any core/ or xmpp/ base class use jaxl_require() method.
Updated library code and xep's to adhere to this convention.
Jaxl instance now provide a system specific /tmp folder location accessible by JAXL::tmp
- Removed JAXL_NAME and JAXL_VERSION constants.
Instead const variables are now defined per instance accessible by getName() and getVersion() methods.
Updated XEP-0030,0092,0115 to use the same
- Moved indivisual XEP's working parameter (0114,0124) from JAXL core class to XEP classes itself.
XEP's make use of JAXL::config array for parsing user options.
- Added JAXL_COMPONENT_PASS option inside jaxl.ini. Updated build.sh with new /app file paths.
Updated XEP-0114,0124,0206 to use array style configs as defined inside JAXL class
- Removed dependency upon jaxl.ini from all sample applications.
First checkin of sample sendMessage.php app.
- Config parameters for XEP's like 0114 and 0206 are now saved as an array inside JAXL class (later on they will be moved inside respective XEP's).
Added constructor config option to pre-choose an auth mechanism to be performed
if an auth mech is pre-chosen app files SHOULD not register callback for jaxl_get_auth_mech hook.
Bosh cookie settings can now be passed along with Jaxl constructor.
Added support for publishing vcard-temp:x:update node along with presence stanzas.
Jaxl instance can run in 3 modes a.k.a. stream,component and bosh mode
applications should use JAXL::startCore('mode') to configure instance for a specific mode.
- Removed redundant NS variable from inside XEP-0124
- Moved JAXLHTTPd setting defines inside the class (if gone missing CPU usage peaks to 100%)
- Added jaxl_httpd_pre_shutdown, jaxl_httpd_get_http_request, jaxl_httpd_get_sock_request event hooks inside JAXLHTTPd class
- Added JAXLS5B path (SOCKS5 implementation) inside jaxl_require method
- Removed all occurance of JAXL::$action variable from /core and /xep class files
- Updated boshChat and boshMUChat sample application which no longer user JAXL::$action variable inside application code
- Updated preFetchBOSH and preFetchXMPP sample example.
Application code don't need any JAXL::$action variable now
Neither application code need to define JAXL_BASE_PATH (optional from now on)
- JAXL core and XEP-0206 have no relation and dependency upon JAXL::$action variable now.
- Deprecated jaxl_get_body hook which was only for XEP-0124 working.
Also cleaned up XEP-0124 code by removing processBody method which is now handled inside preHandler itself.
- Defining JAXL_BASE_PATH inside application code made optional.
Developers can directly include /path/to/jaxl/core/jaxl.class.php and start writing applications.
Also added a JAXL::startCore() method (see usage in /app/preFetchXMPP.php).
Jaxl magic method for calling XEP methods now logs a warning inside jaxl.log if XEP doesn't exists in the environment
- Added tag map for XMPP message thread and subject child elements
- Fixed typo where in case of streamError proper description namespace was not parsed/displayed
- Disabled BOSH session close if application is running in boshOut=false mode
Suggested by MOVIM dev team who were experiencing loss of session data on end of script
- JAXL::log method 2nd parameter now defaults to logLevel=1 (passing 2nd param is now optional)
- Fixed XPath for iq stanza error condition and error NS extraction inside jaxl.parser.class
- First checkin of XEP-0184 Message Receipts
- Added support for usage of name() xpath function inside tag maps of JAXLXml class.
Also added some documentation for methods available inside JAXLXml class
- Fixed JAXLPlugin::remove method to properly remove and manage callback registry.
Also added some documentation for JAXLPlugin class methods
- Added JAXL contructor config option to disable BOSH module auto-output behaviour.
This is utilized inside app/preFetchBOSH.php sample example
- First checkin of sample application code pre-fetching XMPP/Jabber data for web page population using BOSH XEP
- Added a sample application file which can be used to pre-fetch XMPP/Jabber data for a webpage without using BOSH XEP or Ajax requests
As per the discussion on google groups (http://bit.ly/aKavZB) with MOVIM team
- JAXL library is now $jaxl independent, you can use anything like $var = new JAXL(); instance your applications now
JAXLUtil::encryptPassword now accepts username/password during SASL auth.
Previously it used to auto detect the same from JAXL instance, now core has to manually pass these param
- Added JAXL::startHTTPd method with appropriate docblock on how to convert Jaxl instance into a Jaxl socket (web) server.
Comments also explains how to still maintaining XMPP communication in the background
- Updated JAXLHTTPd class to use new constants inside jaxl.ini
- Added jaxl_get_stream_error event handler.
Registered callback methods also receive array form of received XMPP XML stanza
- Connecting Jaxl instance now fallback to default value 'localhost' for host,domain,boshHost,boshPort,boshSuffix
If these values are not configured either using jaxl.ini constants or constructor
- Provided a sendIQ method per JAXL instance.
Recommended that applications and XEP's should directly use this method for sending <iq/> type stanza
DONOT use XMPPSend methods inside your application code from here on
- Added configuration options for JAXL HTTPd server and JAXL Bosh Component Manager inside jaxl.ini
- Fixed type in XEP-0202 (Entity Time). XEP was not sending <iq/> id in response to get request
- Jaxl library is now phpdocs ready. Added extended documentation for JAXL core class, rest to be added
- All core classes inside core/, xmpp/ and xep/ folder now make use of jaxl->log method
JAXL Core constructor are now well prepared so that inclusion of jaxl.ini is now optional
Application code too should use jaxl->log instead of JAXLog::log method for logging purpose
- Reshuffled core instance paramaters between JAXL and XMPP class
Also Jaxl core now logs at level 1 instead of 0 (i.e. all logs goes inside jaxl.log and not on console)
- JAXL class now make use of endStream method inside XMPP base class while disconnecting.
Also XMPPSend::endStream now forces xmpp stanza delivery (escaping JAXL internal buffer)
http://code.google.com/p/jaxl/issues/detail?id=23
- Added endStream method inside XMPP base class and startSession,startBind methods inside XMPPSend class
XMPP::sendXML now accepts a $force parameter for escaping XMPP stanza's from JAXL internal buffer
- Updated the way Jaxl core calls XEP 0115 method (entity caps) to match documentation
XEP method's should accept jaxl instance as first paramater
- First checkin of PEP (Personal Eventing), User Location, User Mood, User Activity and User Tune XEP's
- Completed methods discoFeatures, discoNodes, discoNodeInfo, discoNodeMeta and discoNodeItems in PubSub XEP
- Hardcoded client category, type, lang and name. TODO: Make them configurable in future
- Cleaned up XEP 0030 (Service Discovery) and XEP 0115 (Entity Capabilities)
- Updated XMPP base class to use performance configuration parameters (now customizable with JAXL constructor)
- jaxl.conf will be removed from jaxl core in future, 1st step towards this goal
- Moved bulk of core configs from jaxl.conf
- Added more configuration options relating to client performance e.g. getPkts, getPktSize etc
- Fixed client mode by detecting sapi type instead of $_REQUEST['jaxl'] variable
- Now every implemented XEP should have an 'init' method which will accept only one parameter (jaxl instance itself)
- Jaxl core now converts transmitted stanza's into xmlentities (http://code.google.com/p/jaxl/issues/detail?id=22)
- Created a top level 'patch' folder which contains various patches sent by developers using 'git diff > patch' utility
- Fixed typo in namespace inside 0030 (thanks to Thomas Baquet for the patch)
- First checkin of PubSub XEP (untested)
- Indented build.sh and moved define's from top of JAXLHTTPd class to jaxl.ini
- Added JAXLHTTPd inside Jaxl core (a simple socket select server)
- Fixed sync of background iq and other stanza requests with browser ajax calls
- Updated left out methods in XMPP over BOSH xep to accept jaxl instance as first method
- All XEP methods available in application landspace, now accepts jaxl instance as first parameter. Updated core jaxl class magic method to handle the same.
If you are calling XEP methods as specified in the documentation, this change will not hurt your running applications
- Updated echobot sample application to utilize XEP 0054 (VCard Temp) and 0202 (Entity Time)
- First checkin of missing vcard-temp xep
- Added xmlentities JAXLUtil method
- Jaxl Parser now default parses xXmlns node for message stanzas
- Added PCRE_DOTALL and PCRE_MULTILINE pattern modifier for bosh unwrapBody method
- Added utility methods like urldecode, urlencode, htmlEntities, stripHTML and splitJid inside jaxl.js
- Updated sample application jaxl.ini to reflect changes in env/jaxl.ini
version 2.1.1
-------------
- Updated XMPPSend 'presence', 'message' and 'iq' methods to accept $jaxl instance as first parameter
if you are not calling these methods directly from your application code as mentioned in documentation
this change should not hurt you
- Added more comments to env/jaxl.ini and also added JAXL_LOG_ROTATE ini file option
- JAXL instance logs can be rotated every x seconds (logRotate config parameter) now
- Removed config param dumpTime, instead use dumpStat to specify stats dump period
- Base XMPP class now auto-flush output buffers filled because of library level rate limiter
- Added more options for JAXL constructor e.g.
boshHost, boshPort, boshSuffix, pidPath, logPath, logLevel, dumpStat, dumpTime
These param overwrites value specified inside jaxl.ini file
Also JAXL core will now periodically dump instance statistics
- Added an option in JAXL constructor to disable inbuild core rate limiter
- Added support when applications need to connect with external bosh endpoints
Bosh application code requires update for ->JAXL0206('startStream') method
- XMPPGet::handler replaces ->handler inside XEP-0124
- JAXLCron job now also passes connected instance to callback cron methods
- Updated base XMPP class now maintains a clock, updated sendXML method to respect library level rate limiting
- Base JAXL class now includes JAXLCron class for periodically dumping connected bot memory/usage stats
- First version of JAXLCron class for adding periodic jobs in the background
- XMPP payload handler moves from XMPPGet to base XMPP class, packets are then routed to XMPPGet class for further processing
- Updated xep-0124 to use instance bosh parameters instead of values defined inside jaxl.ini
- Provision to specify custom JAXL_BOSH_HOST inside jaxl.ini
- Instead of global logLevel and logPath, logger class now respects indivisual instance log settings
Helpful in multiple instance applications
- Updated base JAXL class to accept various other configuration parameters inside constructor
These param overwrites values defined inside jaxl.ini
- XMPPSend::xml method moves inside XMPP::sendXML (call using ->sendXML from within application code), as a part of library core cleanup
- Updated jaxl class to return back payload from called xep methods
- XMPP base method getXML can be instructed not to take a nap between stream reads
- Added jaxl_get_xml hook for taking control over incoming xml payload from xmpp stream
- Added support for disabling sig term registration, required by applications who already handle this in their core code
- Added capability of sending multiple message/presence stanza in one go inside jaxl base class
- Fixed typo in MUC Direct Invitation xep invite method
- getHandler should have accepted core instance by reference, fixed now. BOSH MUC Chat sample application header is now more appropriate
version 2.1.0
-------------
- First checkin of bosh MUC sample application
- Updated build file now packages bosh MUC chat sample application along with core classes
- Updated JAXLog class to accept instance inside log() method, application code should use ->log() to call JAXLog::log() method now
- Updated JAXLPlugin class to pass instance along with every XMPP event hook
- Updated jaxl_require method to call including XEP's init() method every time they are included using jaxl_require method
- Update jaxl.ini with some documentation/comments about JAXL_BOSH_COOKIE_DOMAIN parameter
- Updated echobot sample application code to pass instance while calling jaxl_require method
- Update XMPP SASL Auth class to accept instance while calculating SASL response.
Also passinginstance when jaxl_get_facebook_key hook is called
- Updated XMPP base class to accept component host name inside constructor.
Sending currentinstance with every XMPPSend, XMPPGet and JAXLog method calls
- Every XMPPGet method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Every XMPPSend method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Updated component bot sample application to show how to pass component host inside JAXL constructor.
Also updated jaxl_require call to accept current working instance
- Updated boshchat sample application to follow new rules of jaxl_require, also cleaned up the sample app code a bit
- Updated jaxl.ini of packaged sample applications to match /env/jaxl.ini
- Updated implemented XEP's init method to accept instance during initialization step
Send working instance with every XMPPSend method call
Almost every XEP's available method now accepts an additional instance so that XEP's can work independently for every instance inside a multiple jaxl instance application code
- Added magic method __call inside JAXL class
All application codes should now call a methods inside implemented XEP's like ->JAXLxxxx('method', , , ...)
Also added ->log method to be used by application codes
JAXLog::log() should not be called directly from application code
Updated XMPPSend methods to accept instance
Added ->requires() method that does a similar job as jaxl_require() which now also expects instance as one of the passed parameter.
version 2.0.4
-------------
- Updated XMPP base class and XMPP Get class to utilize new XMPPAuth class
- Updated jaxl_require method with new XMPPAuth class path
- Extracted XMPP SASL auth mechanism out of XMPP Get class, code cleanup
- unwrapBody method of XEP 0124 is now public
- Added #News block on top of README
- No more capital true, false, null inside Jaxl core to pass PHP_CodeSniffer tests
- :retab Jaxl library core to pass PHP_CodeSniffer tests
- Added Jabber Component Protocol example application bot
- Updated README with documentation link for Jabber component protocol
- Updated Entity Caps method to use list of passed feature list for verification code generation
- Updated MUC available methods doc link inside README
- Added experimental support for SCRAM-SHA-1, CRAM-MD5 and LOGIN auth mechanisms
version 2.0.3
-------------
- Updated Jaxl XML parsing class to handle multiple level nested child cases
- Updated README and bosh chat application with documentation link
- Fixed bosh application to run on localhost
- Added doc links inside echobot sample app
- Bosh sample application also use entity time XEP-0202 now
- Fix for sapi detection inside jaxl util
- jaxl.js updated to handle multiple ajax poll response payloads
- Bosh session manager now dumps ajax poll response on post handler callback
- Removed hardcoded ajax poll url inside boshchat application
- Updated component protocol XEP pre handshake event handling
version 2.0.2
-------------
- Packaged XEP 0202 (Entity Time)
- First checkin of Bosh related XEP 0124 and 0206
- Sample Bosh Chat example application
- Updated jaxl.class.php to save Bosh request action parameter
- jaxl.ini updated with Bosh related cookie options, default loglevel now set to 4
- jaxl.js checkin which should be used with bosh applications
- Updated base xmpp classes to provide integrated bosh support
- Outgoing presence and message stanza's too can include @id attribute now
version 2.0.1
-------------
- Typo fix in JAXLXml::$tagMap for errorCode
- Fix for handling overflooded roster list
- Packaged XEP 0115 (Entity capability) and XEP 0199 (XMPP Ping)
- Updated sample echobot to use XEP 0115 and XEP 0199
- Support for X-FACEBOOK-PLATFORM authentication
version 2.0.0
--------------
First checkin of:
- Restructed core library with event mechanism
- Packaged XEP 0004, 0030, 0045, 0050, 0085, 0092, 0114, 0133, 0249
- Sample echobot application
diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index 246282e..17e0ee7 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,489 +1,496 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
var $streamBlocking = 1;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
/**
* Instance start time
*/
var $startTime = false;
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
/**
* Maximum rate at which XMPP stanza's can flow out
*/
var $sendRate = false;
/**
* Size of each packet to be read from the socket
*/
var $getPktSize = false;
/**
* Read select timeouts
*/
var $getSelectSecs = 5;
var $getSelectUsecs = 0;
/**
* Packet count and sizes
*/
var $totalRcvdPkt = 0;
var $totalRcvdSize = 0;
var $totalSentPkt = 0;
var $totalSentSize = 0;
+ /**
+ * Whether Jaxl core should return a SimpleXMLElement object of parsed string with callback payloads?
+ */
+ var $getSXE = false;
+
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
$this->clocked = $this->startTime = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
$this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 4096;
$this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : .4;
+ $this->getSelectSecs = isset($config['getSelectSecs']) ? $config['getSelectSecs'] : 5;
+ $this->getSXE = isset($config['getSXE']) ? $config['getSXE'] : false;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
$this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
$this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
$this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
$this->executePlugin('jaxl_post_connect', $ret);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = $this->executePlugin('jaxl_get_id', ++$this->lastid);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
* $option = null (read until data is available)
* $option = integer (read for so many seconds)
*/
function getXML() {
// prepare select streams
$streams = array(); $jaxls = $this->instances['xmpp'];
foreach($jaxls as $cnt=>$jaxl) {
if($jaxl->stream) $streams[$cnt] = $jaxl->stream;
else unset($jaxls[$cnt]);
}
// get num changed streams
$read = $streams; $write = null; $except = null; $secs = $this->getSelectSecs; $usecs = $this->getSelectUsecs;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPGet]] \nError while reading packet from stream", 5);
}
else {
$this->log("[[XMPPGet]] $changed streams ready for read out of total ".sizeof($streams)." streams", 7);
if($changed == 0) $now = $this->clocked+$secs;
else $now = time();
foreach($read as $k=>$r) {
// get jaxl instance we are dealing with
$ret = $payload = '';
$key = array_search($r, $streams);
$jaxl = $jaxls[$key];
unset($jaxls[$key]);
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
}
// reload pending buffer
$payload = $jaxl->buffer;
$jaxl->buffer = '';
// read stream
$ret = @fread($jaxl->stream, $jaxl->getPktSize);
$jaxl->log("[[XMPPGet]] \n".$ret, 4);
$jaxl->totalRcvdSize = strlen($ret);
$ret = $jaxl->executePlugin('jaxl_get_xml', $ret);
$payload .= $ret;
// route packets
$jaxl->handler($payload);
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
foreach($jaxls as $jaxl) {
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
$payload = $jaxl->executePlugin('jaxl_get_xml', '');
}
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
}
unset($jaxls, $streams);
return $changed;
}
/**
* Send XMPP XML packet over connected stream
*/
function sendXML($xml='', $force=false) {
$xml = $this->executePlugin('jaxl_send_xml', $xml);
if($this->mode == "cgi") {
$this->executePlugin('jaxl_send_body', $xml);
}
else {
$currSendRate = ($this->totalSentSize/(JAXLUtil::getTime()-$this->lastSendTime))/1000000;
$this->obuffer .= $xml;
if($this->rateLimit
&& !$force
&& $this->lastSendTime
&& ($currSendRate > $this->sendRate)
) {
$this->log("[[XMPPSend]] rateLimit\nBufferSize:".strlen($this->obuffer).", maxSendRate:".$this->sendRate.", currSendRate:".$currSendRate, 5);
return 0;
}
$xml = $this->obuffer;
$this->obuffer = '';
return ($xml == '') ? 0 : $this->_sendXML($xml);
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
if($this->stream && $xml != '') {
$read = array(); $write = array($this->stream); $except = array();
$secs = null; $usecs = null;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPSend]] \nError while trying to send packet", 5);
throw new JAXLException("[[XMPPSend]] \nError while trying to send packet");
return 0;
}
else if($changed > 0) {
$this->lastSendTime = JAXLUtil::getTime();
$xmls = JAXLUtil::splitXML($xml);
$pktCnt = count($xmls);
$this->totalSentPkt += $pktCnt;
$ret = @fwrite($this->stream, $xml);
$this->totalSentSize += $ret;
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
return $ret;
}
else {
$this->log("[[XMPPSend]] Failed\n".$xml);
throw new JAXLException("[[XMPPSend]] \nFailed");
return 0;
}
}
else if($xml == '') {
$this->log("[[XMPPSend]] Tried to send an empty stanza, not processing", 1);
return 0;
}
else {
$this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
return 0;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
if($payload == '' && $this->mode == 'cli') return '';
$payload = $this->executePlugin('jaxl_pre_handler', $payload);
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
$this->totalRcvdPkt += $pktCnt;
$buffer = array();
foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
$this->buffer .= $xml;
break;
}
}
if(substr($xml, 0, 7) == '<stream') $arr = $this->xml->xmlize($xml);
- else $arr = JAXLXml::parse($xml);
+ else $arr = JAXLXml::parse($xml, $this->getSXE);
if($arr === false) { $this->buffer .= $xml; continue; }
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
$jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
unset($buffer);
$this->executePlugin('jaxl_post_handler', $payload);
return $payload;
}
}
?>
|
jaxl/JAXL | 5e494d82076185ce5bbbc4f678d26f1b25c6e567 | Better handling for multi-instance jaxl applications (Use JAXL::addCore to add new instance) | diff --git a/CHANGELOG b/CHANGELOG
index b8da5bf..14e6ee1 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,317 +1,318 @@
version 2.1.2
-------------
-- Simple method of issuing unique id to each connected jaxl instance
+- Better handling for multi-instance jaxl applications (Use JAXL::addCore to add new instance)
+ Simple method of issuing unique id to each connected jaxl instance
Improved dumpStat cron to include send/rcv rate, buffer sizes in stats
Core logged class prefix log data with instance uid, pid and current clock
Parse class return false if unable to parse as xml for recv'd xmpp packet
Lots of core improvement in XMPP base class related to performance and multi-instance app handling
- Updated core class files to make use of JAXL::executePlugin method instead of JAXLPlugin::execute method
- XMPP base class now make use of socket_select() to poll opened stream efficiently (getting rid of annoying sleep)
Updated JAXLCron method to adjust to new core changes
- Added hook for jaxl_get_bosh_curl_error which is called when bosh end point returns a non-zero errno
Updated Jaxl core session variable names to avoid clash with existing session vars
Updated boshchat.php to make use of jaxl_get_bosh_curl_error to disconnect intelligently
- PHP CMS looking to integrate Jaxl in their core can now force disable auto start of php session by Jaxl core
Simple pass 'boshSession' as false with jaxl constructor config array
- Entire Jaxl core including xmpp/, xep/ and core/ class files now make use of JAXL::addPlugin instead of JAXLPlugin to register per instance callbacks
- JAXLPlugin can now register a callback for a dedicated jaxl instance in a multi-instance jaxl application
Class functionality remains backward compatible.
- JAXLog class now also dump connect instance uid per log line
- XMPP instance iq id now defaults to a random value between 1 and 9
Also added jaxl_get_id event hook for apps to customize iq id for the connected Jaxl instance
Also as compared to default numeric iq id, Jaxl core now uses hex iq id's
- Every jaxl instance per php process id now generate it's own unique id JAXL::$uid
- Jaxl core doesn't go for a session if it's optional as indicated by the xmpp server
- Fixed boshChat postBind issues as reported by issue#26 (http://code.google.com/p/jaxl/issues/detail?id=26)
- Fixed jaxl constructor config read warning and XEP 0114 now make use of JAXL::getConfigByPriority method
- Removed warning while reading user config inside Jaxl constructor
Upgraded Jaxl Parser class which was malfunctioning on CentOS PHP 5.1.6 (cli)
- Added bosh error response handling and appropriate logging inside XMPP over Bosh core files
- Code cleanup inside jaxl logger class.
Fixed getConfigByPriority method which was malfunctioning in specific cases
- JAXLog class now using inbuild php function (error_log)
- Checking in first version of XEP-0016 (Privacy Lists), XEP-0055 (Jabber Search), XEP-0077 (In-Band Registration), XEP-0144 (Roster Item Exchange), XEP-0153 (vCard-Based Avatars), XEP-0237 (Roster Versioning)
- On auth faliure core doesn't throw exception since XMPP over Bosh apps are not held inside a try catch block (a better fix may be possible in future)
- XMPP over BOSH xep wasn't passing back Jaxl instance obj for jaxl_post_disconnect hook, fixed that for clean disconnect
- Jaxl core attempts to create log and pid files if doesn't already exists
Also instead of die() core throws relevant exception message wherever required
XMPP base classes throws relevant exception with message wherever required
- First commit of JAXLException class. JAXL core now uses JAXLException
- Jaxl constructor dies if logPath, pidPath and tmpPath doesn't exists on the system
- Core updates JAXL::resource after successful binding to match resource assigned by the connecting server
- Updated echobot sample example to make use of autoSubscribe core feature
Also registers callback for jaxl_post_subscription_request and jaxl_post_subscription_accept hooks
- Updated echobot and boshchat application to use in memory roster cache maintained by Jaxl core.
App files should register callback on hook jaxl_post_roster_update to get notified everytime local roster cache is updated
- Added provision for local roster cache management inside Jaxl core.
Retrived roster lists are cached in memory (see updated echobot.php sample example).
Also added provision for presence tracking (JAXL::trackPresence).
If enabled Jaxl core keep a track of jid availability and update local roster cache accordingly.
Also added provision for auto-accept subscription (JAXL::autoSubscribe).
- Removed XMPP::isConnected variable which used to tell status of connected socket stream.
This is equivalent to checking XMPP:stream variable for true/false
- Added a (kind of) buggy support for '/xml()' inside parser xpath
- If Jaxl instance has being configured for auto periodic ping (XEP-0199), pings are holded till auth completion.
Also if server responds 'feature-not-implemented' for first ping XEP-0199 automatically deleted periodic ping cron tab
- Corrected handling of error type iq stanza's (removed jaxl_get_iq_error hook)
- Added iq error code xpath inside JAXLXml class
- Completed missing JAXLCron::delete method for removing a previously registered cron tab
- Checking in first version of XEP-0049 (Private XML Storage) (not yet tested)
- Checking in first version of XEP-0191 (Simple Communication Blocking) (not yet tested)
- Added JAXL_PING_INTERVAL configuration option inside jaxl.ini
- XEP-0199 (XMPP Ping) can now automatically ping the connected server periodically for keeping connection alive on long running bots
(see echobot.php sample app for usage)
- Updated JAXLCron::add method to accept a number of arguments while adding bckgrnd jobs
These list of arguments is passed back to the application method
- Updated IQ handling inside XEP-0202 which wasn't returning iq stanza back resulting in no ping/pong
- Updated echobot to show usage of JAXL::discoItems and JAXL::discoInfo inside application code
- Added tagMap xpath for service identity and feature nodes in service discovery resultset
- JAXL core now auto includes XEP-0128 along with XEP-0030 on startup.
Also added two methods JAXL::discoItems and JAXL::discoInfo for service discovery
- Checking in first version of XEP-0128 (Service Discovery Extension)
- Fixed bug where message and presence stanza builder were not using passed id value as attribute
- Removed jaxl_pre_curl event hook which was only used internally by XEP-0124
- Jaxl now shutdown gracefully is encryption is required and openssl PHP module is not loaded in the environment
- For every registered callback on XMPP hooks, callback'd method will receive two params.
A payload and reference of Jaxl instance for whom XMPP event has occured.
Updated sample application code to use passed back Jaxl instance reference instead of global jaxl variable.
- As a library convention XEP's exposing user space configuration parameters via JAXL constructor SHOULD utilize JAXL::getConfigByPriority method
Added JAXL_TMP_PATH option inside jaxl.ini
- Jaxl::tmp is now Jaxl::tmpPath. Also added Jaxl config param to specify custom tmp path location
Jaxl client also self detect the IP of the host it is running upon (to be used by STUN/TURN utilities in Jingle negotitation)
- Removed JAXLUtil::includePath and JAXLUtil::getAppFilePath methods which are now redundant after removing jaxl.ini and jaxl.conf from lib core
- Removed global defines JAXL_BASE_PATH, JAXL_APP_BASE_PATH, JAXL_BOSH_APP_ABS_PATH from inside jaxl.ini (No more required by apps to specify these values)
- Removing env/jaxl.php and env/jaxl.conf (were required if you run your apps using `jaxl` command line utility)
Updated env/jaxl.ini so that projects can now directly include their app setting via jaxl.ini (before including core/jaxl.class.php)
- Added JAXL::bareJid public variable for usage inside applications.
XMPP base class now return bool on socket connect completion (used by PHPUnit test cases)
- Removing build.sh file from library for next release
Users should simply download, extract, include and write their app code without caring about the build script from 2.1.2 release
- As a library convention to include XEP's use JAXL::requires() method, while to include any core/ or xmpp/ base class use jaxl_require() method.
Updated library code and xep's to adhere to this convention.
Jaxl instance now provide a system specific /tmp folder location accessible by JAXL::tmp
- Removed JAXL_NAME and JAXL_VERSION constants.
Instead const variables are now defined per instance accessible by getName() and getVersion() methods.
Updated XEP-0030,0092,0115 to use the same
- Moved indivisual XEP's working parameter (0114,0124) from JAXL core class to XEP classes itself.
XEP's make use of JAXL::config array for parsing user options.
- Added JAXL_COMPONENT_PASS option inside jaxl.ini. Updated build.sh with new /app file paths.
Updated XEP-0114,0124,0206 to use array style configs as defined inside JAXL class
- Removed dependency upon jaxl.ini from all sample applications.
First checkin of sample sendMessage.php app.
- Config parameters for XEP's like 0114 and 0206 are now saved as an array inside JAXL class (later on they will be moved inside respective XEP's).
Added constructor config option to pre-choose an auth mechanism to be performed
if an auth mech is pre-chosen app files SHOULD not register callback for jaxl_get_auth_mech hook.
Bosh cookie settings can now be passed along with Jaxl constructor.
Added support for publishing vcard-temp:x:update node along with presence stanzas.
Jaxl instance can run in 3 modes a.k.a. stream,component and bosh mode
applications should use JAXL::startCore('mode') to configure instance for a specific mode.
- Removed redundant NS variable from inside XEP-0124
- Moved JAXLHTTPd setting defines inside the class (if gone missing CPU usage peaks to 100%)
- Added jaxl_httpd_pre_shutdown, jaxl_httpd_get_http_request, jaxl_httpd_get_sock_request event hooks inside JAXLHTTPd class
- Added JAXLS5B path (SOCKS5 implementation) inside jaxl_require method
- Removed all occurance of JAXL::$action variable from /core and /xep class files
- Updated boshChat and boshMUChat sample application which no longer user JAXL::$action variable inside application code
- Updated preFetchBOSH and preFetchXMPP sample example.
Application code don't need any JAXL::$action variable now
Neither application code need to define JAXL_BASE_PATH (optional from now on)
- JAXL core and XEP-0206 have no relation and dependency upon JAXL::$action variable now.
- Deprecated jaxl_get_body hook which was only for XEP-0124 working.
Also cleaned up XEP-0124 code by removing processBody method which is now handled inside preHandler itself.
- Defining JAXL_BASE_PATH inside application code made optional.
Developers can directly include /path/to/jaxl/core/jaxl.class.php and start writing applications.
Also added a JAXL::startCore() method (see usage in /app/preFetchXMPP.php).
Jaxl magic method for calling XEP methods now logs a warning inside jaxl.log if XEP doesn't exists in the environment
- Added tag map for XMPP message thread and subject child elements
- Fixed typo where in case of streamError proper description namespace was not parsed/displayed
- Disabled BOSH session close if application is running in boshOut=false mode
Suggested by MOVIM dev team who were experiencing loss of session data on end of script
- JAXL::log method 2nd parameter now defaults to logLevel=1 (passing 2nd param is now optional)
- Fixed XPath for iq stanza error condition and error NS extraction inside jaxl.parser.class
- First checkin of XEP-0184 Message Receipts
- Added support for usage of name() xpath function inside tag maps of JAXLXml class.
Also added some documentation for methods available inside JAXLXml class
- Fixed JAXLPlugin::remove method to properly remove and manage callback registry.
Also added some documentation for JAXLPlugin class methods
- Added JAXL contructor config option to disable BOSH module auto-output behaviour.
This is utilized inside app/preFetchBOSH.php sample example
- First checkin of sample application code pre-fetching XMPP/Jabber data for web page population using BOSH XEP
- Added a sample application file which can be used to pre-fetch XMPP/Jabber data for a webpage without using BOSH XEP or Ajax requests
As per the discussion on google groups (http://bit.ly/aKavZB) with MOVIM team
- JAXL library is now $jaxl independent, you can use anything like $var = new JAXL(); instance your applications now
JAXLUtil::encryptPassword now accepts username/password during SASL auth.
Previously it used to auto detect the same from JAXL instance, now core has to manually pass these param
- Added JAXL::startHTTPd method with appropriate docblock on how to convert Jaxl instance into a Jaxl socket (web) server.
Comments also explains how to still maintaining XMPP communication in the background
- Updated JAXLHTTPd class to use new constants inside jaxl.ini
- Added jaxl_get_stream_error event handler.
Registered callback methods also receive array form of received XMPP XML stanza
- Connecting Jaxl instance now fallback to default value 'localhost' for host,domain,boshHost,boshPort,boshSuffix
If these values are not configured either using jaxl.ini constants or constructor
- Provided a sendIQ method per JAXL instance.
Recommended that applications and XEP's should directly use this method for sending <iq/> type stanza
DONOT use XMPPSend methods inside your application code from here on
- Added configuration options for JAXL HTTPd server and JAXL Bosh Component Manager inside jaxl.ini
- Fixed type in XEP-0202 (Entity Time). XEP was not sending <iq/> id in response to get request
- Jaxl library is now phpdocs ready. Added extended documentation for JAXL core class, rest to be added
- All core classes inside core/, xmpp/ and xep/ folder now make use of jaxl->log method
JAXL Core constructor are now well prepared so that inclusion of jaxl.ini is now optional
Application code too should use jaxl->log instead of JAXLog::log method for logging purpose
- Reshuffled core instance paramaters between JAXL and XMPP class
Also Jaxl core now logs at level 1 instead of 0 (i.e. all logs goes inside jaxl.log and not on console)
- JAXL class now make use of endStream method inside XMPP base class while disconnecting.
Also XMPPSend::endStream now forces xmpp stanza delivery (escaping JAXL internal buffer)
http://code.google.com/p/jaxl/issues/detail?id=23
- Added endStream method inside XMPP base class and startSession,startBind methods inside XMPPSend class
XMPP::sendXML now accepts a $force parameter for escaping XMPP stanza's from JAXL internal buffer
- Updated the way Jaxl core calls XEP 0115 method (entity caps) to match documentation
XEP method's should accept jaxl instance as first paramater
- First checkin of PEP (Personal Eventing), User Location, User Mood, User Activity and User Tune XEP's
- Completed methods discoFeatures, discoNodes, discoNodeInfo, discoNodeMeta and discoNodeItems in PubSub XEP
- Hardcoded client category, type, lang and name. TODO: Make them configurable in future
- Cleaned up XEP 0030 (Service Discovery) and XEP 0115 (Entity Capabilities)
- Updated XMPP base class to use performance configuration parameters (now customizable with JAXL constructor)
- jaxl.conf will be removed from jaxl core in future, 1st step towards this goal
- Moved bulk of core configs from jaxl.conf
- Added more configuration options relating to client performance e.g. getPkts, getPktSize etc
- Fixed client mode by detecting sapi type instead of $_REQUEST['jaxl'] variable
- Now every implemented XEP should have an 'init' method which will accept only one parameter (jaxl instance itself)
- Jaxl core now converts transmitted stanza's into xmlentities (http://code.google.com/p/jaxl/issues/detail?id=22)
- Created a top level 'patch' folder which contains various patches sent by developers using 'git diff > patch' utility
- Fixed typo in namespace inside 0030 (thanks to Thomas Baquet for the patch)
- First checkin of PubSub XEP (untested)
- Indented build.sh and moved define's from top of JAXLHTTPd class to jaxl.ini
- Added JAXLHTTPd inside Jaxl core (a simple socket select server)
- Fixed sync of background iq and other stanza requests with browser ajax calls
- Updated left out methods in XMPP over BOSH xep to accept jaxl instance as first method
- All XEP methods available in application landspace, now accepts jaxl instance as first parameter. Updated core jaxl class magic method to handle the same.
If you are calling XEP methods as specified in the documentation, this change will not hurt your running applications
- Updated echobot sample application to utilize XEP 0054 (VCard Temp) and 0202 (Entity Time)
- First checkin of missing vcard-temp xep
- Added xmlentities JAXLUtil method
- Jaxl Parser now default parses xXmlns node for message stanzas
- Added PCRE_DOTALL and PCRE_MULTILINE pattern modifier for bosh unwrapBody method
- Added utility methods like urldecode, urlencode, htmlEntities, stripHTML and splitJid inside jaxl.js
- Updated sample application jaxl.ini to reflect changes in env/jaxl.ini
version 2.1.1
-------------
- Updated XMPPSend 'presence', 'message' and 'iq' methods to accept $jaxl instance as first parameter
if you are not calling these methods directly from your application code as mentioned in documentation
this change should not hurt you
- Added more comments to env/jaxl.ini and also added JAXL_LOG_ROTATE ini file option
- JAXL instance logs can be rotated every x seconds (logRotate config parameter) now
- Removed config param dumpTime, instead use dumpStat to specify stats dump period
- Base XMPP class now auto-flush output buffers filled because of library level rate limiter
- Added more options for JAXL constructor e.g.
boshHost, boshPort, boshSuffix, pidPath, logPath, logLevel, dumpStat, dumpTime
These param overwrites value specified inside jaxl.ini file
Also JAXL core will now periodically dump instance statistics
- Added an option in JAXL constructor to disable inbuild core rate limiter
- Added support when applications need to connect with external bosh endpoints
Bosh application code requires update for ->JAXL0206('startStream') method
- XMPPGet::handler replaces ->handler inside XEP-0124
- JAXLCron job now also passes connected instance to callback cron methods
- Updated base XMPP class now maintains a clock, updated sendXML method to respect library level rate limiting
- Base JAXL class now includes JAXLCron class for periodically dumping connected bot memory/usage stats
- First version of JAXLCron class for adding periodic jobs in the background
- XMPP payload handler moves from XMPPGet to base XMPP class, packets are then routed to XMPPGet class for further processing
- Updated xep-0124 to use instance bosh parameters instead of values defined inside jaxl.ini
- Provision to specify custom JAXL_BOSH_HOST inside jaxl.ini
- Instead of global logLevel and logPath, logger class now respects indivisual instance log settings
Helpful in multiple instance applications
- Updated base JAXL class to accept various other configuration parameters inside constructor
These param overwrites values defined inside jaxl.ini
- XMPPSend::xml method moves inside XMPP::sendXML (call using ->sendXML from within application code), as a part of library core cleanup
- Updated jaxl class to return back payload from called xep methods
- XMPP base method getXML can be instructed not to take a nap between stream reads
- Added jaxl_get_xml hook for taking control over incoming xml payload from xmpp stream
- Added support for disabling sig term registration, required by applications who already handle this in their core code
- Added capability of sending multiple message/presence stanza in one go inside jaxl base class
- Fixed typo in MUC Direct Invitation xep invite method
- getHandler should have accepted core instance by reference, fixed now. BOSH MUC Chat sample application header is now more appropriate
version 2.1.0
-------------
- First checkin of bosh MUC sample application
- Updated build file now packages bosh MUC chat sample application along with core classes
- Updated JAXLog class to accept instance inside log() method, application code should use ->log() to call JAXLog::log() method now
- Updated JAXLPlugin class to pass instance along with every XMPP event hook
- Updated jaxl_require method to call including XEP's init() method every time they are included using jaxl_require method
- Update jaxl.ini with some documentation/comments about JAXL_BOSH_COOKIE_DOMAIN parameter
- Updated echobot sample application code to pass instance while calling jaxl_require method
- Update XMPP SASL Auth class to accept instance while calculating SASL response.
Also passinginstance when jaxl_get_facebook_key hook is called
- Updated XMPP base class to accept component host name inside constructor.
Sending currentinstance with every XMPPSend, XMPPGet and JAXLog method calls
- Every XMPPGet method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Every XMPPSend method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Updated component bot sample application to show how to pass component host inside JAXL constructor.
Also updated jaxl_require call to accept current working instance
- Updated boshchat sample application to follow new rules of jaxl_require, also cleaned up the sample app code a bit
- Updated jaxl.ini of packaged sample applications to match /env/jaxl.ini
- Updated implemented XEP's init method to accept instance during initialization step
Send working instance with every XMPPSend method call
Almost every XEP's available method now accepts an additional instance so that XEP's can work independently for every instance inside a multiple jaxl instance application code
- Added magic method __call inside JAXL class
All application codes should now call a methods inside implemented XEP's like ->JAXLxxxx('method', , , ...)
Also added ->log method to be used by application codes
JAXLog::log() should not be called directly from application code
Updated XMPPSend methods to accept instance
Added ->requires() method that does a similar job as jaxl_require() which now also expects instance as one of the passed parameter.
version 2.0.4
-------------
- Updated XMPP base class and XMPP Get class to utilize new XMPPAuth class
- Updated jaxl_require method with new XMPPAuth class path
- Extracted XMPP SASL auth mechanism out of XMPP Get class, code cleanup
- unwrapBody method of XEP 0124 is now public
- Added #News block on top of README
- No more capital true, false, null inside Jaxl core to pass PHP_CodeSniffer tests
- :retab Jaxl library core to pass PHP_CodeSniffer tests
- Added Jabber Component Protocol example application bot
- Updated README with documentation link for Jabber component protocol
- Updated Entity Caps method to use list of passed feature list for verification code generation
- Updated MUC available methods doc link inside README
- Added experimental support for SCRAM-SHA-1, CRAM-MD5 and LOGIN auth mechanisms
version 2.0.3
-------------
- Updated Jaxl XML parsing class to handle multiple level nested child cases
- Updated README and bosh chat application with documentation link
- Fixed bosh application to run on localhost
- Added doc links inside echobot sample app
- Bosh sample application also use entity time XEP-0202 now
- Fix for sapi detection inside jaxl util
- jaxl.js updated to handle multiple ajax poll response payloads
- Bosh session manager now dumps ajax poll response on post handler callback
- Removed hardcoded ajax poll url inside boshchat application
- Updated component protocol XEP pre handshake event handling
version 2.0.2
-------------
- Packaged XEP 0202 (Entity Time)
- First checkin of Bosh related XEP 0124 and 0206
- Sample Bosh Chat example application
- Updated jaxl.class.php to save Bosh request action parameter
- jaxl.ini updated with Bosh related cookie options, default loglevel now set to 4
- jaxl.js checkin which should be used with bosh applications
- Updated base xmpp classes to provide integrated bosh support
- Outgoing presence and message stanza's too can include @id attribute now
version 2.0.1
-------------
- Typo fix in JAXLXml::$tagMap for errorCode
- Fix for handling overflooded roster list
- Packaged XEP 0115 (Entity capability) and XEP 0199 (XMPP Ping)
- Updated sample echobot to use XEP 0115 and XEP 0199
- Support for X-FACEBOOK-PLATFORM authentication
version 2.0.0
--------------
First checkin of:
- Restructed core library with event mechanism
- Packaged XEP 0004, 0030, 0045, 0050, 0085, 0092, 0114, 0133, 0249
- Sample echobot application
diff --git a/core/jaxl.class.php b/core/jaxl.class.php
index a1d4250..dd211ef 100644
--- a/core/jaxl.class.php
+++ b/core/jaxl.class.php
@@ -1,893 +1,905 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
declare(ticks=1);
// Set JAXL_BASE_PATH if not already defined by application code
if(!@constant('JAXL_BASE_PATH'))
define('JAXL_BASE_PATH', dirname(dirname(__FILE__)));
-
+
/**
* Autoload method for Jaxl library and it's applications
*
* @param string|array $classNames core class name required in PHP environment
* @param object $jaxl Jaxl object which require these classes. Optional but always required while including implemented XEP's in PHP environment
*/
function jaxl_require($classNames, $jaxl=false) {
static $included = array();
$tagMap = array(
// core classes
'JAXLBosh' => '/core/jaxl.bosh.php',
'JAXLCron' => '/core/jaxl.cron.php',
'JAXLHTTPd' => '/core/jaxl.httpd.php',
'JAXLog' => '/core/jaxl.logger.php',
'JAXLXml' => '/core/jaxl.parser.php',
'JAXLPlugin' => '/core/jaxl.plugin.php',
'JAXLUtil' => '/core/jaxl.util.php',
'JAXLS5B' => '/core/jaxl.s5b.php',
'JAXLException' => '/core/jaxl.exception.php',
'XML' => '/core/jaxl.xml.php',
// xmpp classes
'XMPP' => '/xmpp/xmpp.class.php',
'XMPPGet' => '/xmpp/xmpp.get.php',
'XMPPSend' => '/xmpp/xmpp.send.php',
'XMPPAuth' => '/xmpp/xmpp.auth.php'
);
if(!is_array($classNames)) $classNames = array('0'=>$classNames);
foreach($classNames as $key => $className) {
$xep = substr($className, 4, 4);
if(substr($className, 0, 4) == 'JAXL'
&& is_numeric($xep)
) { // is XEP
if(!isset($included[$className])) {
require_once JAXL_BASE_PATH.'/xep/jaxl.'.$xep.'.php';
$included[$className] = true;
}
call_user_func(array('JAXL'.$xep, 'init'), $jaxl);
} // is Core file
else if(isset($tagMap[$className])) {
require_once JAXL_BASE_PATH.$tagMap[$className];
$included[$className] = true;
}
}
return;
}
+ // cnt of connected instances
+ global $jaxl_instance_cnt;
+ $jaxl_instance_cnt = 0;
+
// Include core classes and xmpp base
jaxl_require(array(
'JAXLog',
'JAXLUtil',
'JAXLPlugin',
'JAXLCron',
'JAXLException',
'XML',
'XMPP',
));
- // number of running instance(s)
- global $jaxl_instance_cnt;
- $jaxl_instance_cnt = 1;
-
/**
* Jaxl class extending base XMPP class
*
* Jaxl library core is like any of your desktop Instant Messaging (IM) clients.
* Include Jaxl core in you application and start connecting and managing multiple XMPP accounts
* Packaged library is custom configured for running <b>single instance</b> Jaxl applications
*
* For connecting <b>multiple instance</b> XMPP accounts inside your application rewrite Jaxl controller
* using combination of env/jaxl.php, env/jaxl.ini and env/jaxl.conf
*/
class JAXL extends XMPP {
/**
* Client version of the connected Jaxl instance
*/
const version = '2.1.2';
/**
* Client name of the connected Jaxl instance
*/
const name = 'Jaxl :: Jabber XMPP Client Library';
/**
* Custom config passed to Jaxl constructor
*
* @var array
*/
var $config = array();
/**
* Username of connecting Jaxl instance
*
* @var string
*/
var $user = false;
/**
* Password of connecting Jaxl instance
*
* @var string
*/
var $pass = false;
/**
* Hostname for the connecting Jaxl instance
*
* @var string
*/
var $host = 'localhost';
/**
* Port for the connecting Jaxl instance
*
* @var integer
*/
var $port = 5222;
/**
* Full JID of the connected Jaxl instance
*
* @var string
*/
var $jid = false;
/**
* Bare JID of the connected Jaxl instance
*
* @var string
*/
var $bareJid = false;
/**
* Domain for the connecting Jaxl instance
*
* @var string
*/
var $domain = 'localhost';
/**
* Resource for the connecting Jaxl instance
*
* @var string
*/
var $resource = false;
/**
* Local cache of roster list and related info maintained by Jaxl instance
*/
var $roster = array();
/**
* Jaxl will track presence stanza's and update local $roster cache
*/
var $trackPresence = true;
/**
* Configure Jaxl instance to auto-accept subscription requests
*/
var $autoSubscribe = false;
/**
* Log Level of the connected Jaxl instance
*
* @var integer
*/
var $logLevel = 1;
/**
* Enable/Disable automatic log rotation for this Jaxl instance
*
* @var bool|integer
*/
var $logRotate = false;
/**
* Absolute path of log file for this Jaxl instance
*/
var $logPath = '/var/log/jaxl.log';
/**
* Absolute path of pid file for this Jaxl instance
*/
var $pidPath = '/var/run/jaxl.pid';
/**
* Enable/Disable shutdown callback on SIGH terms
*
* @var bool
*/
var $sigh = true;
/**
* Process Id of the connected Jaxl instance
*
* @var bool|integer
*/
var $pid = false;
/**
* Mode of the connected Jaxl instance (cgi or cli)
*
* @var bool|string
*/
var $mode = false;
/**
* Jabber auth mechanism performed by this Jaxl instance
*
* @var false|string
*/
var $authType = false;
/**
* Jaxl instance dumps usage statistics periodically. Disabled if set to "false"
*
* @var bool|integer
*/
var $dumpStat = 300;
/**
* List of XMPP feature supported by this Jaxl instance
*
* @var array
*/
var $features = array();
/**
* XMPP entity category for the connected Jaxl instance
*
* @var string
*/
var $category = 'client';
/**
* XMPP entity type for the connected Jaxl instance
*
* @var string
*/
var $type = 'bot';
/**
* Default language of the connected Jaxl instance
*/
var $lang = 'en';
/**
* Location to system temporary folder
*/
var $tmpPath = null;
/**
* IP address of the host Jaxl instance is running upon.
* To be used by STUN client implementations.
*/
var $ip = null;
/**
* PHP OpenSSL module info
*/
var $openSSL = false;
+ var $instances = false;
+
/**
* @return string $name Returns name of this Jaxl client
*/
function getName() {
return JAXL::name;
}
/**
* @return float $version Returns version of this Jaxl client
*/
function getVersion() {
return JAXL::version;
}
/**
* Discover items
*/
function discoItems($jid, $callback, $node=false) {
$this->JAXL0030('discoItems', $jid, $this->jid, $callback, $node);
}
/**
* Discover info
*/
function discoInfo($jid, $callback, $node=false) {
$this->JAXL0030('discoInfo', $jid, $this->jid, $callback, $node);
}
/**
* Shutdown Jaxl instance cleanly
*
* shutdown method is auto invoked when Jaxl instance receives a SIGH term.
* Before cleanly shutting down this method callbacks registered using <b>jaxl_pre_shutdown</b> hook.
*
* @param mixed $signal This is passed as paramater to callbacks registered using <b>jaxl_pre_shutdown</b> hook
*/
function shutdown($signal=false) {
$this->log("[[JAXL]] Shutting down ...");
$this->executePlugin('jaxl_pre_shutdown', $signal);
if($this->stream) $this->endStream();
$this->stream = false;
}
/**
* Perform authentication for connecting Jaxl instance
*
* @param string $type Authentication mechanism to proceed with. Supported auth types are:
* - DIGEST-MD5
* - PLAIN
* - X-FACEBOOK-PLATFORM
* - ANONYMOUS
*/
function auth($type) {
$this->authType = $type;
return XMPPSend::startAuth($this);
}
/**
* Set status of the connected Jaxl instance
*
* @param bool|string $status
* @param bool|string $show
* @param bool|integer $priority
* @param bool $caps
*/
function setStatus($status=false, $show=false, $priority=false, $caps=false, $vcard=false) {
$child = array();
$child['status'] = ($status === false ? 'Online using Jaxl library http://code.google.com/p/jaxl' : $status);
$child['show'] = ($show === false ? 'chat' : $show);
$child['priority'] = ($priority === false ? 1 : $priority);
if($caps) $child['payload'] = $this->JAXL0115('getCaps', $this->features);
if($vcard) $child['payload'] .= $this->JAXL0153('getUpdateData', false);
return XMPPSend::presence($this, false, false, $child, false);
}
/**
* Send authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send authorization request
*/
function subscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribe');
}
/**
* Accept authorization request from $toJid
*
* @param string $toJid JID who's authorization request Jaxl instance wants to accept
*/
function subscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribed');
}
/**
* Send cancel authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send cancel authorization request
*/
function unsubscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribe');
}
/**
* Accept cancel authorization request from $toJid
*
* @param string $toJid JID who's cancel authorization request Jaxl instance wants to accept
*/
function unsubscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribed');
}
/**
* Retrieve connected Jaxl instance roster list from the server
*
* @param mixed $callback Method to be callback'd when roster list is received from the server
*/
function getRosterList($callback=false) {
$payload = '<query xmlns="jabber:iq:roster"/>';
if($callback === false) $callback = array($this, '_handleRosterList');
return XMPPSend::iq($this, "get", $payload, false, $this->jid, $callback);
}
/**
* Add a new jabber account in connected Jaxl instance roster list
*
* @param string $jid JID to be added in the roster list
* @param string $group Group name
* @param bool|string $name Name of JID to be added
*/
function addRoster($jid, $group, $name=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Update subscription of a jabber account in roster list
*
* @param string $jid JID to be updated inside roster list
* @param string $group Updated group name
* @param bool|string $subscription Updated subscription type
*/
function updateRoster($jid, $group, $name=false, $subscription=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
if($subscription) $payload .= ' subscription="'.$subscription.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Delete a jabber account from roster list
*
* @param string $jid JID to be removed from the roster list
*/
function deleteRoster($jid) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'" subscription="remove">';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Send an XMPP message
*
* @param string $to JID to whom message is sent
* @param string $message Message to be sent
* @param string $from (Optional) JID from whom this message should be sent
* @param string $type (Optional) Type of message stanza to be delivered
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessage($to, $message, $from=false, $type='chat', $id=false) {
$child = array();
$child['body'] = $message;
return XMPPSend::message($this, $to, $from, $child, $type, $id);
}
/**
* Send multiple XMPP messages in one go
*
* @param array $to array of JID's to whom this presence stanza should be send
* @param array $from (Optional) array of JID from whom this presence stanza should originate
* @param array $child (Optional) array of arrays specifying child objects of the stanza
* @param array $type (Optional) array of type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessages($to, $from=false, $child=false, $type='chat', $id=false) {
return XMPPSend::message($this, $to, $from, $child, $type);
}
/**
* Send an XMPP presence stanza
*
* @param string $to (Optional) JID to whom this presence stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param array $child (Optional) array specifying child objects of the stanza
* @param string $type (Optional) Type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendPresence($to=false, $from=false, $child=false, $type=false, $id=false) {
return XMPPSend::presence($this, $to, $from, $child, $type, $id);
}
/**
* Send an XMPP iq stanza
*
* @param string $type Type of iq stanza to send
* @param string $payload (Optional) XML string to be transmitted
* @param string $to (Optional) JID to whom this iq stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param string|array $callback (Optional) Callback method which will handle "result" type stanza rcved
* @param integer $id (Optional) Add an id attribute to transmitted stanza (auto-generated if not provided)
*/
function sendIQ($type, $payload=false, $to=false, $from=false, $callback=false, $id=false) {
return XMPPSend::iq($this, $type, $payload, $to, $from, $callback, $id);
}
/**
* Logs library core and application debug data into the log file
*
* @param string $log Datum to be logged
* @param integer $level Log level for passed datum
*/
function log($log, $level=1) {
JAXLog::log($log, $level, $this);
}
/**
* Instead of using jaxl_require method applications can use $jaxl->requires to include XEP's in PHP environment
*
* @param string $class Class name of the XEP to be included e.g. JAXL0045 for including XEP-0045 a.k.a. Multi-user chat
*/
function requires($class) {
jaxl_require($class, $this);
}
/**
* Use this method instead of JAXLPlugin::add to register a callback for connected instance only
*/
function addPlugin($hook, $callback, $priority=10) {
JAXLPlugin::add($hook, $callback, $priority, $this->uid);
}
/**
* Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
*/
function removePlugin($hook, $callback, $priority=10) {
JAXLPlugin::remove($hook, $callback, $priority, $this->uid);
}
/**
* Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
*/
function executePlugin($hook, $payload) {
return JAXLPlugin::execute($hook, $payload, $this);
}
+ function addCore($jaxl) {
+ $jaxl->addPlugin('jaxl_post_connect', array($jaxl, 'startStream'));
+ $jaxl->connect();
+ $this->instances['jaxl'][] = $jaxl;
+ }
+
/**
* Starts Jaxl Core
*
* This method should be called after Jaxl initialization and hook registration inside your application code
* Optionally, you can pass 'jaxl_post_connect' and 'jaxl_get_auth_mech' response type directly to this method
* In that case application code SHOULD NOT register callbacks to above mentioned hooks
*
* @param string $arg[0] Optionally application code can pre-choose what Jaxl core should do after establishing socket connection.
* Following are the valid options:
* a) startStream
* b) startComponent
* c) startBosh
*/
function startCore($mode=false) {
if($mode) {
switch($mode) {
case 'stream':
$this->addPlugin('jaxl_post_connect', array($this, 'startStream'));
break;
case 'component':
$this->addPlugin('jaxl_post_connect', array($this, 'startComponent'));
break;
case 'bosh':
$this->startBosh();
break;
default:
break;
}
}
if($this->mode == 'cli') {
try {
if($this->connect()) {
while($this->stream) {
$this->getXML();
}
}
}
catch(JAXLException $e) {
die($e->getMessage());
}
/* Exit Jaxl after end of loop */
exit;
}
}
/**
* Starts a socket server at 127.0.0.1:port
*
* startHTTPd converts Jaxl instance into a Jaxl socket server (may or may not be a HTTP server)
* Same Jaxl socket server instance <b>SHOULD NOT</b> be used for XMPP communications.
* Instead separate "new Jaxl();" instances should be created for such XMPP communications.
*
* @param integer $port Port at which to start the socket server
* @param integer $maxq JAXLHTTPd socket server max queue
*/
function startHTTPd($port, $maxq) {
JAXLHTTPd::start(array(
'port' => $port,
'maxq' => $maxq
));
}
/**
* Start instance in bosh mode
*/
function startBosh() {
$this->JAXL0206('startStream');
}
/**
* Start instance in component mode
*/
function startComponent($payload, $jaxl) {
$this->JAXL0114('startStream', $payload);
}
/**
* Jaxl core constructor
*
* Jaxl instance configures itself using the constants inside your application jaxl.ini.
* However, passed array of configuration options overrides the value inside jaxl.ini.
* If no configuration are found or passed for a particular value,
* Jaxl falls back to default config options.
*
* @param $config Array of configuration options
* @todo Use DNS SRV lookup to set $jaxl->host from provided domain info
*/
function __construct($config=array()) {
global $jaxl_instance_cnt;
parent::__construct($config);
- $this->uid = $jaxl_instance_cnt++;
+ $this->uid = ++$jaxl_instance_cnt;
$this->ip = gethostbyname(php_uname('n'));
$this->mode = (PHP_SAPI == "cli") ? PHP_SAPI : "cgi";
$this->config = $config;
$this->pid = getmypid();
/* Mandatory params to be supplied either by jaxl.ini constants or constructor $config array */
$this->user = $this->getConfigByPriority(@$config['user'], "JAXL_USER_NAME", $this->user);
$this->pass = $this->getConfigByPriority(@$config['pass'], "JAXL_USER_PASS", $this->pass);
$this->domain = $this->getConfigByPriority(@$config['domain'], "JAXL_HOST_DOMAIN", $this->domain);
$this->bareJid = $this->user."@".$this->domain;
/* Optional params if not configured using jaxl.ini or $config take default values */
$this->host = $this->getConfigByPriority(@$config['host'], "JAXL_HOST_NAME", $this->domain);
$this->port = $this->getConfigByPriority(@$config['port'], "JAXL_HOST_PORT", $this->port);
$this->resource = $this->getConfigByPriority(@$config['resource'], "JAXL_USER_RESC", "jaxl.".$this->uid.".".$this->clocked);
$this->logLevel = $this->getConfigByPriority(@$config['logLevel'], "JAXL_LOG_LEVEL", $this->logLevel);
$this->logRotate = $this->getConfigByPriority(@$config['logRotate'], "JAXL_LOG_ROTATE", $this->logRotate);
$this->logPath = $this->getConfigByPriority(@$config['logPath'], "JAXL_LOG_PATH", $this->logPath);
if(!file_exists($this->logPath) && !touch($this->logPath)) throw new JAXLException("Log file ".$this->logPath." doesn't exists");
$this->pidPath = $this->getConfigByPriority(@$config['pidPath'], "JAXL_PID_PATH", $this->pidPath);
if($this->mode == "cli" && !file_exists($this->pidPath) && !touch($this->pidPath)) throw new JAXLException("Pid file ".$this->pidPath." doesn't exists");
/* Resolve temporary folder path */
if(function_exists('sys_get_temp_dir')) $this->tmpPath = sys_get_temp_dir();
$this->tmpPath = $this->getConfigByPriority(@$config['tmpPath'], "JAXL_TMP_PATH", $this->tmpPath);
if($this->tmpPath && !file_exists($this->tmpPath)) throw new JAXLException("Tmp directory ".$this->tmpPath." doesn't exists");
/* Handle pre-choosen auth type mechanism */
$this->authType = $this->getConfigByPriority(@$config['authType'], "JAXL_AUTH_TYPE", $this->authType);
if($this->authType) $this->addPlugin('jaxl_get_auth_mech', array($this, 'doAuth'));
/* Presence handling */
$this->trackPresence = isset($config['trackPresence']) ? $config['trackPresence'] : true;
$this->autoSubscribe = isset($config['autoSubscribe']) ? $config['autoSubscribe'] : false;
$this->addPlugin('jaxl_get_presence', array($this, '_handlePresence'), 0);
/* Optional params which can be configured only via constructor $config */
$this->sigh = isset($config['sigh']) ? $config['sigh'] : true;
$this->dumpStat = isset($config['dumpStat']) ? $config['dumpStat'] : 300;
/* Configure instance for platforms */
$this->configure($config);
$this->xml = new XML();
/* Initialize JAXLCron and register instance cron jobs */
JAXLCron::init($this);
if($this->dumpStat) JAXLCron::add(array($this, 'dumpStat'), $this->dumpStat);
if($this->logRotate) JAXLCron::add(array('JAXLog', 'logRotate'), $this->logRotate);
- // include service discovery XEP-0030 and it's extensions, recommended for every XMPP entity
+ /* include service discovery XEP-0030 and it's extensions, recommended for every XMPP entity */
$this->requires(array(
'JAXL0030',
'JAXL0128'
));
+
+ /* add to instance */
+ if($jaxl_instance_cnt == 1) $this->instances = array('jaxl'=>array());
+ $this->instances['jaxl'][] = $this;
}
/**
* Return Jaxl instance config param depending upon user choice and default values
*/
function getConfigByPriority($config, $constant, $default) {
return ($config === null) ? (@constant($constant) === null ? $default : constant($constant)) : $config;
}
/**
* Configures Jaxl instance to run across various platforms (*nix/windows)
*
* Configure method tunes connecting Jaxl instance for
* OS compatibility, SSL support and dependencies over PHP methods
*/
protected function configure() {
// register shutdown function
if(!JAXLUtil::isWin() && JAXLUtil::pcntlEnabled() && $this->sigh) {
pcntl_signal(SIGTERM, array($this, "shutdown"));
pcntl_signal(SIGINT, array($this, "shutdown"));
$this->log("[[JAXL]] Registering callbacks for CTRL+C and kill.", 4);
}
else {
$this->log("[[JAXL]] No callbacks registered for CTRL+C and kill.", 4);
}
// check Jaxl dependency on PHP extension in cli mode
if($this->mode == "cli") {
if(($this->openSSL = JAXLUtil::sslEnabled()))
$this->log("[[JAXL]] OpenSSL extension is loaded.", 4);
else
$this->log("[[JAXL]] OpenSSL extension not loaded.", 4);
if(!function_exists('fsockopen'))
throw new JAXLException("[[JAXL]] Requires fsockopen method");
if(@is_writable($this->pidPath))
file_put_contents($this->pidPath, $this->pid);
}
// check Jaxl dependency on PHP extension in cgi mode
if($this->mode == "cgi") {
if(!function_exists('curl_init'))
throw new JAXLException("[[JAXL]] Requires CURL PHP extension");
if(!function_exists('json_encode'))
throw new JAXLException("[[JAXL]] Requires JSON PHP extension.");
}
}
/**
* Dumps Jaxl instance usage statistics
*
* Jaxl instance periodically calls this methods every JAXL::$dumpStat seconds.
*/
function dumpStat() {
$stat = "[[JAXL]] Memory:".round(memory_get_usage()/pow(1024,2), 2)."Mb";
if(function_exists('memory_get_peak_usage')) $stat .= ", PeakMemory:".round(memory_get_peak_usage()/pow(1024,2), 2)."Mb";
$stat .= ", obuffer: ".strlen($this->obuffer);
$stat .= ", buffer: ".strlen($this->buffer);
$stat .= ", RcvdRate: ".$this->totalRcvdSize/$this->clock."Kb";
$stat .= ", SentRate: ".$this->totalSentSize/$this->clock."Kb";
$this->log($stat, 1);
}
/**
* Magic method for calling XEP's included by the JAXL instance
*
* Application <b>should never</b> call an XEP method directly using <code>JAXL0045::joinRoom()</code>
* instead use <code>$jaxl->JAXL0045('joinRoom', $param1, ..)</code> to call methods provided by included XEP's
*
* @param string $xep XMPP extension (XEP) class name e.g. JAXL0045 for XEP-0045 a.k.a. Multi-User chat extension
* @param array $param Array of parameters where $param[0]='methodName' is the method called inside JAXL0045 class
*
* @return mixed $return Return value of called XEP method
*/
function __call($xep, $param) {
$method = array_shift($param);
array_unshift($param, $this);
if(substr($xep, 0, 4) == 'JAXL') {
$xep = substr($xep, 4, 4);
if(is_numeric($xep)
&& class_exists('JAXL'.$xep)
) { return call_user_func_array(array('JAXL'.$xep, $method), $param); }
else { $this->log("[[JAXL]] JAXL$xep Doesn't exists in the environment"); }
}
}
/**
* Perform pre-choosen auth type for the Jaxl instance
*/
function doAuth($mechanism) {
return XMPPSend::startAuth($this);
}
/**
* Adds a node (if doesn't exists) for $jid inside local $roster cache
*/
function _addRosterNode($jid, $inRoster=true) {
if(!isset($this->roster[$jid]))
$this->roster[$jid] = array(
'groups'=>array(),
'name'=>'',
'subscription'=>'',
'presence'=>array(),
'inRoster'=>$inRoster
);
return;
}
/**
* Core method that accepts retrieved roster list and manage local cache
*/
function _handleRosterList($payload, $jaxl) {
if(@is_array($payload['queryItemJid'])) {
foreach($payload['queryItemJid'] as $key=>$jid) {
$this->_addRosterNode($jid);
$this->roster[$jid]['groups'] = @$payload['queryItemGrp'][$key];
$this->roster[$jid]['name'] = @$payload['queryItemName'][$key];
$this->roster[$jid]['subscription'] = @$payload['queryItemSub'][$key];
}
}
else {
$jid = @$payload['queryItemJid'];
$this->_addRosterNode($jid);
$this->roster[$jid]['groups'] = @$payload['queryItemGrp'];
$this->roster[$jid]['name'] = @$payload['queryItemName'];
$this->roster[$jid]['subscription'] = @$payload['queryItemSub'];
}
$this->executePlugin('jaxl_post_roster_update', $payload);
return $payload;
}
/**
* Tracks all incoming presence stanza's
*/
function _handlePresence($payloads, $jaxl) {
foreach($payloads as $payload) {
if($this->trackPresence) {
// update local $roster cache
$jid = JAXLUtil::getBareJid($payload['from']);
$this->_addRosterNode($jid, false);
if(!isset($this->roster[$jid]['presence'][$payload['from']])) $this->roster[$jid]['presence'][$payload['from']] = array();
$this->roster[$jid]['presence'][$payload['from']]['type'] = $payload['type'] == '' ? 'available' : $payload['type'];
$this->roster[$jid]['presence'][$payload['from']]['status'] = $payload['status'];
$this->roster[$jid]['presence'][$payload['from']]['show'] = $payload['show'];
$this->roster[$jid]['presence'][$payload['from']]['priority'] = $payload['priority'];
}
if($payload['type'] == 'subscribe'
&& $this->autoSubscribe
) {
$this->subscribed($payload['from']);
$this->subscribe($payload['from']);
$this->executePlugin('jaxl_post_subscription_request', $payload);
}
else if($payload['type'] == 'subscribed') {
$this->executePlugin('jaxl_post_subscription_accept', $payload);
}
}
return $payloads;
}
}
?>
diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index ba9b637..395f551 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,482 +1,489 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
var $streamBlocking = 1;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
/**
* Instance start time
*/
var $startTime = false;
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
/**
* Maximum rate at which XMPP stanza's can flow out
*/
var $sendRate = false;
/**
* Size of each packet to be read from the socket
*/
var $getPktSize = false;
/**
- * Pkt count and sizes
+ * Read select timeouts
+ */
+ var $getSelectSecs = 5;
+ var $getSelectUsecs = 0;
+
+ /**
+ * Packet count and sizes
*/
var $totalRcvdPkt = 0;
var $totalRcvdSize = 0;
var $totalSentPkt = 0;
var $totalSentSize = 0;
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
$this->clocked = $this->startTime = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
$this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 4096;
$this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : .4;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
$this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
$this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
$this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
$this->executePlugin('jaxl_post_connect', $ret);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = $this->executePlugin('jaxl_get_id', ++$this->lastid);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
* $option = null (read until data is available)
* $option = integer (read for so many seconds)
*/
- function getXML($option=5) {
- // prepare streams to select
- $stream = array(); $jaxls = array($this);
- $jaxls = $this->executePlugin('jaxl_pre_get_xml_stream', $jaxls);
- foreach($jaxls as $jaxl) $streams[] = $jaxl->stream;
- $read = $streams;
+ function getXML() {
+ // prepare select streams
+ $streams = array(); $jaxls = $this->instances['jaxl'];
+ foreach($jaxls as $cnt=>$jaxl) {
+ if($jaxl->stream) $streams[$cnt] = $jaxl->stream;
+ else unset($jaxls[$cnt]);
+ }
// get num changed streams
- $write = null; $except = null; $secs = $option; $usecs = 0;
+ $read = $streams; $write = null; $except = null; $secs = $this->getSelectSecs; $usecs = $this->getSelectUsecs;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPGet]] \nError while reading packet from stream", 5);
}
else {
$this->log("[[XMPPGet]] $changed streams ready for read out of total ".sizeof($streams)." streams", 7);
if($changed == 0) $now = $this->clocked+$secs;
else $now = time();
foreach($read as $k=>$r) {
// get jaxl instance we are dealing with
$ret = $payload = '';
$key = array_search($r, $streams);
$jaxl = $jaxls[$key];
unset($jaxls[$key]);
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
}
// reload pending buffer
$payload = $jaxl->buffer;
$jaxl->buffer = '';
// read stream
$ret = @fread($jaxl->stream, $jaxl->getPktSize);
$jaxl->log("[[XMPPGet]] \n".$ret, 4);
$jaxl->totalRcvdSize = strlen($ret);
$ret = $jaxl->executePlugin('jaxl_get_xml', $ret);
$payload .= $ret;
// route packets
$jaxl->handler($payload);
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
foreach($jaxls as $jaxl) {
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
$payload = $jaxl->executePlugin('jaxl_get_xml', '');
}
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
}
unset($jaxls, $streams);
return $changed;
}
/**
* Send XMPP XML packet over connected stream
*/
function sendXML($xml='', $force=false) {
$xml = $this->executePlugin('jaxl_send_xml', $xml);
if($this->mode == "cgi") {
$this->executePlugin('jaxl_send_body', $xml);
}
else {
$currSendRate = ($this->totalSentSize/(JAXLUtil::getTime()-$this->lastSendTime))/1000000;
$this->obuffer .= $xml;
if($this->rateLimit
&& !$force
&& $this->lastSendTime
&& ($currSendRate > $this->sendRate)
) {
$this->log("[[XMPPSend]] rateLimit\nBufferSize:".strlen($this->obuffer).", maxSendRate:".$this->sendRate.", currSendRate:".$currSendRate, 5);
return 0;
}
$xml = $this->obuffer;
$this->obuffer = '';
return ($xml == '') ? 0 : $this->_sendXML($xml);
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
if($this->stream && $xml != '') {
$read = array(); $write = array($this->stream); $except = array();
$secs = null; $usecs = null;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPSend]] \nError while trying to send packet", 5);
throw new JAXLException("[[XMPPSend]] \nError while trying to send packet");
return 0;
}
else if($changed > 0) {
$this->lastSendTime = JAXLUtil::getTime();
$xmls = JAXLUtil::splitXML($xml);
$pktCnt = count($xmls);
$this->totalSentPkt += $pktCnt;
$ret = @fwrite($this->stream, $xml);
$this->totalSentSize += $ret;
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
return $ret;
}
else {
$this->log("[[XMPPSend]] Failed\n".$xml);
throw new JAXLException("[[XMPPSend]] \nFailed");
return 0;
}
}
else if($xml == '') {
$this->log("[[XMPPSend]] Tried to send an empty stanza, not processing", 1);
return 0;
}
else {
$this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
return 0;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
if($payload == '' && $this->mode == 'cli') return '';
$payload = $this->executePlugin('jaxl_pre_handler', $payload);
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
$this->totalRcvdPkt += $pktCnt;
$buffer = array();
foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
$this->buffer .= $xml;
break;
}
}
if(substr($xml, 0, 7) == '<stream') $arr = $this->xml->xmlize($xml);
else $arr = JAXLXml::parse($xml);
if($arr === false) { $this->buffer .= $xml; continue; }
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
$jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
unset($buffer);
$this->executePlugin('jaxl_post_handler', $payload);
return $payload;
}
}
?>
|
jaxl/JAXL | fa862cb8d2377e77d443713837a4740dcbe40f3c | Removed debug log code | diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index 08c7543..ba9b637 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,483 +1,482 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
var $streamBlocking = 1;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
/**
* Instance start time
*/
var $startTime = false;
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
/**
* Maximum rate at which XMPP stanza's can flow out
*/
var $sendRate = false;
/**
* Size of each packet to be read from the socket
*/
var $getPktSize = false;
/**
* Pkt count and sizes
*/
var $totalRcvdPkt = 0;
var $totalRcvdSize = 0;
var $totalSentPkt = 0;
var $totalSentSize = 0;
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
$this->clocked = $this->startTime = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
$this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 4096;
$this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : .4;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
$this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
$this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
$this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
$this->executePlugin('jaxl_post_connect', $ret);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = $this->executePlugin('jaxl_get_id', ++$this->lastid);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
* $option = null (read until data is available)
* $option = integer (read for so many seconds)
*/
function getXML($option=5) {
// prepare streams to select
$stream = array(); $jaxls = array($this);
$jaxls = $this->executePlugin('jaxl_pre_get_xml_stream', $jaxls);
foreach($jaxls as $jaxl) $streams[] = $jaxl->stream;
$read = $streams;
// get num changed streams
$write = null; $except = null; $secs = $option; $usecs = 0;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPGet]] \nError while reading packet from stream", 5);
}
else {
$this->log("[[XMPPGet]] $changed streams ready for read out of total ".sizeof($streams)." streams", 7);
if($changed == 0) $now = $this->clocked+$secs;
else $now = time();
foreach($read as $k=>$r) {
// get jaxl instance we are dealing with
$ret = $payload = '';
$key = array_search($r, $streams);
$jaxl = $jaxls[$key];
unset($jaxls[$key]);
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
}
// reload pending buffer
$payload = $jaxl->buffer;
$jaxl->buffer = '';
// read stream
$ret = @fread($jaxl->stream, $jaxl->getPktSize);
$jaxl->log("[[XMPPGet]] \n".$ret, 4);
$jaxl->totalRcvdSize = strlen($ret);
$ret = $jaxl->executePlugin('jaxl_get_xml', $ret);
$payload .= $ret;
// route packets
$jaxl->handler($payload);
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
foreach($jaxls as $jaxl) {
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
$payload = $jaxl->executePlugin('jaxl_get_xml', '');
}
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
}
unset($jaxls, $streams);
return $changed;
}
/**
* Send XMPP XML packet over connected stream
*/
function sendXML($xml='', $force=false) {
$xml = $this->executePlugin('jaxl_send_xml', $xml);
if($this->mode == "cgi") {
$this->executePlugin('jaxl_send_body', $xml);
}
else {
$currSendRate = ($this->totalSentSize/(JAXLUtil::getTime()-$this->lastSendTime))/1000000;
$this->obuffer .= $xml;
if($this->rateLimit
&& !$force
&& $this->lastSendTime
&& ($currSendRate > $this->sendRate)
) {
$this->log("[[XMPPSend]] rateLimit\nBufferSize:".strlen($this->obuffer).", maxSendRate:".$this->sendRate.", currSendRate:".$currSendRate, 5);
return 0;
}
$xml = $this->obuffer;
$this->obuffer = '';
- if($currSendRate > $this->sendRate) echo $can.PHP_EOL;
return ($xml == '') ? 0 : $this->_sendXML($xml);
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
if($this->stream && $xml != '') {
$read = array(); $write = array($this->stream); $except = array();
$secs = null; $usecs = null;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPSend]] \nError while trying to send packet", 5);
throw new JAXLException("[[XMPPSend]] \nError while trying to send packet");
return 0;
}
else if($changed > 0) {
$this->lastSendTime = JAXLUtil::getTime();
$xmls = JAXLUtil::splitXML($xml);
$pktCnt = count($xmls);
$this->totalSentPkt += $pktCnt;
$ret = @fwrite($this->stream, $xml);
$this->totalSentSize += $ret;
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
return $ret;
}
else {
$this->log("[[XMPPSend]] Failed\n".$xml);
throw new JAXLException("[[XMPPSend]] \nFailed");
return 0;
}
}
else if($xml == '') {
$this->log("[[XMPPSend]] Tried to send an empty stanza, not processing", 1);
return 0;
}
else {
$this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
return 0;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
if($payload == '' && $this->mode == 'cli') return '';
$payload = $this->executePlugin('jaxl_pre_handler', $payload);
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
$this->totalRcvdPkt += $pktCnt;
$buffer = array();
foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
$this->buffer .= $xml;
break;
}
}
if(substr($xml, 0, 7) == '<stream') $arr = $this->xml->xmlize($xml);
else $arr = JAXLXml::parse($xml);
if($arr === false) { $this->buffer .= $xml; continue; }
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
$jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
unset($buffer);
$this->executePlugin('jaxl_post_handler', $payload);
return $payload;
}
}
?>
|
jaxl/JAXL | 7c6dd0e6594173f33acb26d348dcbacf05d0f799 | Fixed typo in core for bosh related application files | diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index e0e0abb..08c7543 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,480 +1,483 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
var $streamBlocking = 1;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
/**
* Instance start time
*/
var $startTime = false;
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
/**
* Maximum rate at which XMPP stanza's can flow out
*/
var $sendRate = false;
/**
* Size of each packet to be read from the socket
*/
var $getPktSize = false;
/**
* Pkt count and sizes
*/
var $totalRcvdPkt = 0;
var $totalRcvdSize = 0;
var $totalSentPkt = 0;
var $totalSentSize = 0;
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
$this->clocked = $this->startTime = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
$this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 4096;
$this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : .4;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
$this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
$this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
$this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
$this->executePlugin('jaxl_post_connect', $ret);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = $this->executePlugin('jaxl_get_id', ++$this->lastid);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
* $option = null (read until data is available)
* $option = integer (read for so many seconds)
*/
function getXML($option=5) {
// prepare streams to select
$stream = array(); $jaxls = array($this);
$jaxls = $this->executePlugin('jaxl_pre_get_xml_stream', $jaxls);
foreach($jaxls as $jaxl) $streams[] = $jaxl->stream;
$read = $streams;
// get num changed streams
$write = null; $except = null; $secs = $option; $usecs = 0;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPGet]] \nError while reading packet from stream", 5);
}
else {
$this->log("[[XMPPGet]] $changed streams ready for read out of total ".sizeof($streams)." streams", 7);
if($changed == 0) $now = $this->clocked+$secs;
else $now = time();
foreach($read as $k=>$r) {
// get jaxl instance we are dealing with
$ret = $payload = '';
$key = array_search($r, $streams);
$jaxl = $jaxls[$key];
unset($jaxls[$key]);
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
}
// reload pending buffer
$payload = $jaxl->buffer;
$jaxl->buffer = '';
// read stream
$ret = @fread($jaxl->stream, $jaxl->getPktSize);
$jaxl->log("[[XMPPGet]] \n".$ret, 4);
$jaxl->totalRcvdSize = strlen($ret);
$ret = $jaxl->executePlugin('jaxl_get_xml', $ret);
$payload .= $ret;
// route packets
$jaxl->handler($payload);
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
foreach($jaxls as $jaxl) {
// update clock
if($now > $jaxl->clocked) {
$jaxl->clock += $now-$jaxl->clocked;
$jaxl->clocked = $now;
$payload = $jaxl->executePlugin('jaxl_get_xml', '');
}
// clear buffer
if($jaxl->obuffer != '') $jaxl->sendXML();
}
}
unset($jaxls, $streams);
return $changed;
}
/**
* Send XMPP XML packet over connected stream
*/
function sendXML($xml='', $force=false) {
- $currSendRate = ($this->totalSentSize/(JAXLUtil::getTime()-$this->lastSendTime))/1000000;
- if($this->mode == "cgi") { $this->executePlugin('jaxl_send_body', $xml); }
+ $xml = $this->executePlugin('jaxl_send_xml', $xml);
+ if($this->mode == "cgi") {
+ $this->executePlugin('jaxl_send_body', $xml);
+ }
else {
+ $currSendRate = ($this->totalSentSize/(JAXLUtil::getTime()-$this->lastSendTime))/1000000;
$this->obuffer .= $xml;
+
if($this->rateLimit
&& !$force
&& $this->lastSendTime
&& ($currSendRate > $this->sendRate)
) {
$this->log("[[XMPPSend]] rateLimit\nBufferSize:".strlen($this->obuffer).", maxSendRate:".$this->sendRate.", currSendRate:".$currSendRate, 5);
return 0;
}
$xml = $this->obuffer;
$this->obuffer = '';
if($currSendRate > $this->sendRate) echo $can.PHP_EOL;
- $xml = $this->executePlugin('jaxl_send_xml', $xml);
return ($xml == '') ? 0 : $this->_sendXML($xml);
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
if($this->stream && $xml != '') {
$read = array(); $write = array($this->stream); $except = array();
$secs = null; $usecs = null;
if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPSend]] \nError while trying to send packet", 5);
throw new JAXLException("[[XMPPSend]] \nError while trying to send packet");
return 0;
}
else if($changed > 0) {
$this->lastSendTime = JAXLUtil::getTime();
$xmls = JAXLUtil::splitXML($xml);
$pktCnt = count($xmls);
$this->totalSentPkt += $pktCnt;
$ret = @fwrite($this->stream, $xml);
$this->totalSentSize += $ret;
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
return $ret;
}
else {
$this->log("[[XMPPSend]] Failed\n".$xml);
throw new JAXLException("[[XMPPSend]] \nFailed");
return 0;
}
}
else if($xml == '') {
$this->log("[[XMPPSend]] Tried to send an empty stanza, not processing", 1);
return 0;
}
else {
$this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
return 0;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
- if($payload == '') return '';
+ if($payload == '' && $this->mode == 'cli') return '';
$payload = $this->executePlugin('jaxl_pre_handler', $payload);
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
$this->totalRcvdPkt += $pktCnt;
$buffer = array();
foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
$this->buffer .= $xml;
break;
}
}
if(substr($xml, 0, 7) == '<stream') $arr = $this->xml->xmlize($xml);
else $arr = JAXLXml::parse($xml);
if($arr === false) { $this->buffer .= $xml; continue; }
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
$jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
unset($buffer);
$this->executePlugin('jaxl_post_handler', $payload);
return $payload;
}
}
?>
|
jaxl/JAXL | de60086a83a0b2eba833f22723bdc0c1ffa4e3a4 | Lots of core improvement in XMPP base class related to performance and multi-instance app handling | diff --git a/CHANGELOG b/CHANGELOG
index 14b22ae..b8da5bf 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,316 +1,317 @@
version 2.1.2
-------------
- Simple method of issuing unique id to each connected jaxl instance
Improved dumpStat cron to include send/rcv rate, buffer sizes in stats
Core logged class prefix log data with instance uid, pid and current clock
Parse class return false if unable to parse as xml for recv'd xmpp packet
+ Lots of core improvement in XMPP base class related to performance and multi-instance app handling
- Updated core class files to make use of JAXL::executePlugin method instead of JAXLPlugin::execute method
- XMPP base class now make use of socket_select() to poll opened stream efficiently (getting rid of annoying sleep)
Updated JAXLCron method to adjust to new core changes
- Added hook for jaxl_get_bosh_curl_error which is called when bosh end point returns a non-zero errno
Updated Jaxl core session variable names to avoid clash with existing session vars
Updated boshchat.php to make use of jaxl_get_bosh_curl_error to disconnect intelligently
- PHP CMS looking to integrate Jaxl in their core can now force disable auto start of php session by Jaxl core
Simple pass 'boshSession' as false with jaxl constructor config array
- Entire Jaxl core including xmpp/, xep/ and core/ class files now make use of JAXL::addPlugin instead of JAXLPlugin to register per instance callbacks
- JAXLPlugin can now register a callback for a dedicated jaxl instance in a multi-instance jaxl application
Class functionality remains backward compatible.
- JAXLog class now also dump connect instance uid per log line
- XMPP instance iq id now defaults to a random value between 1 and 9
Also added jaxl_get_id event hook for apps to customize iq id for the connected Jaxl instance
Also as compared to default numeric iq id, Jaxl core now uses hex iq id's
- Every jaxl instance per php process id now generate it's own unique id JAXL::$uid
- Jaxl core doesn't go for a session if it's optional as indicated by the xmpp server
- Fixed boshChat postBind issues as reported by issue#26 (http://code.google.com/p/jaxl/issues/detail?id=26)
- Fixed jaxl constructor config read warning and XEP 0114 now make use of JAXL::getConfigByPriority method
- Removed warning while reading user config inside Jaxl constructor
Upgraded Jaxl Parser class which was malfunctioning on CentOS PHP 5.1.6 (cli)
- Added bosh error response handling and appropriate logging inside XMPP over Bosh core files
- Code cleanup inside jaxl logger class.
Fixed getConfigByPriority method which was malfunctioning in specific cases
- JAXLog class now using inbuild php function (error_log)
- Checking in first version of XEP-0016 (Privacy Lists), XEP-0055 (Jabber Search), XEP-0077 (In-Band Registration), XEP-0144 (Roster Item Exchange), XEP-0153 (vCard-Based Avatars), XEP-0237 (Roster Versioning)
- On auth faliure core doesn't throw exception since XMPP over Bosh apps are not held inside a try catch block (a better fix may be possible in future)
- XMPP over BOSH xep wasn't passing back Jaxl instance obj for jaxl_post_disconnect hook, fixed that for clean disconnect
- Jaxl core attempts to create log and pid files if doesn't already exists
Also instead of die() core throws relevant exception message wherever required
XMPP base classes throws relevant exception with message wherever required
- First commit of JAXLException class. JAXL core now uses JAXLException
- Jaxl constructor dies if logPath, pidPath and tmpPath doesn't exists on the system
- Core updates JAXL::resource after successful binding to match resource assigned by the connecting server
- Updated echobot sample example to make use of autoSubscribe core feature
Also registers callback for jaxl_post_subscription_request and jaxl_post_subscription_accept hooks
- Updated echobot and boshchat application to use in memory roster cache maintained by Jaxl core.
App files should register callback on hook jaxl_post_roster_update to get notified everytime local roster cache is updated
- Added provision for local roster cache management inside Jaxl core.
Retrived roster lists are cached in memory (see updated echobot.php sample example).
Also added provision for presence tracking (JAXL::trackPresence).
If enabled Jaxl core keep a track of jid availability and update local roster cache accordingly.
Also added provision for auto-accept subscription (JAXL::autoSubscribe).
- Removed XMPP::isConnected variable which used to tell status of connected socket stream.
This is equivalent to checking XMPP:stream variable for true/false
- Added a (kind of) buggy support for '/xml()' inside parser xpath
- If Jaxl instance has being configured for auto periodic ping (XEP-0199), pings are holded till auth completion.
Also if server responds 'feature-not-implemented' for first ping XEP-0199 automatically deleted periodic ping cron tab
- Corrected handling of error type iq stanza's (removed jaxl_get_iq_error hook)
- Added iq error code xpath inside JAXLXml class
- Completed missing JAXLCron::delete method for removing a previously registered cron tab
- Checking in first version of XEP-0049 (Private XML Storage) (not yet tested)
- Checking in first version of XEP-0191 (Simple Communication Blocking) (not yet tested)
- Added JAXL_PING_INTERVAL configuration option inside jaxl.ini
- XEP-0199 (XMPP Ping) can now automatically ping the connected server periodically for keeping connection alive on long running bots
(see echobot.php sample app for usage)
- Updated JAXLCron::add method to accept a number of arguments while adding bckgrnd jobs
These list of arguments is passed back to the application method
- Updated IQ handling inside XEP-0202 which wasn't returning iq stanza back resulting in no ping/pong
- Updated echobot to show usage of JAXL::discoItems and JAXL::discoInfo inside application code
- Added tagMap xpath for service identity and feature nodes in service discovery resultset
- JAXL core now auto includes XEP-0128 along with XEP-0030 on startup.
Also added two methods JAXL::discoItems and JAXL::discoInfo for service discovery
- Checking in first version of XEP-0128 (Service Discovery Extension)
- Fixed bug where message and presence stanza builder were not using passed id value as attribute
- Removed jaxl_pre_curl event hook which was only used internally by XEP-0124
- Jaxl now shutdown gracefully is encryption is required and openssl PHP module is not loaded in the environment
- For every registered callback on XMPP hooks, callback'd method will receive two params.
A payload and reference of Jaxl instance for whom XMPP event has occured.
Updated sample application code to use passed back Jaxl instance reference instead of global jaxl variable.
- As a library convention XEP's exposing user space configuration parameters via JAXL constructor SHOULD utilize JAXL::getConfigByPriority method
Added JAXL_TMP_PATH option inside jaxl.ini
- Jaxl::tmp is now Jaxl::tmpPath. Also added Jaxl config param to specify custom tmp path location
Jaxl client also self detect the IP of the host it is running upon (to be used by STUN/TURN utilities in Jingle negotitation)
- Removed JAXLUtil::includePath and JAXLUtil::getAppFilePath methods which are now redundant after removing jaxl.ini and jaxl.conf from lib core
- Removed global defines JAXL_BASE_PATH, JAXL_APP_BASE_PATH, JAXL_BOSH_APP_ABS_PATH from inside jaxl.ini (No more required by apps to specify these values)
- Removing env/jaxl.php and env/jaxl.conf (were required if you run your apps using `jaxl` command line utility)
Updated env/jaxl.ini so that projects can now directly include their app setting via jaxl.ini (before including core/jaxl.class.php)
- Added JAXL::bareJid public variable for usage inside applications.
XMPP base class now return bool on socket connect completion (used by PHPUnit test cases)
- Removing build.sh file from library for next release
Users should simply download, extract, include and write their app code without caring about the build script from 2.1.2 release
- As a library convention to include XEP's use JAXL::requires() method, while to include any core/ or xmpp/ base class use jaxl_require() method.
Updated library code and xep's to adhere to this convention.
Jaxl instance now provide a system specific /tmp folder location accessible by JAXL::tmp
- Removed JAXL_NAME and JAXL_VERSION constants.
Instead const variables are now defined per instance accessible by getName() and getVersion() methods.
Updated XEP-0030,0092,0115 to use the same
- Moved indivisual XEP's working parameter (0114,0124) from JAXL core class to XEP classes itself.
XEP's make use of JAXL::config array for parsing user options.
- Added JAXL_COMPONENT_PASS option inside jaxl.ini. Updated build.sh with new /app file paths.
Updated XEP-0114,0124,0206 to use array style configs as defined inside JAXL class
- Removed dependency upon jaxl.ini from all sample applications.
First checkin of sample sendMessage.php app.
- Config parameters for XEP's like 0114 and 0206 are now saved as an array inside JAXL class (later on they will be moved inside respective XEP's).
Added constructor config option to pre-choose an auth mechanism to be performed
if an auth mech is pre-chosen app files SHOULD not register callback for jaxl_get_auth_mech hook.
Bosh cookie settings can now be passed along with Jaxl constructor.
Added support for publishing vcard-temp:x:update node along with presence stanzas.
Jaxl instance can run in 3 modes a.k.a. stream,component and bosh mode
applications should use JAXL::startCore('mode') to configure instance for a specific mode.
- Removed redundant NS variable from inside XEP-0124
- Moved JAXLHTTPd setting defines inside the class (if gone missing CPU usage peaks to 100%)
- Added jaxl_httpd_pre_shutdown, jaxl_httpd_get_http_request, jaxl_httpd_get_sock_request event hooks inside JAXLHTTPd class
- Added JAXLS5B path (SOCKS5 implementation) inside jaxl_require method
- Removed all occurance of JAXL::$action variable from /core and /xep class files
- Updated boshChat and boshMUChat sample application which no longer user JAXL::$action variable inside application code
- Updated preFetchBOSH and preFetchXMPP sample example.
Application code don't need any JAXL::$action variable now
Neither application code need to define JAXL_BASE_PATH (optional from now on)
- JAXL core and XEP-0206 have no relation and dependency upon JAXL::$action variable now.
- Deprecated jaxl_get_body hook which was only for XEP-0124 working.
Also cleaned up XEP-0124 code by removing processBody method which is now handled inside preHandler itself.
- Defining JAXL_BASE_PATH inside application code made optional.
Developers can directly include /path/to/jaxl/core/jaxl.class.php and start writing applications.
Also added a JAXL::startCore() method (see usage in /app/preFetchXMPP.php).
Jaxl magic method for calling XEP methods now logs a warning inside jaxl.log if XEP doesn't exists in the environment
- Added tag map for XMPP message thread and subject child elements
- Fixed typo where in case of streamError proper description namespace was not parsed/displayed
- Disabled BOSH session close if application is running in boshOut=false mode
Suggested by MOVIM dev team who were experiencing loss of session data on end of script
- JAXL::log method 2nd parameter now defaults to logLevel=1 (passing 2nd param is now optional)
- Fixed XPath for iq stanza error condition and error NS extraction inside jaxl.parser.class
- First checkin of XEP-0184 Message Receipts
- Added support for usage of name() xpath function inside tag maps of JAXLXml class.
Also added some documentation for methods available inside JAXLXml class
- Fixed JAXLPlugin::remove method to properly remove and manage callback registry.
Also added some documentation for JAXLPlugin class methods
- Added JAXL contructor config option to disable BOSH module auto-output behaviour.
This is utilized inside app/preFetchBOSH.php sample example
- First checkin of sample application code pre-fetching XMPP/Jabber data for web page population using BOSH XEP
- Added a sample application file which can be used to pre-fetch XMPP/Jabber data for a webpage without using BOSH XEP or Ajax requests
As per the discussion on google groups (http://bit.ly/aKavZB) with MOVIM team
- JAXL library is now $jaxl independent, you can use anything like $var = new JAXL(); instance your applications now
JAXLUtil::encryptPassword now accepts username/password during SASL auth.
Previously it used to auto detect the same from JAXL instance, now core has to manually pass these param
- Added JAXL::startHTTPd method with appropriate docblock on how to convert Jaxl instance into a Jaxl socket (web) server.
Comments also explains how to still maintaining XMPP communication in the background
- Updated JAXLHTTPd class to use new constants inside jaxl.ini
- Added jaxl_get_stream_error event handler.
Registered callback methods also receive array form of received XMPP XML stanza
- Connecting Jaxl instance now fallback to default value 'localhost' for host,domain,boshHost,boshPort,boshSuffix
If these values are not configured either using jaxl.ini constants or constructor
- Provided a sendIQ method per JAXL instance.
Recommended that applications and XEP's should directly use this method for sending <iq/> type stanza
DONOT use XMPPSend methods inside your application code from here on
- Added configuration options for JAXL HTTPd server and JAXL Bosh Component Manager inside jaxl.ini
- Fixed type in XEP-0202 (Entity Time). XEP was not sending <iq/> id in response to get request
- Jaxl library is now phpdocs ready. Added extended documentation for JAXL core class, rest to be added
- All core classes inside core/, xmpp/ and xep/ folder now make use of jaxl->log method
JAXL Core constructor are now well prepared so that inclusion of jaxl.ini is now optional
Application code too should use jaxl->log instead of JAXLog::log method for logging purpose
- Reshuffled core instance paramaters between JAXL and XMPP class
Also Jaxl core now logs at level 1 instead of 0 (i.e. all logs goes inside jaxl.log and not on console)
- JAXL class now make use of endStream method inside XMPP base class while disconnecting.
Also XMPPSend::endStream now forces xmpp stanza delivery (escaping JAXL internal buffer)
http://code.google.com/p/jaxl/issues/detail?id=23
- Added endStream method inside XMPP base class and startSession,startBind methods inside XMPPSend class
XMPP::sendXML now accepts a $force parameter for escaping XMPP stanza's from JAXL internal buffer
- Updated the way Jaxl core calls XEP 0115 method (entity caps) to match documentation
XEP method's should accept jaxl instance as first paramater
- First checkin of PEP (Personal Eventing), User Location, User Mood, User Activity and User Tune XEP's
- Completed methods discoFeatures, discoNodes, discoNodeInfo, discoNodeMeta and discoNodeItems in PubSub XEP
- Hardcoded client category, type, lang and name. TODO: Make them configurable in future
- Cleaned up XEP 0030 (Service Discovery) and XEP 0115 (Entity Capabilities)
- Updated XMPP base class to use performance configuration parameters (now customizable with JAXL constructor)
- jaxl.conf will be removed from jaxl core in future, 1st step towards this goal
- Moved bulk of core configs from jaxl.conf
- Added more configuration options relating to client performance e.g. getPkts, getPktSize etc
- Fixed client mode by detecting sapi type instead of $_REQUEST['jaxl'] variable
- Now every implemented XEP should have an 'init' method which will accept only one parameter (jaxl instance itself)
- Jaxl core now converts transmitted stanza's into xmlentities (http://code.google.com/p/jaxl/issues/detail?id=22)
- Created a top level 'patch' folder which contains various patches sent by developers using 'git diff > patch' utility
- Fixed typo in namespace inside 0030 (thanks to Thomas Baquet for the patch)
- First checkin of PubSub XEP (untested)
- Indented build.sh and moved define's from top of JAXLHTTPd class to jaxl.ini
- Added JAXLHTTPd inside Jaxl core (a simple socket select server)
- Fixed sync of background iq and other stanza requests with browser ajax calls
- Updated left out methods in XMPP over BOSH xep to accept jaxl instance as first method
- All XEP methods available in application landspace, now accepts jaxl instance as first parameter. Updated core jaxl class magic method to handle the same.
If you are calling XEP methods as specified in the documentation, this change will not hurt your running applications
- Updated echobot sample application to utilize XEP 0054 (VCard Temp) and 0202 (Entity Time)
- First checkin of missing vcard-temp xep
- Added xmlentities JAXLUtil method
- Jaxl Parser now default parses xXmlns node for message stanzas
- Added PCRE_DOTALL and PCRE_MULTILINE pattern modifier for bosh unwrapBody method
- Added utility methods like urldecode, urlencode, htmlEntities, stripHTML and splitJid inside jaxl.js
- Updated sample application jaxl.ini to reflect changes in env/jaxl.ini
version 2.1.1
-------------
- Updated XMPPSend 'presence', 'message' and 'iq' methods to accept $jaxl instance as first parameter
if you are not calling these methods directly from your application code as mentioned in documentation
this change should not hurt you
- Added more comments to env/jaxl.ini and also added JAXL_LOG_ROTATE ini file option
- JAXL instance logs can be rotated every x seconds (logRotate config parameter) now
- Removed config param dumpTime, instead use dumpStat to specify stats dump period
- Base XMPP class now auto-flush output buffers filled because of library level rate limiter
- Added more options for JAXL constructor e.g.
boshHost, boshPort, boshSuffix, pidPath, logPath, logLevel, dumpStat, dumpTime
These param overwrites value specified inside jaxl.ini file
Also JAXL core will now periodically dump instance statistics
- Added an option in JAXL constructor to disable inbuild core rate limiter
- Added support when applications need to connect with external bosh endpoints
Bosh application code requires update for ->JAXL0206('startStream') method
- XMPPGet::handler replaces ->handler inside XEP-0124
- JAXLCron job now also passes connected instance to callback cron methods
- Updated base XMPP class now maintains a clock, updated sendXML method to respect library level rate limiting
- Base JAXL class now includes JAXLCron class for periodically dumping connected bot memory/usage stats
- First version of JAXLCron class for adding periodic jobs in the background
- XMPP payload handler moves from XMPPGet to base XMPP class, packets are then routed to XMPPGet class for further processing
- Updated xep-0124 to use instance bosh parameters instead of values defined inside jaxl.ini
- Provision to specify custom JAXL_BOSH_HOST inside jaxl.ini
- Instead of global logLevel and logPath, logger class now respects indivisual instance log settings
Helpful in multiple instance applications
- Updated base JAXL class to accept various other configuration parameters inside constructor
These param overwrites values defined inside jaxl.ini
- XMPPSend::xml method moves inside XMPP::sendXML (call using ->sendXML from within application code), as a part of library core cleanup
- Updated jaxl class to return back payload from called xep methods
- XMPP base method getXML can be instructed not to take a nap between stream reads
- Added jaxl_get_xml hook for taking control over incoming xml payload from xmpp stream
- Added support for disabling sig term registration, required by applications who already handle this in their core code
- Added capability of sending multiple message/presence stanza in one go inside jaxl base class
- Fixed typo in MUC Direct Invitation xep invite method
- getHandler should have accepted core instance by reference, fixed now. BOSH MUC Chat sample application header is now more appropriate
version 2.1.0
-------------
- First checkin of bosh MUC sample application
- Updated build file now packages bosh MUC chat sample application along with core classes
- Updated JAXLog class to accept instance inside log() method, application code should use ->log() to call JAXLog::log() method now
- Updated JAXLPlugin class to pass instance along with every XMPP event hook
- Updated jaxl_require method to call including XEP's init() method every time they are included using jaxl_require method
- Update jaxl.ini with some documentation/comments about JAXL_BOSH_COOKIE_DOMAIN parameter
- Updated echobot sample application code to pass instance while calling jaxl_require method
- Update XMPP SASL Auth class to accept instance while calculating SASL response.
Also passinginstance when jaxl_get_facebook_key hook is called
- Updated XMPP base class to accept component host name inside constructor.
Sending currentinstance with every XMPPSend, XMPPGet and JAXLog method calls
- Every XMPPGet method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Every XMPPSend method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Updated component bot sample application to show how to pass component host inside JAXL constructor.
Also updated jaxl_require call to accept current working instance
- Updated boshchat sample application to follow new rules of jaxl_require, also cleaned up the sample app code a bit
- Updated jaxl.ini of packaged sample applications to match /env/jaxl.ini
- Updated implemented XEP's init method to accept instance during initialization step
Send working instance with every XMPPSend method call
Almost every XEP's available method now accepts an additional instance so that XEP's can work independently for every instance inside a multiple jaxl instance application code
- Added magic method __call inside JAXL class
All application codes should now call a methods inside implemented XEP's like ->JAXLxxxx('method', , , ...)
Also added ->log method to be used by application codes
JAXLog::log() should not be called directly from application code
Updated XMPPSend methods to accept instance
Added ->requires() method that does a similar job as jaxl_require() which now also expects instance as one of the passed parameter.
version 2.0.4
-------------
- Updated XMPP base class and XMPP Get class to utilize new XMPPAuth class
- Updated jaxl_require method with new XMPPAuth class path
- Extracted XMPP SASL auth mechanism out of XMPP Get class, code cleanup
- unwrapBody method of XEP 0124 is now public
- Added #News block on top of README
- No more capital true, false, null inside Jaxl core to pass PHP_CodeSniffer tests
- :retab Jaxl library core to pass PHP_CodeSniffer tests
- Added Jabber Component Protocol example application bot
- Updated README with documentation link for Jabber component protocol
- Updated Entity Caps method to use list of passed feature list for verification code generation
- Updated MUC available methods doc link inside README
- Added experimental support for SCRAM-SHA-1, CRAM-MD5 and LOGIN auth mechanisms
version 2.0.3
-------------
- Updated Jaxl XML parsing class to handle multiple level nested child cases
- Updated README and bosh chat application with documentation link
- Fixed bosh application to run on localhost
- Added doc links inside echobot sample app
- Bosh sample application also use entity time XEP-0202 now
- Fix for sapi detection inside jaxl util
- jaxl.js updated to handle multiple ajax poll response payloads
- Bosh session manager now dumps ajax poll response on post handler callback
- Removed hardcoded ajax poll url inside boshchat application
- Updated component protocol XEP pre handshake event handling
version 2.0.2
-------------
- Packaged XEP 0202 (Entity Time)
- First checkin of Bosh related XEP 0124 and 0206
- Sample Bosh Chat example application
- Updated jaxl.class.php to save Bosh request action parameter
- jaxl.ini updated with Bosh related cookie options, default loglevel now set to 4
- jaxl.js checkin which should be used with bosh applications
- Updated base xmpp classes to provide integrated bosh support
- Outgoing presence and message stanza's too can include @id attribute now
version 2.0.1
-------------
- Typo fix in JAXLXml::$tagMap for errorCode
- Fix for handling overflooded roster list
- Packaged XEP 0115 (Entity capability) and XEP 0199 (XMPP Ping)
- Updated sample echobot to use XEP 0115 and XEP 0199
- Support for X-FACEBOOK-PLATFORM authentication
version 2.0.0
--------------
First checkin of:
- Restructed core library with event mechanism
- Packaged XEP 0004, 0030, 0045, 0050, 0085, 0092, 0114, 0133, 0249
- Sample echobot application
|
jaxl/JAXL | 1696ec0ce383bfda07d6c4161a6488f8976cc55c | Lots of core improvement in XMPP base class related to performance and multi-instance app handling | diff --git a/xmpp/xmpp.auth.php b/xmpp/xmpp.auth.php
index 6e71db2..e3a5a65 100644
--- a/xmpp/xmpp.auth.php
+++ b/xmpp/xmpp.auth.php
@@ -1,155 +1,155 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLUtil',
'JAXLPlugin'
));
/**
* XMPP Auth class for performing various SASL auth mechanisms
* DIGEST-MD5, X-FACEBOOK-PLATFORM, SCRAM-SHA-1, CRAM-MD5
*/
class XMPPAuth {
public static function getResponse($authType, $challenge, $jaxl) {
$response = array();
$decoded = base64_decode($challenge);
$xml = '<response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">';
if($authType == 'X-FACEBOOK-PLATFORM') {
$decoded = explode('&', $decoded);
foreach($decoded as $k=>$v) {
list($kk, $vv) = explode('=', $v);
$decoded[$kk] = $vv;
unset($decoded[$k]);
}
list($secret, $decoded['api_key'], $decoded['session_key']) = $jaxl->executePlugin('jaxl_get_facebook_key', false);
- $decoded['call_id'] = time();
+ $decoded['call_id'] = $jaxl->clock;
$decoded['v'] = '1.0';
$base_string = '';
foreach(array('api_key', 'call_id', 'method', 'nonce', 'session_key', 'v') as $key) {
if(isset($decoded[$key])) {
$response[$key] = $decoded[$key];
$base_string .= $key.'='.$decoded[$key];
}
}
$base_string .= $secret;
$response['sig'] = md5($base_string);
$responseURI = '';
foreach($response as $k=>$v) {
if($responseURI == '') $responseURI .= $k.'='.urlencode($v);
else $responseURI .= '&'.$k.'='.urlencode($v);
}
$xml .= base64_encode($responseURI);
}
else if($authType == 'DIGEST-MD5') {
$decoded = JAXLUtil::explodeData($decoded);
if(!isset($decoded['digest-uri'])) $decoded['digest-uri'] = 'xmpp/'.$jaxl->domain;
$decoded['cnonce'] = base64_encode(JAXLUtil::generateNonce());
if(isset($decoded['qop'])
&& $decoded['qop'] != 'auth'
&& strpos($decoded['qop'],'auth') !== false
) { $decoded['qop'] = 'auth'; }
$response = array('username'=>$jaxl->user,
'response' => JAXLUtil::encryptPassword(array_merge($decoded,array('nc'=>'00000001')), $jaxl->user, $jaxl->pass),
'charset' => 'utf-8',
'nc' => '00000001',
'qop' => 'auth'
);
foreach(array('nonce', 'digest-uri', 'realm', 'cnonce') as $key)
if(isset($decoded[$key]))
$response[$key] = $decoded[$key];
$xml .= base64_encode(JAXLUtil::implodeData($response));
}
else if($authType == 'SCRAM-SHA-1') {
$decoded = JAXLUtil::explodeData($decoded);
// SaltedPassword := Hi(Normalize(password), salt, i)
$saltedPasswd = JAXLUtil::pbkdf2($jaxl->pass, $decoded['s'], $decoded['i']);
// ClientKey := HMAC(SaltedPassword, "Client Key")
$clientKey = JAXLUtil::hashMD5($saltedPassword, "Client Key");
// StoredKey := H(ClientKey)
$storedKey = sha1("Client Key");
// assemble client-final-message-without-proof
$clientFinalMessage = "c=bwis,r=".$decoded['r'];
// AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof
// ClientSignature := HMAC(StoredKey, AuthMessage)
// ClientProof := ClientKey XOR ClientSignature
// ServerKey := HMAC(SaltedPassword, "Server Key")
// ServerSignature := HMAC(ServerKey, AuthMessage)
foreach(array('c', 'r', 'p') as $key)
if(isset($decoded[$key]))
$response[$key] = $decoded[$key];
$xml .= base64_encode(JAXLUtil::implodeData($response));
}
else if($authType == 'CRAM-MD5') {
$xml .= base64_encode($jaxl->user.' '.hash_hmac('md5', $jaxl->pass, $arr['challenge']));
}
$xml .= '</response>';
$jaxl->secondChallenge = true;
return $xml;
}
}
?>
diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index 5bd281c..e0e0abb 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,429 +1,480 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
var $streamBlocking = 1;
-
- /**
- * Size of each packet to be read from the socket
- */
- var $getPktSize = false;
-
- /**
- * Maximum rate at which XMPP stanza's can flow out
- */
- var $sendRate = false;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
+ /**
+ * Instance start time
+ */
+ var $startTime = false;
+
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
+ /**
+ * Maximum rate at which XMPP stanza's can flow out
+ */
+ var $sendRate = false;
+
+ /**
+ * Size of each packet to be read from the socket
+ */
+ var $getPktSize = false;
+
+ /**
+ * Pkt count and sizes
+ */
+ var $totalRcvdPkt = 0;
+ var $totalRcvdSize = 0;
+ var $totalSentPkt = 0;
+ var $totalSentSize = 0;
+
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
- $this->clocked = time();
+ $this->clocked = $this->startTime = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
$this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 4096;
- $this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : 0.1;
+ $this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : .4;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
$this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
$this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
$this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
$this->executePlugin('jaxl_post_connect', $ret);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = $this->executePlugin('jaxl_get_id', ++$this->lastid);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
* $option = null (read until data is available)
* $option = integer (read for so many seconds)
*/
- function getXML($option=2) {
- // reload pending buffer
- $payload = $this->buffer;
- $this->buffer = '';
-
+ function getXML($option=5) {
// prepare streams to select
- $read = array($this->stream); $write = array(); $except = array();
- $secs = $option; $usecs = 0;
+ $stream = array(); $jaxls = array($this);
+ $jaxls = $this->executePlugin('jaxl_pre_get_xml_stream', $jaxls);
+ foreach($jaxls as $jaxl) $streams[] = $jaxl->stream;
+ $read = $streams;
// get num changed streams
- if(false === ($changed = @stream_select($read, $write, $except, $secs, $usecs))) {
+ $write = null; $except = null; $secs = $option; $usecs = 0;
+ if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPGet]] \nError while reading packet from stream", 5);
- @fclose($this->stream);
- $this->socket = null;
- return false;
}
- else if($changed > 0) { $payload .= @fread($this->stream, $this->getPktSize); }
- else {}
-
- // update clock
- $now = time();
- $this->clock += $now-$this->clocked;
- $this->clocked = $now;
-
- // route rcvd packet
- $payload = trim($payload);
- $payload = $this->executePlugin('jaxl_get_xml', $payload);
- $this->handler($payload);
-
- // flush obuffer
- if($this->obuffer != '') {
- $payload = $this->obuffer;
- $this->obuffer = '';
- $this->_sendXML($payload);
+ else {
+ $this->log("[[XMPPGet]] $changed streams ready for read out of total ".sizeof($streams)." streams", 7);
+ if($changed == 0) $now = $this->clocked+$secs;
+ else $now = time();
+
+ foreach($read as $k=>$r) {
+ // get jaxl instance we are dealing with
+ $ret = $payload = '';
+ $key = array_search($r, $streams);
+ $jaxl = $jaxls[$key];
+ unset($jaxls[$key]);
+
+ // update clock
+ if($now > $jaxl->clocked) {
+ $jaxl->clock += $now-$jaxl->clocked;
+ $jaxl->clocked = $now;
+ }
+
+ // reload pending buffer
+ $payload = $jaxl->buffer;
+ $jaxl->buffer = '';
+
+ // read stream
+ $ret = @fread($jaxl->stream, $jaxl->getPktSize);
+ $jaxl->log("[[XMPPGet]] \n".$ret, 4);
+ $jaxl->totalRcvdSize = strlen($ret);
+ $ret = $jaxl->executePlugin('jaxl_get_xml', $ret);
+ $payload .= $ret;
+
+ // route packets
+ $jaxl->handler($payload);
+
+ // clear buffer
+ if($jaxl->obuffer != '') $jaxl->sendXML();
+ }
+
+ foreach($jaxls as $jaxl) {
+ // update clock
+ if($now > $jaxl->clocked) {
+ $jaxl->clock += $now-$jaxl->clocked;
+ $jaxl->clocked = $now;
+ $payload = $jaxl->executePlugin('jaxl_get_xml', '');
+ }
+
+ // clear buffer
+ if($jaxl->obuffer != '') $jaxl->sendXML();
+ }
}
+
+ unset($jaxls, $streams);
+ return $changed;
}
-
+
/**
* Send XMPP XML packet over connected stream
*/
- function sendXML($xml, $force=false) {
- $xml = $this->executePlugin('jaxl_send_xml', $xml);
-
- if($this->mode == "cgi") {
- $this->executePlugin('jaxl_send_body', $xml);
- }
+ function sendXML($xml='', $force=false) {
+ $currSendRate = ($this->totalSentSize/(JAXLUtil::getTime()-$this->lastSendTime))/1000000;
+ if($this->mode == "cgi") { $this->executePlugin('jaxl_send_body', $xml); }
else {
+ $this->obuffer .= $xml;
if($this->rateLimit
&& !$force
&& $this->lastSendTime
- && JAXLUtil::getTime() - $this->lastSendTime < $this->sendRate
- ) { $this->obuffer .= $xml; }
- else {
- $xml = $this->obuffer.$xml;
- $this->obuffer = '';
- return $this->_sendXML($xml);
+ && ($currSendRate > $this->sendRate)
+ ) {
+ $this->log("[[XMPPSend]] rateLimit\nBufferSize:".strlen($this->obuffer).", maxSendRate:".$this->sendRate.", currSendRate:".$currSendRate, 5);
+ return 0;
}
+
+ $xml = $this->obuffer;
+ $this->obuffer = '';
+ if($currSendRate > $this->sendRate) echo $can.PHP_EOL;
+ $xml = $this->executePlugin('jaxl_send_xml', $xml);
+ return ($xml == '') ? 0 : $this->_sendXML($xml);
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
- if($this->stream) {
- $this->lastSendTime = JAXLUtil::getTime();
-
- // prepare streams to select
+ if($this->stream && $xml != '') {
$read = array(); $write = array($this->stream); $except = array();
$secs = null; $usecs = null;
- // try sending packet
- if(false === ($changed = @stream_select($read, $write, $except, $secs, $usecs))) {
+ if(false === ($changed = @stream_select(&$read, &$write, &$except, $secs, $usecs))) {
$this->log("[[XMPPSend]] \nError while trying to send packet", 5);
+ throw new JAXLException("[[XMPPSend]] \nError while trying to send packet");
+ return 0;
}
else if($changed > 0) {
+ $this->lastSendTime = JAXLUtil::getTime();
+ $xmls = JAXLUtil::splitXML($xml);
+ $pktCnt = count($xmls);
+ $this->totalSentPkt += $pktCnt;
+
$ret = @fwrite($this->stream, $xml);
+ $this->totalSentSize += $ret;
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
+ return $ret;
}
else {
$this->log("[[XMPPSend]] Failed\n".$xml);
throw new JAXLException("[[XMPPSend]] \nFailed");
+ return 0;
}
- return $ret;
+ }
+ else if($xml == '') {
+ $this->log("[[XMPPSend]] Tried to send an empty stanza, not processing", 1);
+ return 0;
}
else {
$this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
- return false;
+ return 0;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
if($payload == '') return '';
- $this->log("[[XMPPGet]] \n".$payload, 4);
-
- $buffer = array();
$payload = $this->executePlugin('jaxl_pre_handler', $payload);
-
+
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
+ $this->totalRcvdPkt += $pktCnt;
+ $buffer = array();
- foreach($xmls as $pktNo => $xml) {
+ foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
- $this->buffer = $xml;
+ $this->buffer .= $xml;
break;
}
}
- if(substr($xml, 0, 7) == '<stream')
- $arr = $this->xml->xmlize($xml);
- else
- $arr = JAXLXml::parse($xml);
-
+ if(substr($xml, 0, 7) == '<stream') $arr = $this->xml->xmlize($xml);
+ else $arr = JAXLXml::parse($xml);
+ if($arr === false) { $this->buffer .= $xml; continue; }
+
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
$jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
- unset($buffer);
-
+ unset($buffer);
+
$this->executePlugin('jaxl_post_handler', $payload);
+ return $payload;
}
}
?>
|
jaxl/JAXL | 6b6b255d577c5b35c41a2c69e29e63559b4436fa | Added log inside JAXLPlugin execute method | diff --git a/core/jaxl.plugin.php b/core/jaxl.plugin.php
index 27c844f..1c6ee9d 100644
--- a/core/jaxl.plugin.php
+++ b/core/jaxl.plugin.php
@@ -1,121 +1,121 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl Plugin Framework
*/
class JAXLPlugin {
/**
* Registry of all registered hooks
*/
public static $registry = array();
/**
* Register callback on hook
*
* @param string $hook
* @param string|array $callback A valid callback inside your application code
* @param integer $priority (>0) When more than one callbacks is attached on hook, they are called in priority order or which ever was registered first
* @param integer $uid random id $jaxl->uid of connected Jaxl instance, $uid=0 means callback registered for all connected instances
*/
public static function add($hook, $callback, $priority=10, $uid=0) {
if(!isset(self::$registry[$uid]))
self::$registry[$uid] = array();
if(!isset(self::$registry[$uid][$hook]))
self::$registry[$uid][$hook] = array();
if(!isset(self::$registry[$uid][$hook][$priority]))
self::$registry[$uid][$hook][$priority] = array();
array_push(self::$registry[$uid][$hook][$priority], $callback);
}
/**
* Removes a previously registered callback on hook
*
* @param string $hook
* @param string|array $callback
* @param integer $priority
* @param integer $uid random id $jaxl->uid of connected Jaxl instance, $uid=0 means callback registered for all connected instances
*/
public static function remove($hook, $callback, $priority=10, $uid=0) {
if(($key = array_search($callback, self::$registry[$uid][$hook][$priority])) !== FALSE)
unset(self::$registry[$uid][$hook][$priority][$key]);
if(count(self::$registry[$uid][$hook][$priority]) == 0)
unset(self::$registry[$uid][$hook][$priority]);
if(count(self::$registry[$uid][$hook]) == 0)
unset(self::$registry[$uid][$hook]);
}
/*
* Method calls previously registered callbacks on executing hook
*
* @param string $hook
* @param mixed $payload
* @param object $jaxl
* @param array $filter
*/
public static function execute($hook, $payload=null, $jaxl=false, $filter=false) {
$uids = array($jaxl->uid, 0);
foreach($uids as $uid) {
if(isset(self::$registry[$uid][$hook]) && count(self::$registry[$uid][$hook]) > 0) {
foreach(self::$registry[$uid][$hook] as $priority) {
foreach($priority as $callback) {
if($filter === false || (is_array($filter) && in_array($callback[0], $filter))) {
- //$jaxl->log("[[JAXLPlugin]] Executing hook $hook for uid $uid", 5);
+ $jaxl->log("[[JAXLPlugin]] Executing hook $hook for uid $uid", 7);
$payload = call_user_func($callback, $payload, $jaxl);
}
}
}
}
}
return $payload;
}
}
?>
diff --git a/core/jaxl.util.php b/core/jaxl.util.php
index b9fa420..61cd3a1 100644
--- a/core/jaxl.util.php
+++ b/core/jaxl.util.php
@@ -1,212 +1,212 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl Utility Class
*/
class JAXLUtil {
public static function curl($url, $type='GET', $headers=false, $data=false, $user=false, $pass=false) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
if($headers) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_VERBOSE, false);
if($type == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
if($user && $pass) {
curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$pass);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
}
$rs = array();
$rs['content'] = curl_exec($ch);
$rs['errno'] = curl_errno($ch);
$rs['errmsg'] = curl_error($ch);
$rs['header'] = curl_getinfo($ch);
curl_close($ch);
return $rs;
}
public static function isWin() {
return strtoupper(substr(PHP_OS,0,3)) == "WIN" ? true : false;
}
public static function pcntlEnabled() {
return extension_loaded('pcntl');
}
public static function sslEnabled() {
return extension_loaded('openssl');
}
public static function getTime() {
- list($usec, $sec) = explode(" ",microtime());
- return (float) $sec + (float) $usec;
+ list($usec, $sec) = explode(" ", microtime());
+ return (float) $sec + (float) $usec;
}
public static function splitXML($xml) {
$xmlarr = array();
$temp = preg_split("/<(message|iq|presence|stream|proceed|challenge|success|failure)(?=[\:\s\>])/", $xml, -1, PREG_SPLIT_DELIM_CAPTURE);
for($a=1; $a<count($temp); $a=$a+2) $xmlarr[] = "<".$temp[$a].$temp[($a+1)];
return $xmlarr;
}
public static function explodeData($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 static function implodeData($data) {
$return = array();
foreach($data as $key => $value)
$return[] = $key . '="' . $value . '"';
return implode(',', $return);
}
public static function generateNonce() {
$str = '';
mt_srand((double) microtime()*10000000);
for($i=0; $i<32; $i++)
$str .= chr(mt_rand(0, 255));
return $str;
}
public static function encryptPassword($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)));
}
public static function hmacMD5($key, $data) {
if(strlen($key) > 64) $key = pack('H32', md5($key));
if(strlen($key) < 64) $key = str_pad($key, 64, chr(0));
$k_ipad = substr($key, 0, 64) ^ str_repeat(chr(0x36), 64);
$k_opad = substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64);
$inner = pack('H32', md5($k_ipad . $data));
$digest = md5($k_opad . $inner);
return $digest;
}
public static function pbkdf2($data, $secret, $iteration, $dkLen=32, $algo='sha1') {
$hLen = strlen(hash($algo, null, true));
$l = ceil($dkLen/$hLen);
$t = null;
for($i=1; $i<=$l; $i++) {
$f = $u = hash_hmac($algo, $s.pack('N', $i), $p, true);
for($j=1; $j<$c; $j++)
$f ^= ($u = hash_hmac($algo, $u, $p, true));
$t .= $f;
}
return substr($t, 0, $dk_len);
}
public static function getBareJid($jid) {
list($user,$domain,$resource) = self::splitJid($jid);
return ($user ? $user."@" : "").$domain;
}
public static function splitJid($jid) {
preg_match("/(?:([^\@]+)\@)?([^\/]+)(?:\/(.*))?$/",$jid,$matches);
return array($matches[1],$matches[2],@$matches[3]);
}
/*
* xmlentities method for PHP supporting
* 1) Rserved characters in HTML
* 2) ISO 8859-1 Symbols
* 3) ISO 8859-1 Characters
* 4) Math Symbols Supported by HTML
* 5) Greek Letters Supported by HTML
* 6) Other Entities Supported by HTML
*
* Credits:
* --------
* http://www.sourcerally.net/Scripts/39-Convert-HTML-Entities-to-XML-Entities
* http://www.w3schools.com/tags/ref_entities.asp
* http://www.w3schools.com/tags/ref_symbols.asp
*/
public static function xmlentities($str) {
$str = htmlentities($str, ENT_QUOTES, 'UTF-8');
$xml = array('"','&','&','<','>',' ','¡','¢','£','¤','¥','¦','§','¨','©','ª','«','¬','­','®','¯','°','±','²','³','´','µ','¶','·','¸','¹','º','»','¼','½','¾','¿','À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','×','Ø','Ù','Ú','Û','Ü','Ý','Þ','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô','õ','ö','÷','ø','ù','ú','û','ü','ý','þ','ÿ','∀','∂','∃','∅','∇','∈','∉','∋','∏','∑','−','∗','√','∝','∞','∠','∧','∨','∩','∪','∫','∴','∼','≅','≈','≠','≡','≤','≥','⊂','⊃','⊄','⊆','⊇','⊕','⊗','⊥','⋅','Α','Β','Γ','Δ','Ε','Ζ','Η','Θ','Ι','Κ','Λ','Μ','Ν','Ξ','Ο','Π','Ρ','Σ','Τ','Υ','Φ','Χ','Ψ','Ω','α','β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ','ς','σ','τ','υ','φ','χ','ψ','ω','ϑ','ϒ','ϖ','Œ','œ','Š','š','Ÿ','ƒ','ˆ','˜',' ',' ',' ','‌','‍','‎','‏','–','—','‘','’','‚','“','”','„','†','‡','•','…','‰','′','″','‹','›','‾','€','™','←','↑','→','↓','↔','↵','⌈','⌉','⌊','⌋','◊','♠','♣','♥','♦');
$html = array('"','&','&','<','>',' ','¡','¢','£','¤','¥','¦','§','¨','©','ª','«','¬','­','®','¯','°','±','²','³','´','µ','¶','·','¸','¹','º','»','¼','½','¾','¿','À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','×','Ø','Ù','Ú','Û','Ü','Ý','Þ','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô','õ','ö','÷','ø','ù','ú','û','ü','ý','þ','ÿ','∀','∂','∃','∅','∇','∈','∉','∋','∏','∑','−','∗','√','∝','∞','∠','∧','∨','∩','∪','∫','∴','∼','≅','≈','≠','≡','≤','≥','⊂','⊃','⊄','⊆','⊇','⊕','⊗','⊥','⋅','Α','Β','Γ','Δ','Ε','Ζ','Η','Θ','Ι','Κ','Λ','Μ','Ν','Ξ','Ο','Π','Ρ','Σ','Τ','Υ','Φ','Χ','Ψ','Ω','α','β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ','ς','σ','τ','υ','φ','χ','ψ','ω','ϑ','ϒ','ϖ','Œ','œ','Š','š','Ÿ','ƒ','ˆ','˜',' ',' ',' ','‌','‍','‎','‏','–','—','‘','’','‚','“','”','„','†','‡','•','…','‰','′','″','‹','›','‾','€','™','←','↑','→','↓','↔','↵','⌈','⌉','⌊','⌋','◊','♠','♣','♥','♦');
$str = str_replace($html,$xml,$str);
$str = str_ireplace($html,$xml,$str);
return $str;
}
}
?>
|
jaxl/JAXL | f0b01fd3d44d22c4efd35777d713ddacc127f940 | Parse class return false if unable to parse as xml for recv'd xmpp packet | diff --git a/CHANGELOG b/CHANGELOG
index 46088a7..14b22ae 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,314 +1,316 @@
version 2.1.2
-------------
- Simple method of issuing unique id to each connected jaxl instance
Improved dumpStat cron to include send/rcv rate, buffer sizes in stats
+ Core logged class prefix log data with instance uid, pid and current clock
+ Parse class return false if unable to parse as xml for recv'd xmpp packet
- Updated core class files to make use of JAXL::executePlugin method instead of JAXLPlugin::execute method
- XMPP base class now make use of socket_select() to poll opened stream efficiently (getting rid of annoying sleep)
Updated JAXLCron method to adjust to new core changes
- Added hook for jaxl_get_bosh_curl_error which is called when bosh end point returns a non-zero errno
Updated Jaxl core session variable names to avoid clash with existing session vars
Updated boshchat.php to make use of jaxl_get_bosh_curl_error to disconnect intelligently
- PHP CMS looking to integrate Jaxl in their core can now force disable auto start of php session by Jaxl core
Simple pass 'boshSession' as false with jaxl constructor config array
- Entire Jaxl core including xmpp/, xep/ and core/ class files now make use of JAXL::addPlugin instead of JAXLPlugin to register per instance callbacks
- JAXLPlugin can now register a callback for a dedicated jaxl instance in a multi-instance jaxl application
Class functionality remains backward compatible.
- JAXLog class now also dump connect instance uid per log line
- XMPP instance iq id now defaults to a random value between 1 and 9
Also added jaxl_get_id event hook for apps to customize iq id for the connected Jaxl instance
Also as compared to default numeric iq id, Jaxl core now uses hex iq id's
- Every jaxl instance per php process id now generate it's own unique id JAXL::$uid
- Jaxl core doesn't go for a session if it's optional as indicated by the xmpp server
- Fixed boshChat postBind issues as reported by issue#26 (http://code.google.com/p/jaxl/issues/detail?id=26)
- Fixed jaxl constructor config read warning and XEP 0114 now make use of JAXL::getConfigByPriority method
- Removed warning while reading user config inside Jaxl constructor
Upgraded Jaxl Parser class which was malfunctioning on CentOS PHP 5.1.6 (cli)
- Added bosh error response handling and appropriate logging inside XMPP over Bosh core files
- Code cleanup inside jaxl logger class.
Fixed getConfigByPriority method which was malfunctioning in specific cases
- JAXLog class now using inbuild php function (error_log)
- Checking in first version of XEP-0016 (Privacy Lists), XEP-0055 (Jabber Search), XEP-0077 (In-Band Registration), XEP-0144 (Roster Item Exchange), XEP-0153 (vCard-Based Avatars), XEP-0237 (Roster Versioning)
- On auth faliure core doesn't throw exception since XMPP over Bosh apps are not held inside a try catch block (a better fix may be possible in future)
- XMPP over BOSH xep wasn't passing back Jaxl instance obj for jaxl_post_disconnect hook, fixed that for clean disconnect
- Jaxl core attempts to create log and pid files if doesn't already exists
Also instead of die() core throws relevant exception message wherever required
XMPP base classes throws relevant exception with message wherever required
- First commit of JAXLException class. JAXL core now uses JAXLException
- Jaxl constructor dies if logPath, pidPath and tmpPath doesn't exists on the system
- Core updates JAXL::resource after successful binding to match resource assigned by the connecting server
- Updated echobot sample example to make use of autoSubscribe core feature
Also registers callback for jaxl_post_subscription_request and jaxl_post_subscription_accept hooks
- Updated echobot and boshchat application to use in memory roster cache maintained by Jaxl core.
App files should register callback on hook jaxl_post_roster_update to get notified everytime local roster cache is updated
- Added provision for local roster cache management inside Jaxl core.
Retrived roster lists are cached in memory (see updated echobot.php sample example).
Also added provision for presence tracking (JAXL::trackPresence).
If enabled Jaxl core keep a track of jid availability and update local roster cache accordingly.
Also added provision for auto-accept subscription (JAXL::autoSubscribe).
- Removed XMPP::isConnected variable which used to tell status of connected socket stream.
This is equivalent to checking XMPP:stream variable for true/false
- Added a (kind of) buggy support for '/xml()' inside parser xpath
- If Jaxl instance has being configured for auto periodic ping (XEP-0199), pings are holded till auth completion.
Also if server responds 'feature-not-implemented' for first ping XEP-0199 automatically deleted periodic ping cron tab
- Corrected handling of error type iq stanza's (removed jaxl_get_iq_error hook)
- Added iq error code xpath inside JAXLXml class
- Completed missing JAXLCron::delete method for removing a previously registered cron tab
- Checking in first version of XEP-0049 (Private XML Storage) (not yet tested)
- Checking in first version of XEP-0191 (Simple Communication Blocking) (not yet tested)
- Added JAXL_PING_INTERVAL configuration option inside jaxl.ini
- XEP-0199 (XMPP Ping) can now automatically ping the connected server periodically for keeping connection alive on long running bots
(see echobot.php sample app for usage)
- Updated JAXLCron::add method to accept a number of arguments while adding bckgrnd jobs
These list of arguments is passed back to the application method
- Updated IQ handling inside XEP-0202 which wasn't returning iq stanza back resulting in no ping/pong
- Updated echobot to show usage of JAXL::discoItems and JAXL::discoInfo inside application code
- Added tagMap xpath for service identity and feature nodes in service discovery resultset
- JAXL core now auto includes XEP-0128 along with XEP-0030 on startup.
Also added two methods JAXL::discoItems and JAXL::discoInfo for service discovery
- Checking in first version of XEP-0128 (Service Discovery Extension)
- Fixed bug where message and presence stanza builder were not using passed id value as attribute
- Removed jaxl_pre_curl event hook which was only used internally by XEP-0124
- Jaxl now shutdown gracefully is encryption is required and openssl PHP module is not loaded in the environment
- For every registered callback on XMPP hooks, callback'd method will receive two params.
A payload and reference of Jaxl instance for whom XMPP event has occured.
Updated sample application code to use passed back Jaxl instance reference instead of global jaxl variable.
- As a library convention XEP's exposing user space configuration parameters via JAXL constructor SHOULD utilize JAXL::getConfigByPriority method
Added JAXL_TMP_PATH option inside jaxl.ini
- Jaxl::tmp is now Jaxl::tmpPath. Also added Jaxl config param to specify custom tmp path location
Jaxl client also self detect the IP of the host it is running upon (to be used by STUN/TURN utilities in Jingle negotitation)
- Removed JAXLUtil::includePath and JAXLUtil::getAppFilePath methods which are now redundant after removing jaxl.ini and jaxl.conf from lib core
- Removed global defines JAXL_BASE_PATH, JAXL_APP_BASE_PATH, JAXL_BOSH_APP_ABS_PATH from inside jaxl.ini (No more required by apps to specify these values)
- Removing env/jaxl.php and env/jaxl.conf (were required if you run your apps using `jaxl` command line utility)
Updated env/jaxl.ini so that projects can now directly include their app setting via jaxl.ini (before including core/jaxl.class.php)
- Added JAXL::bareJid public variable for usage inside applications.
XMPP base class now return bool on socket connect completion (used by PHPUnit test cases)
- Removing build.sh file from library for next release
Users should simply download, extract, include and write their app code without caring about the build script from 2.1.2 release
- As a library convention to include XEP's use JAXL::requires() method, while to include any core/ or xmpp/ base class use jaxl_require() method.
Updated library code and xep's to adhere to this convention.
Jaxl instance now provide a system specific /tmp folder location accessible by JAXL::tmp
- Removed JAXL_NAME and JAXL_VERSION constants.
Instead const variables are now defined per instance accessible by getName() and getVersion() methods.
Updated XEP-0030,0092,0115 to use the same
- Moved indivisual XEP's working parameter (0114,0124) from JAXL core class to XEP classes itself.
XEP's make use of JAXL::config array for parsing user options.
- Added JAXL_COMPONENT_PASS option inside jaxl.ini. Updated build.sh with new /app file paths.
Updated XEP-0114,0124,0206 to use array style configs as defined inside JAXL class
- Removed dependency upon jaxl.ini from all sample applications.
First checkin of sample sendMessage.php app.
- Config parameters for XEP's like 0114 and 0206 are now saved as an array inside JAXL class (later on they will be moved inside respective XEP's).
Added constructor config option to pre-choose an auth mechanism to be performed
if an auth mech is pre-chosen app files SHOULD not register callback for jaxl_get_auth_mech hook.
Bosh cookie settings can now be passed along with Jaxl constructor.
Added support for publishing vcard-temp:x:update node along with presence stanzas.
Jaxl instance can run in 3 modes a.k.a. stream,component and bosh mode
applications should use JAXL::startCore('mode') to configure instance for a specific mode.
- Removed redundant NS variable from inside XEP-0124
- Moved JAXLHTTPd setting defines inside the class (if gone missing CPU usage peaks to 100%)
- Added jaxl_httpd_pre_shutdown, jaxl_httpd_get_http_request, jaxl_httpd_get_sock_request event hooks inside JAXLHTTPd class
- Added JAXLS5B path (SOCKS5 implementation) inside jaxl_require method
- Removed all occurance of JAXL::$action variable from /core and /xep class files
- Updated boshChat and boshMUChat sample application which no longer user JAXL::$action variable inside application code
- Updated preFetchBOSH and preFetchXMPP sample example.
Application code don't need any JAXL::$action variable now
Neither application code need to define JAXL_BASE_PATH (optional from now on)
- JAXL core and XEP-0206 have no relation and dependency upon JAXL::$action variable now.
- Deprecated jaxl_get_body hook which was only for XEP-0124 working.
Also cleaned up XEP-0124 code by removing processBody method which is now handled inside preHandler itself.
- Defining JAXL_BASE_PATH inside application code made optional.
Developers can directly include /path/to/jaxl/core/jaxl.class.php and start writing applications.
Also added a JAXL::startCore() method (see usage in /app/preFetchXMPP.php).
Jaxl magic method for calling XEP methods now logs a warning inside jaxl.log if XEP doesn't exists in the environment
- Added tag map for XMPP message thread and subject child elements
- Fixed typo where in case of streamError proper description namespace was not parsed/displayed
- Disabled BOSH session close if application is running in boshOut=false mode
Suggested by MOVIM dev team who were experiencing loss of session data on end of script
- JAXL::log method 2nd parameter now defaults to logLevel=1 (passing 2nd param is now optional)
- Fixed XPath for iq stanza error condition and error NS extraction inside jaxl.parser.class
- First checkin of XEP-0184 Message Receipts
- Added support for usage of name() xpath function inside tag maps of JAXLXml class.
Also added some documentation for methods available inside JAXLXml class
- Fixed JAXLPlugin::remove method to properly remove and manage callback registry.
Also added some documentation for JAXLPlugin class methods
- Added JAXL contructor config option to disable BOSH module auto-output behaviour.
This is utilized inside app/preFetchBOSH.php sample example
- First checkin of sample application code pre-fetching XMPP/Jabber data for web page population using BOSH XEP
- Added a sample application file which can be used to pre-fetch XMPP/Jabber data for a webpage without using BOSH XEP or Ajax requests
As per the discussion on google groups (http://bit.ly/aKavZB) with MOVIM team
- JAXL library is now $jaxl independent, you can use anything like $var = new JAXL(); instance your applications now
JAXLUtil::encryptPassword now accepts username/password during SASL auth.
Previously it used to auto detect the same from JAXL instance, now core has to manually pass these param
- Added JAXL::startHTTPd method with appropriate docblock on how to convert Jaxl instance into a Jaxl socket (web) server.
Comments also explains how to still maintaining XMPP communication in the background
- Updated JAXLHTTPd class to use new constants inside jaxl.ini
- Added jaxl_get_stream_error event handler.
Registered callback methods also receive array form of received XMPP XML stanza
- Connecting Jaxl instance now fallback to default value 'localhost' for host,domain,boshHost,boshPort,boshSuffix
If these values are not configured either using jaxl.ini constants or constructor
- Provided a sendIQ method per JAXL instance.
Recommended that applications and XEP's should directly use this method for sending <iq/> type stanza
DONOT use XMPPSend methods inside your application code from here on
- Added configuration options for JAXL HTTPd server and JAXL Bosh Component Manager inside jaxl.ini
- Fixed type in XEP-0202 (Entity Time). XEP was not sending <iq/> id in response to get request
- Jaxl library is now phpdocs ready. Added extended documentation for JAXL core class, rest to be added
- All core classes inside core/, xmpp/ and xep/ folder now make use of jaxl->log method
JAXL Core constructor are now well prepared so that inclusion of jaxl.ini is now optional
Application code too should use jaxl->log instead of JAXLog::log method for logging purpose
- Reshuffled core instance paramaters between JAXL and XMPP class
Also Jaxl core now logs at level 1 instead of 0 (i.e. all logs goes inside jaxl.log and not on console)
- JAXL class now make use of endStream method inside XMPP base class while disconnecting.
Also XMPPSend::endStream now forces xmpp stanza delivery (escaping JAXL internal buffer)
http://code.google.com/p/jaxl/issues/detail?id=23
- Added endStream method inside XMPP base class and startSession,startBind methods inside XMPPSend class
XMPP::sendXML now accepts a $force parameter for escaping XMPP stanza's from JAXL internal buffer
- Updated the way Jaxl core calls XEP 0115 method (entity caps) to match documentation
XEP method's should accept jaxl instance as first paramater
- First checkin of PEP (Personal Eventing), User Location, User Mood, User Activity and User Tune XEP's
- Completed methods discoFeatures, discoNodes, discoNodeInfo, discoNodeMeta and discoNodeItems in PubSub XEP
- Hardcoded client category, type, lang and name. TODO: Make them configurable in future
- Cleaned up XEP 0030 (Service Discovery) and XEP 0115 (Entity Capabilities)
- Updated XMPP base class to use performance configuration parameters (now customizable with JAXL constructor)
- jaxl.conf will be removed from jaxl core in future, 1st step towards this goal
- Moved bulk of core configs from jaxl.conf
- Added more configuration options relating to client performance e.g. getPkts, getPktSize etc
- Fixed client mode by detecting sapi type instead of $_REQUEST['jaxl'] variable
- Now every implemented XEP should have an 'init' method which will accept only one parameter (jaxl instance itself)
- Jaxl core now converts transmitted stanza's into xmlentities (http://code.google.com/p/jaxl/issues/detail?id=22)
- Created a top level 'patch' folder which contains various patches sent by developers using 'git diff > patch' utility
- Fixed typo in namespace inside 0030 (thanks to Thomas Baquet for the patch)
- First checkin of PubSub XEP (untested)
- Indented build.sh and moved define's from top of JAXLHTTPd class to jaxl.ini
- Added JAXLHTTPd inside Jaxl core (a simple socket select server)
- Fixed sync of background iq and other stanza requests with browser ajax calls
- Updated left out methods in XMPP over BOSH xep to accept jaxl instance as first method
- All XEP methods available in application landspace, now accepts jaxl instance as first parameter. Updated core jaxl class magic method to handle the same.
If you are calling XEP methods as specified in the documentation, this change will not hurt your running applications
- Updated echobot sample application to utilize XEP 0054 (VCard Temp) and 0202 (Entity Time)
- First checkin of missing vcard-temp xep
- Added xmlentities JAXLUtil method
- Jaxl Parser now default parses xXmlns node for message stanzas
- Added PCRE_DOTALL and PCRE_MULTILINE pattern modifier for bosh unwrapBody method
- Added utility methods like urldecode, urlencode, htmlEntities, stripHTML and splitJid inside jaxl.js
- Updated sample application jaxl.ini to reflect changes in env/jaxl.ini
version 2.1.1
-------------
- Updated XMPPSend 'presence', 'message' and 'iq' methods to accept $jaxl instance as first parameter
if you are not calling these methods directly from your application code as mentioned in documentation
this change should not hurt you
- Added more comments to env/jaxl.ini and also added JAXL_LOG_ROTATE ini file option
- JAXL instance logs can be rotated every x seconds (logRotate config parameter) now
- Removed config param dumpTime, instead use dumpStat to specify stats dump period
- Base XMPP class now auto-flush output buffers filled because of library level rate limiter
- Added more options for JAXL constructor e.g.
boshHost, boshPort, boshSuffix, pidPath, logPath, logLevel, dumpStat, dumpTime
These param overwrites value specified inside jaxl.ini file
Also JAXL core will now periodically dump instance statistics
- Added an option in JAXL constructor to disable inbuild core rate limiter
- Added support when applications need to connect with external bosh endpoints
Bosh application code requires update for ->JAXL0206('startStream') method
- XMPPGet::handler replaces ->handler inside XEP-0124
- JAXLCron job now also passes connected instance to callback cron methods
- Updated base XMPP class now maintains a clock, updated sendXML method to respect library level rate limiting
- Base JAXL class now includes JAXLCron class for periodically dumping connected bot memory/usage stats
- First version of JAXLCron class for adding periodic jobs in the background
- XMPP payload handler moves from XMPPGet to base XMPP class, packets are then routed to XMPPGet class for further processing
- Updated xep-0124 to use instance bosh parameters instead of values defined inside jaxl.ini
- Provision to specify custom JAXL_BOSH_HOST inside jaxl.ini
- Instead of global logLevel and logPath, logger class now respects indivisual instance log settings
Helpful in multiple instance applications
- Updated base JAXL class to accept various other configuration parameters inside constructor
These param overwrites values defined inside jaxl.ini
- XMPPSend::xml method moves inside XMPP::sendXML (call using ->sendXML from within application code), as a part of library core cleanup
- Updated jaxl class to return back payload from called xep methods
- XMPP base method getXML can be instructed not to take a nap between stream reads
- Added jaxl_get_xml hook for taking control over incoming xml payload from xmpp stream
- Added support for disabling sig term registration, required by applications who already handle this in their core code
- Added capability of sending multiple message/presence stanza in one go inside jaxl base class
- Fixed typo in MUC Direct Invitation xep invite method
- getHandler should have accepted core instance by reference, fixed now. BOSH MUC Chat sample application header is now more appropriate
version 2.1.0
-------------
- First checkin of bosh MUC sample application
- Updated build file now packages bosh MUC chat sample application along with core classes
- Updated JAXLog class to accept instance inside log() method, application code should use ->log() to call JAXLog::log() method now
- Updated JAXLPlugin class to pass instance along with every XMPP event hook
- Updated jaxl_require method to call including XEP's init() method every time they are included using jaxl_require method
- Update jaxl.ini with some documentation/comments about JAXL_BOSH_COOKIE_DOMAIN parameter
- Updated echobot sample application code to pass instance while calling jaxl_require method
- Update XMPP SASL Auth class to accept instance while calculating SASL response.
Also passinginstance when jaxl_get_facebook_key hook is called
- Updated XMPP base class to accept component host name inside constructor.
Sending currentinstance with every XMPPSend, XMPPGet and JAXLog method calls
- Every XMPPGet method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Every XMPPSend method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Updated component bot sample application to show how to pass component host inside JAXL constructor.
Also updated jaxl_require call to accept current working instance
- Updated boshchat sample application to follow new rules of jaxl_require, also cleaned up the sample app code a bit
- Updated jaxl.ini of packaged sample applications to match /env/jaxl.ini
- Updated implemented XEP's init method to accept instance during initialization step
Send working instance with every XMPPSend method call
Almost every XEP's available method now accepts an additional instance so that XEP's can work independently for every instance inside a multiple jaxl instance application code
- Added magic method __call inside JAXL class
All application codes should now call a methods inside implemented XEP's like ->JAXLxxxx('method', , , ...)
Also added ->log method to be used by application codes
JAXLog::log() should not be called directly from application code
Updated XMPPSend methods to accept instance
Added ->requires() method that does a similar job as jaxl_require() which now also expects instance as one of the passed parameter.
version 2.0.4
-------------
- Updated XMPP base class and XMPP Get class to utilize new XMPPAuth class
- Updated jaxl_require method with new XMPPAuth class path
- Extracted XMPP SASL auth mechanism out of XMPP Get class, code cleanup
- unwrapBody method of XEP 0124 is now public
- Added #News block on top of README
- No more capital true, false, null inside Jaxl core to pass PHP_CodeSniffer tests
- :retab Jaxl library core to pass PHP_CodeSniffer tests
- Added Jabber Component Protocol example application bot
- Updated README with documentation link for Jabber component protocol
- Updated Entity Caps method to use list of passed feature list for verification code generation
- Updated MUC available methods doc link inside README
- Added experimental support for SCRAM-SHA-1, CRAM-MD5 and LOGIN auth mechanisms
version 2.0.3
-------------
- Updated Jaxl XML parsing class to handle multiple level nested child cases
- Updated README and bosh chat application with documentation link
- Fixed bosh application to run on localhost
- Added doc links inside echobot sample app
- Bosh sample application also use entity time XEP-0202 now
- Fix for sapi detection inside jaxl util
- jaxl.js updated to handle multiple ajax poll response payloads
- Bosh session manager now dumps ajax poll response on post handler callback
- Removed hardcoded ajax poll url inside boshchat application
- Updated component protocol XEP pre handshake event handling
version 2.0.2
-------------
- Packaged XEP 0202 (Entity Time)
- First checkin of Bosh related XEP 0124 and 0206
- Sample Bosh Chat example application
- Updated jaxl.class.php to save Bosh request action parameter
- jaxl.ini updated with Bosh related cookie options, default loglevel now set to 4
- jaxl.js checkin which should be used with bosh applications
- Updated base xmpp classes to provide integrated bosh support
- Outgoing presence and message stanza's too can include @id attribute now
version 2.0.1
-------------
- Typo fix in JAXLXml::$tagMap for errorCode
- Fix for handling overflooded roster list
- Packaged XEP 0115 (Entity capability) and XEP 0199 (XMPP Ping)
- Updated sample echobot to use XEP 0115 and XEP 0199
- Support for X-FACEBOOK-PLATFORM authentication
version 2.0.0
--------------
First checkin of:
- Restructed core library with event mechanism
- Packaged XEP 0004, 0030, 0045, 0050, 0085, 0092, 0114, 0133, 0249
- Sample echobot application
diff --git a/core/jaxl.parser.php b/core/jaxl.parser.php
index 8d8bffc..4c7dcd7 100644
--- a/core/jaxl.parser.php
+++ b/core/jaxl.parser.php
@@ -1,296 +1,297 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl XML Parsing Framework
*/
class JAXLXml {
/**
* Contains XPath Map for various XMPP stream and stanza's
* http://tools.ietf.org/html/draft-ietf-xmpp-3920bis-18
*
*/
protected static $tagMap = array(
'starttls' => array(
'xmlns' => '//starttls/@xmlns'
),
'proceed' => array(
'xmlns' => '//proceed/@xmlns'
),
'challenge' => array(
'xmlns' => '//challenge/@xmlns',
'challenge' => '//challenge/text()'
),
'success' => array(
'xmlns' => '//success/@xmlns'
),
'failure' => array(
'xmlns' => '//failure/@xmlns',
'condition' => '//failure/*[1]/name()',
'desc' => '//failure/text',
'descLang' => '//failure/text/@xml:lang'
),
'message' => array(
'to' => '//message/@to',
'from' => '//message/@from',
'id' => '//message/@id',
'type' => '//message/@type',
'xml:lang' => '//message/@xml:lang',
'body' => '//message/body',
'subject' => '//message/subject',
'thread' => '//message/thread',
'xXmlns' => '//presence/x/@xmlns',
'errorType' => '//message/error/@type',
'errorCode' => '//message/error/@code'
),
'presence' => array(
'to' => '//presence/@to',
'from' => '//presence/@from',
'id' => '//presence/@id',
'type' => '//presence/@type',
'xml:lang' => '//presence/@xml:lang',
'show' => '//presence/show',
'status' => '//presence/status',
'priority' => '//presence/priority',
'xXmlns' => '//presence/x/@xmlns',
'errorType' => '//presence/error/@type',
'errorCode' => '//presence/error/@code'
),
'iq' => array(
'to' => '//iq/@to',
'from' => '//iq/@from',
'id' => '//iq/@id',
'type' => '//iq/@type',
'xml:lang' => '//iq/@xml:lang',
'bindResource' => '//iq/bind/resource',
'bindJid' => '//iq/bind/jid',
'queryXmlns'=> '//iq/query/@xmlns',
'queryVer' => '//iq/query/@ver',
'queryItemSub' => '//iq/query/item/@subscription',
'queryItemJid' => '//iq/query/item/@jid',
'queryItemName' => '//iq/query/item/@name',
'queryItemAsk' => '//iq/query/item/@ask',
'queryItemGrp' => '//iq/query/item/group',
'errorType' => '//iq/error/@type',
'errorCode' => '//iq/error/@code',
'errorCondition'=> '//iq/error/*[1]/name()',
'errorXmlns'=> '//iq/error/*[1]/@xmlns'
)
);
/**
* Parses passed $xml string and returns back parsed nodes as associative array
*
* Method assumes passed $xml parameter to be a single xmpp packet.
* This method only parses the node xpath mapping defined inside self::$tagMap
* Optionally, custom $tagMap can also be passed for parsing custom nodes for passed $xml string
*
* @param string $xml XML string to be parsed
* @param bool $sxe Whether method should return SimpleXMLElement object along with parsed nodes
* @param array $tagMap Custom tag mapping to be applied for this parse
*
* @return array $payload An associative array of parsed xpaths as specified inside tagMap
*/
public static function parse($xml, $sxe=false, &$tagMap=null) {
$payload = array();
$xml = str_replace('xmlns=', 'ns=', $xml);
- $xml = new SimpleXMLElement($xml);
+ try { $xml = @new SimpleXMLElement($xml); }
+ catch(Exception $e) { return false; }
$node = $xml->getName();
$parents = array();
if(!$tagMap)
$tagMap = &self::$tagMap[$node];
foreach($tagMap as $tag=>$xpath) {
$xpath = str_replace('/@xmlns', '/@ns', $xpath);
$parentXPath = implode('/', explode('/', $xpath, -1));
$tagXPath = str_replace($parentXPath.'/', '', $xpath);
// save parent XPath in buffer
if(!isset($parents[$parentXPath]))
$parents[$parentXPath] = $xml->xpath($parentXPath);
if(!is_array($parents[$parentXPath]))
continue;
// loop through all the extracted parent nodes
foreach($parents[$parentXPath] as $key=>$obj) {
//echo PHP_EOL."starting loop for tag: ".$tag.", xpath: ".$xpath.", parentXPath: ".$parentXPath.", tagXPath: ".$tagXPath." ======>".PHP_EOL;
//print_r($obj);
if($tagXPath == 'name()') {
$values = $obj->getName();
}
else if($tagXPath == 'text()') {
$values = array('0'=>(string)$obj);
}
else if($tagXPath == 'xml()') {
$values = $obj->asXML();
}
else if(substr($tagXPath, 0, 1) == '@') {
$txpath = str_replace('@', '', $tagXPath);
$values = $obj->attributes();
$values = (array)$values[$txpath];
unset($txpath);
}
else {
$values = $obj->{$tagXPath};
}
if(is_array($values) && sizeof($values) > 1) {
$temp = array();
foreach($values as $value) $temp[] = (string)$value[0];
$payload[$node][$tag][] = $temp;
unset($temp);
}
else if($tagXPath == 'name()') {
$payload[$node][$tag] = $values;
}
else if($tagXPath == 'xml()') {
$payload[$node][$tag] = $values;
}
else {
if(sizeof($parents[$parentXPath]) == 1) $payload[$node][$tag] = isset($values[0]) ? (string)$values[0] : null;
else $payload[$node][$tag][] = isset($values[0]) ? (string)$values[0] : null;
}
}
}
if($sxe) $payload['xml'] = $xml;
unset($xml);
return $payload;
}
/**
* Add node xpath and corresponding tag mapping for parser
*
* @param string $node Node for which this tag map should be parsed
* @param string $tag Tag associated with this xpath
* @param string $map XPath to be extracted
*/
public static function addTag($node, $tag, $map) {
self::$tagMap[$node][$tag] = $map;
}
/**
* Remove node xpath and corresponding tag mapping for parser
*
* @param string $node
* @param string $tag
*/
public static function removeTag($node, $tag) {
unset(self::$tagMap[$node][$tag]);
}
/**
* Creates XML string from passed $tagMap values
*
* @param array $tagVals
* @return string $xml
*/
public static function create($tagVals) {
foreach($tagVals as $node=>$tagVal) {
// initialize new XML document
$dom = new DOMDocument();
$superRoot = $dom->createElement($node);
$dom->appendChild($superRoot);
$childs = array();
// iterate over all tag values
foreach($tagVal as $tag=>$value) {
// find xpath where this $tag and $value should go
$xpath = self::$tagMap[$node][$tag];
// xpath parts for depth detection
$xpath = str_replace('//'.$node.'/', '', $xpath);
$xpart = explode('/', $xpath);
$depth = sizeof($xpart);
$root = $superRoot;
for($currDepth=0; $currDepth<$depth; $currDepth++) {
$element = $xpart[$currDepth];
$isAttr = (substr($element, 0, 1) == '@') ? true : false;
if($isAttr) {
$element = str_replace('@', '', $element);
$attr = $dom->createAttribute($element);
$root->appendChild($attr);
$text = $dom->createTextNode($value);
$attr->appendChild($text);
}
else {
if(!isset($childs[$currDepth][$element])) {
$child = $dom->createElement($element);
$root->appendChild($child);
$childs[$currDepth][$element] = true;
}
else if($currDepth == $depth-1) {
//echo ' value '.$value.PHP_EOL.PHP_EOL;
$text = $dom->createTextNode($value);
$child->appendChild($text);
}
$root = $child;
}
}
}
$xml = $dom->saveXML();
unset($dom); unset($attr); unset($child); unset($text);
return $xml;
}
}
}
?>
|
jaxl/JAXL | e29f04c0f2ad329ac994c25fa8a7f2243e6cfdd3 | Core logged class prefix log data with instance uid, pid and current clock | diff --git a/core/jaxl.cron.php b/core/jaxl.cron.php
index 0ea983a..4f5f52e 100644
--- a/core/jaxl.cron.php
+++ b/core/jaxl.cron.php
@@ -1,98 +1,94 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl Cron Job
*
* Add periodic cron in your xmpp applications
*/
class JAXLCron {
- private static $last = 0;
private static $cron = array();
public static function init($jaxl) {
$jaxl->addPlugin('jaxl_get_xml', array('JAXLCron', 'ticker'));
}
public static function ticker($payload, $jaxl) {
- if(self::$last == $jaxl->clock) return $payload;
-
foreach(self::$cron as $interval => $jobs) {
foreach($jobs as $key => $job) {
- if($jaxl->clock % $interval == 0 // if cron interval matches
- || $jaxl->clocked - $job['lastCall'] > $interval // if cron interval has already passed
+ if($jaxl->clock != 0
+ && $jaxl->clocked - $job['lastCall'] > $interval // if cron interval has already passed
) {
self::$cron[$interval][$key]['lastCall'] = $jaxl->clocked;
$arg = $job['arg'];
array_unshift($arg, $jaxl);
+
+ $jaxl->log("[[JAXLCron]] Executing cron job\nInterval:$interval, Callback:".$job['callback'], 5);
call_user_func_array($job['callback'], $arg);
}
}
}
-
- self::$last = $jaxl->clock;
return $payload;
}
public static function add(/* $callback, $interval, $param1, $param2, .. */) {
$arg = func_get_args();
$callback = array_shift($arg);
$interval = array_shift($arg);
-
self::$cron[$interval][self::generateCbSignature($callback)] = array('callback'=>$callback, 'arg'=>$arg, 'lastCall'=>time());
}
- public static function delete($callback, $interval) {
+ public static function delete($callback, $interval) {
$sig = self::generateCbSignature($callback);
if(isset(self::$cron[$interval][$sig]))
unset(self::$cron[$interval][$sig]);
}
protected static function generateCbSignature($callback) {
return is_array($callback) ? md5(json_encode($callback)) : md5($callback);
}
}
?>
diff --git a/core/jaxl.logger.php b/core/jaxl.logger.php
index a65237a..5d7a380 100644
--- a/core/jaxl.logger.php
+++ b/core/jaxl.logger.php
@@ -1,71 +1,71 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl Logging Class
*/
class JAXLog {
public static function log($log, $level=1, $jaxl=false) {
- $log = '['.$jaxl->pid.':'.$jaxl->uid.'] '.date('Y-m-d H:i:s')." - ".$log;
-
if($level <= $jaxl->logLevel
- ||($level == 0 && $jaxl->mode == "cli"))
- error_log($log."\n\n", 3, $jaxl->logPath);
+ ||($level == 0 && $jaxl->mode == "cli")) {
+ $log = '['.$jaxl->uid.':'.$jaxl->pid.':'.$jaxl->clock.'] '.date('Y-m-d H:i:s')." - ".$log;
+ error_log($log."\n\n", 3, $jaxl->logPath);
+ }
return true;
}
public static function logRotate($jaxl) {
if(copy($jaxl->logPath, $jaxl->logPath.'.'.date('Y-m-d-H-i-s')))
if($jaxl->mode == 'cli')
print '['.$jaxl->pid.':'.$jaxl->uid.'] '.date('Y-m-d H:i:s')." - Successfully rotated log file...\n";
$fh = fopen($jaxl->logPath, "r+");
ftruncate($fh, 1);
rewind($fh);
fclose($fh);
}
}
?>
|
jaxl/JAXL | e3c4e5a2a658ef3247c15fe3f60d5d4fdc8b57af | Simple method of issuing unique id to each connected jaxl instance. Improved dumpStat cron to include send/rcv rate, buffer sizes in stats | diff --git a/CHANGELOG b/CHANGELOG
index 034c1d1..46088a7 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,312 +1,314 @@
version 2.1.2
-------------
+- Simple method of issuing unique id to each connected jaxl instance
+ Improved dumpStat cron to include send/rcv rate, buffer sizes in stats
- Updated core class files to make use of JAXL::executePlugin method instead of JAXLPlugin::execute method
- XMPP base class now make use of socket_select() to poll opened stream efficiently (getting rid of annoying sleep)
Updated JAXLCron method to adjust to new core changes
- Added hook for jaxl_get_bosh_curl_error which is called when bosh end point returns a non-zero errno
Updated Jaxl core session variable names to avoid clash with existing session vars
Updated boshchat.php to make use of jaxl_get_bosh_curl_error to disconnect intelligently
- PHP CMS looking to integrate Jaxl in their core can now force disable auto start of php session by Jaxl core
Simple pass 'boshSession' as false with jaxl constructor config array
- Entire Jaxl core including xmpp/, xep/ and core/ class files now make use of JAXL::addPlugin instead of JAXLPlugin to register per instance callbacks
- JAXLPlugin can now register a callback for a dedicated jaxl instance in a multi-instance jaxl application
Class functionality remains backward compatible.
- JAXLog class now also dump connect instance uid per log line
- XMPP instance iq id now defaults to a random value between 1 and 9
Also added jaxl_get_id event hook for apps to customize iq id for the connected Jaxl instance
Also as compared to default numeric iq id, Jaxl core now uses hex iq id's
- Every jaxl instance per php process id now generate it's own unique id JAXL::$uid
- Jaxl core doesn't go for a session if it's optional as indicated by the xmpp server
- Fixed boshChat postBind issues as reported by issue#26 (http://code.google.com/p/jaxl/issues/detail?id=26)
- Fixed jaxl constructor config read warning and XEP 0114 now make use of JAXL::getConfigByPriority method
- Removed warning while reading user config inside Jaxl constructor
Upgraded Jaxl Parser class which was malfunctioning on CentOS PHP 5.1.6 (cli)
- Added bosh error response handling and appropriate logging inside XMPP over Bosh core files
- Code cleanup inside jaxl logger class.
Fixed getConfigByPriority method which was malfunctioning in specific cases
- JAXLog class now using inbuild php function (error_log)
- Checking in first version of XEP-0016 (Privacy Lists), XEP-0055 (Jabber Search), XEP-0077 (In-Band Registration), XEP-0144 (Roster Item Exchange), XEP-0153 (vCard-Based Avatars), XEP-0237 (Roster Versioning)
- On auth faliure core doesn't throw exception since XMPP over Bosh apps are not held inside a try catch block (a better fix may be possible in future)
- XMPP over BOSH xep wasn't passing back Jaxl instance obj for jaxl_post_disconnect hook, fixed that for clean disconnect
- Jaxl core attempts to create log and pid files if doesn't already exists
Also instead of die() core throws relevant exception message wherever required
XMPP base classes throws relevant exception with message wherever required
- First commit of JAXLException class. JAXL core now uses JAXLException
- Jaxl constructor dies if logPath, pidPath and tmpPath doesn't exists on the system
- Core updates JAXL::resource after successful binding to match resource assigned by the connecting server
- Updated echobot sample example to make use of autoSubscribe core feature
Also registers callback for jaxl_post_subscription_request and jaxl_post_subscription_accept hooks
- Updated echobot and boshchat application to use in memory roster cache maintained by Jaxl core.
App files should register callback on hook jaxl_post_roster_update to get notified everytime local roster cache is updated
- Added provision for local roster cache management inside Jaxl core.
Retrived roster lists are cached in memory (see updated echobot.php sample example).
Also added provision for presence tracking (JAXL::trackPresence).
If enabled Jaxl core keep a track of jid availability and update local roster cache accordingly.
Also added provision for auto-accept subscription (JAXL::autoSubscribe).
- Removed XMPP::isConnected variable which used to tell status of connected socket stream.
This is equivalent to checking XMPP:stream variable for true/false
- Added a (kind of) buggy support for '/xml()' inside parser xpath
- If Jaxl instance has being configured for auto periodic ping (XEP-0199), pings are holded till auth completion.
Also if server responds 'feature-not-implemented' for first ping XEP-0199 automatically deleted periodic ping cron tab
- Corrected handling of error type iq stanza's (removed jaxl_get_iq_error hook)
- Added iq error code xpath inside JAXLXml class
- Completed missing JAXLCron::delete method for removing a previously registered cron tab
- Checking in first version of XEP-0049 (Private XML Storage) (not yet tested)
- Checking in first version of XEP-0191 (Simple Communication Blocking) (not yet tested)
- Added JAXL_PING_INTERVAL configuration option inside jaxl.ini
- XEP-0199 (XMPP Ping) can now automatically ping the connected server periodically for keeping connection alive on long running bots
(see echobot.php sample app for usage)
- Updated JAXLCron::add method to accept a number of arguments while adding bckgrnd jobs
These list of arguments is passed back to the application method
- Updated IQ handling inside XEP-0202 which wasn't returning iq stanza back resulting in no ping/pong
- Updated echobot to show usage of JAXL::discoItems and JAXL::discoInfo inside application code
- Added tagMap xpath for service identity and feature nodes in service discovery resultset
- JAXL core now auto includes XEP-0128 along with XEP-0030 on startup.
Also added two methods JAXL::discoItems and JAXL::discoInfo for service discovery
- Checking in first version of XEP-0128 (Service Discovery Extension)
- Fixed bug where message and presence stanza builder were not using passed id value as attribute
- Removed jaxl_pre_curl event hook which was only used internally by XEP-0124
- Jaxl now shutdown gracefully is encryption is required and openssl PHP module is not loaded in the environment
- For every registered callback on XMPP hooks, callback'd method will receive two params.
A payload and reference of Jaxl instance for whom XMPP event has occured.
Updated sample application code to use passed back Jaxl instance reference instead of global jaxl variable.
- As a library convention XEP's exposing user space configuration parameters via JAXL constructor SHOULD utilize JAXL::getConfigByPriority method
Added JAXL_TMP_PATH option inside jaxl.ini
- Jaxl::tmp is now Jaxl::tmpPath. Also added Jaxl config param to specify custom tmp path location
Jaxl client also self detect the IP of the host it is running upon (to be used by STUN/TURN utilities in Jingle negotitation)
- Removed JAXLUtil::includePath and JAXLUtil::getAppFilePath methods which are now redundant after removing jaxl.ini and jaxl.conf from lib core
- Removed global defines JAXL_BASE_PATH, JAXL_APP_BASE_PATH, JAXL_BOSH_APP_ABS_PATH from inside jaxl.ini (No more required by apps to specify these values)
- Removing env/jaxl.php and env/jaxl.conf (were required if you run your apps using `jaxl` command line utility)
Updated env/jaxl.ini so that projects can now directly include their app setting via jaxl.ini (before including core/jaxl.class.php)
- Added JAXL::bareJid public variable for usage inside applications.
XMPP base class now return bool on socket connect completion (used by PHPUnit test cases)
- Removing build.sh file from library for next release
Users should simply download, extract, include and write their app code without caring about the build script from 2.1.2 release
- As a library convention to include XEP's use JAXL::requires() method, while to include any core/ or xmpp/ base class use jaxl_require() method.
Updated library code and xep's to adhere to this convention.
Jaxl instance now provide a system specific /tmp folder location accessible by JAXL::tmp
- Removed JAXL_NAME and JAXL_VERSION constants.
Instead const variables are now defined per instance accessible by getName() and getVersion() methods.
Updated XEP-0030,0092,0115 to use the same
- Moved indivisual XEP's working parameter (0114,0124) from JAXL core class to XEP classes itself.
XEP's make use of JAXL::config array for parsing user options.
- Added JAXL_COMPONENT_PASS option inside jaxl.ini. Updated build.sh with new /app file paths.
Updated XEP-0114,0124,0206 to use array style configs as defined inside JAXL class
- Removed dependency upon jaxl.ini from all sample applications.
First checkin of sample sendMessage.php app.
- Config parameters for XEP's like 0114 and 0206 are now saved as an array inside JAXL class (later on they will be moved inside respective XEP's).
Added constructor config option to pre-choose an auth mechanism to be performed
if an auth mech is pre-chosen app files SHOULD not register callback for jaxl_get_auth_mech hook.
Bosh cookie settings can now be passed along with Jaxl constructor.
Added support for publishing vcard-temp:x:update node along with presence stanzas.
Jaxl instance can run in 3 modes a.k.a. stream,component and bosh mode
applications should use JAXL::startCore('mode') to configure instance for a specific mode.
- Removed redundant NS variable from inside XEP-0124
- Moved JAXLHTTPd setting defines inside the class (if gone missing CPU usage peaks to 100%)
- Added jaxl_httpd_pre_shutdown, jaxl_httpd_get_http_request, jaxl_httpd_get_sock_request event hooks inside JAXLHTTPd class
- Added JAXLS5B path (SOCKS5 implementation) inside jaxl_require method
- Removed all occurance of JAXL::$action variable from /core and /xep class files
- Updated boshChat and boshMUChat sample application which no longer user JAXL::$action variable inside application code
- Updated preFetchBOSH and preFetchXMPP sample example.
Application code don't need any JAXL::$action variable now
Neither application code need to define JAXL_BASE_PATH (optional from now on)
- JAXL core and XEP-0206 have no relation and dependency upon JAXL::$action variable now.
- Deprecated jaxl_get_body hook which was only for XEP-0124 working.
Also cleaned up XEP-0124 code by removing processBody method which is now handled inside preHandler itself.
- Defining JAXL_BASE_PATH inside application code made optional.
Developers can directly include /path/to/jaxl/core/jaxl.class.php and start writing applications.
Also added a JAXL::startCore() method (see usage in /app/preFetchXMPP.php).
Jaxl magic method for calling XEP methods now logs a warning inside jaxl.log if XEP doesn't exists in the environment
- Added tag map for XMPP message thread and subject child elements
- Fixed typo where in case of streamError proper description namespace was not parsed/displayed
- Disabled BOSH session close if application is running in boshOut=false mode
Suggested by MOVIM dev team who were experiencing loss of session data on end of script
- JAXL::log method 2nd parameter now defaults to logLevel=1 (passing 2nd param is now optional)
- Fixed XPath for iq stanza error condition and error NS extraction inside jaxl.parser.class
- First checkin of XEP-0184 Message Receipts
- Added support for usage of name() xpath function inside tag maps of JAXLXml class.
Also added some documentation for methods available inside JAXLXml class
- Fixed JAXLPlugin::remove method to properly remove and manage callback registry.
Also added some documentation for JAXLPlugin class methods
- Added JAXL contructor config option to disable BOSH module auto-output behaviour.
This is utilized inside app/preFetchBOSH.php sample example
- First checkin of sample application code pre-fetching XMPP/Jabber data for web page population using BOSH XEP
- Added a sample application file which can be used to pre-fetch XMPP/Jabber data for a webpage without using BOSH XEP or Ajax requests
As per the discussion on google groups (http://bit.ly/aKavZB) with MOVIM team
- JAXL library is now $jaxl independent, you can use anything like $var = new JAXL(); instance your applications now
JAXLUtil::encryptPassword now accepts username/password during SASL auth.
Previously it used to auto detect the same from JAXL instance, now core has to manually pass these param
- Added JAXL::startHTTPd method with appropriate docblock on how to convert Jaxl instance into a Jaxl socket (web) server.
Comments also explains how to still maintaining XMPP communication in the background
- Updated JAXLHTTPd class to use new constants inside jaxl.ini
- Added jaxl_get_stream_error event handler.
Registered callback methods also receive array form of received XMPP XML stanza
- Connecting Jaxl instance now fallback to default value 'localhost' for host,domain,boshHost,boshPort,boshSuffix
If these values are not configured either using jaxl.ini constants or constructor
- Provided a sendIQ method per JAXL instance.
Recommended that applications and XEP's should directly use this method for sending <iq/> type stanza
DONOT use XMPPSend methods inside your application code from here on
- Added configuration options for JAXL HTTPd server and JAXL Bosh Component Manager inside jaxl.ini
- Fixed type in XEP-0202 (Entity Time). XEP was not sending <iq/> id in response to get request
- Jaxl library is now phpdocs ready. Added extended documentation for JAXL core class, rest to be added
- All core classes inside core/, xmpp/ and xep/ folder now make use of jaxl->log method
JAXL Core constructor are now well prepared so that inclusion of jaxl.ini is now optional
Application code too should use jaxl->log instead of JAXLog::log method for logging purpose
- Reshuffled core instance paramaters between JAXL and XMPP class
Also Jaxl core now logs at level 1 instead of 0 (i.e. all logs goes inside jaxl.log and not on console)
- JAXL class now make use of endStream method inside XMPP base class while disconnecting.
Also XMPPSend::endStream now forces xmpp stanza delivery (escaping JAXL internal buffer)
http://code.google.com/p/jaxl/issues/detail?id=23
- Added endStream method inside XMPP base class and startSession,startBind methods inside XMPPSend class
XMPP::sendXML now accepts a $force parameter for escaping XMPP stanza's from JAXL internal buffer
- Updated the way Jaxl core calls XEP 0115 method (entity caps) to match documentation
XEP method's should accept jaxl instance as first paramater
- First checkin of PEP (Personal Eventing), User Location, User Mood, User Activity and User Tune XEP's
- Completed methods discoFeatures, discoNodes, discoNodeInfo, discoNodeMeta and discoNodeItems in PubSub XEP
- Hardcoded client category, type, lang and name. TODO: Make them configurable in future
- Cleaned up XEP 0030 (Service Discovery) and XEP 0115 (Entity Capabilities)
- Updated XMPP base class to use performance configuration parameters (now customizable with JAXL constructor)
- jaxl.conf will be removed from jaxl core in future, 1st step towards this goal
- Moved bulk of core configs from jaxl.conf
- Added more configuration options relating to client performance e.g. getPkts, getPktSize etc
- Fixed client mode by detecting sapi type instead of $_REQUEST['jaxl'] variable
- Now every implemented XEP should have an 'init' method which will accept only one parameter (jaxl instance itself)
- Jaxl core now converts transmitted stanza's into xmlentities (http://code.google.com/p/jaxl/issues/detail?id=22)
- Created a top level 'patch' folder which contains various patches sent by developers using 'git diff > patch' utility
- Fixed typo in namespace inside 0030 (thanks to Thomas Baquet for the patch)
- First checkin of PubSub XEP (untested)
- Indented build.sh and moved define's from top of JAXLHTTPd class to jaxl.ini
- Added JAXLHTTPd inside Jaxl core (a simple socket select server)
- Fixed sync of background iq and other stanza requests with browser ajax calls
- Updated left out methods in XMPP over BOSH xep to accept jaxl instance as first method
- All XEP methods available in application landspace, now accepts jaxl instance as first parameter. Updated core jaxl class magic method to handle the same.
If you are calling XEP methods as specified in the documentation, this change will not hurt your running applications
- Updated echobot sample application to utilize XEP 0054 (VCard Temp) and 0202 (Entity Time)
- First checkin of missing vcard-temp xep
- Added xmlentities JAXLUtil method
- Jaxl Parser now default parses xXmlns node for message stanzas
- Added PCRE_DOTALL and PCRE_MULTILINE pattern modifier for bosh unwrapBody method
- Added utility methods like urldecode, urlencode, htmlEntities, stripHTML and splitJid inside jaxl.js
- Updated sample application jaxl.ini to reflect changes in env/jaxl.ini
version 2.1.1
-------------
- Updated XMPPSend 'presence', 'message' and 'iq' methods to accept $jaxl instance as first parameter
if you are not calling these methods directly from your application code as mentioned in documentation
this change should not hurt you
- Added more comments to env/jaxl.ini and also added JAXL_LOG_ROTATE ini file option
- JAXL instance logs can be rotated every x seconds (logRotate config parameter) now
- Removed config param dumpTime, instead use dumpStat to specify stats dump period
- Base XMPP class now auto-flush output buffers filled because of library level rate limiter
- Added more options for JAXL constructor e.g.
boshHost, boshPort, boshSuffix, pidPath, logPath, logLevel, dumpStat, dumpTime
These param overwrites value specified inside jaxl.ini file
Also JAXL core will now periodically dump instance statistics
- Added an option in JAXL constructor to disable inbuild core rate limiter
- Added support when applications need to connect with external bosh endpoints
Bosh application code requires update for ->JAXL0206('startStream') method
- XMPPGet::handler replaces ->handler inside XEP-0124
- JAXLCron job now also passes connected instance to callback cron methods
- Updated base XMPP class now maintains a clock, updated sendXML method to respect library level rate limiting
- Base JAXL class now includes JAXLCron class for periodically dumping connected bot memory/usage stats
- First version of JAXLCron class for adding periodic jobs in the background
- XMPP payload handler moves from XMPPGet to base XMPP class, packets are then routed to XMPPGet class for further processing
- Updated xep-0124 to use instance bosh parameters instead of values defined inside jaxl.ini
- Provision to specify custom JAXL_BOSH_HOST inside jaxl.ini
- Instead of global logLevel and logPath, logger class now respects indivisual instance log settings
Helpful in multiple instance applications
- Updated base JAXL class to accept various other configuration parameters inside constructor
These param overwrites values defined inside jaxl.ini
- XMPPSend::xml method moves inside XMPP::sendXML (call using ->sendXML from within application code), as a part of library core cleanup
- Updated jaxl class to return back payload from called xep methods
- XMPP base method getXML can be instructed not to take a nap between stream reads
- Added jaxl_get_xml hook for taking control over incoming xml payload from xmpp stream
- Added support for disabling sig term registration, required by applications who already handle this in their core code
- Added capability of sending multiple message/presence stanza in one go inside jaxl base class
- Fixed typo in MUC Direct Invitation xep invite method
- getHandler should have accepted core instance by reference, fixed now. BOSH MUC Chat sample application header is now more appropriate
version 2.1.0
-------------
- First checkin of bosh MUC sample application
- Updated build file now packages bosh MUC chat sample application along with core classes
- Updated JAXLog class to accept instance inside log() method, application code should use ->log() to call JAXLog::log() method now
- Updated JAXLPlugin class to pass instance along with every XMPP event hook
- Updated jaxl_require method to call including XEP's init() method every time they are included using jaxl_require method
- Update jaxl.ini with some documentation/comments about JAXL_BOSH_COOKIE_DOMAIN parameter
- Updated echobot sample application code to pass instance while calling jaxl_require method
- Update XMPP SASL Auth class to accept instance while calculating SASL response.
Also passinginstance when jaxl_get_facebook_key hook is called
- Updated XMPP base class to accept component host name inside constructor.
Sending currentinstance with every XMPPSend, XMPPGet and JAXLog method calls
- Every XMPPGet method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Every XMPPSend method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Updated component bot sample application to show how to pass component host inside JAXL constructor.
Also updated jaxl_require call to accept current working instance
- Updated boshchat sample application to follow new rules of jaxl_require, also cleaned up the sample app code a bit
- Updated jaxl.ini of packaged sample applications to match /env/jaxl.ini
- Updated implemented XEP's init method to accept instance during initialization step
Send working instance with every XMPPSend method call
Almost every XEP's available method now accepts an additional instance so that XEP's can work independently for every instance inside a multiple jaxl instance application code
- Added magic method __call inside JAXL class
All application codes should now call a methods inside implemented XEP's like ->JAXLxxxx('method', , , ...)
Also added ->log method to be used by application codes
JAXLog::log() should not be called directly from application code
Updated XMPPSend methods to accept instance
Added ->requires() method that does a similar job as jaxl_require() which now also expects instance as one of the passed parameter.
version 2.0.4
-------------
- Updated XMPP base class and XMPP Get class to utilize new XMPPAuth class
- Updated jaxl_require method with new XMPPAuth class path
- Extracted XMPP SASL auth mechanism out of XMPP Get class, code cleanup
- unwrapBody method of XEP 0124 is now public
- Added #News block on top of README
- No more capital true, false, null inside Jaxl core to pass PHP_CodeSniffer tests
- :retab Jaxl library core to pass PHP_CodeSniffer tests
- Added Jabber Component Protocol example application bot
- Updated README with documentation link for Jabber component protocol
- Updated Entity Caps method to use list of passed feature list for verification code generation
- Updated MUC available methods doc link inside README
- Added experimental support for SCRAM-SHA-1, CRAM-MD5 and LOGIN auth mechanisms
version 2.0.3
-------------
- Updated Jaxl XML parsing class to handle multiple level nested child cases
- Updated README and bosh chat application with documentation link
- Fixed bosh application to run on localhost
- Added doc links inside echobot sample app
- Bosh sample application also use entity time XEP-0202 now
- Fix for sapi detection inside jaxl util
- jaxl.js updated to handle multiple ajax poll response payloads
- Bosh session manager now dumps ajax poll response on post handler callback
- Removed hardcoded ajax poll url inside boshchat application
- Updated component protocol XEP pre handshake event handling
version 2.0.2
-------------
- Packaged XEP 0202 (Entity Time)
- First checkin of Bosh related XEP 0124 and 0206
- Sample Bosh Chat example application
- Updated jaxl.class.php to save Bosh request action parameter
- jaxl.ini updated with Bosh related cookie options, default loglevel now set to 4
- jaxl.js checkin which should be used with bosh applications
- Updated base xmpp classes to provide integrated bosh support
- Outgoing presence and message stanza's too can include @id attribute now
version 2.0.1
-------------
- Typo fix in JAXLXml::$tagMap for errorCode
- Fix for handling overflooded roster list
- Packaged XEP 0115 (Entity capability) and XEP 0199 (XMPP Ping)
- Updated sample echobot to use XEP 0115 and XEP 0199
- Support for X-FACEBOOK-PLATFORM authentication
version 2.0.0
--------------
First checkin of:
- Restructed core library with event mechanism
- Packaged XEP 0004, 0030, 0045, 0050, 0085, 0092, 0114, 0133, 0249
- Sample echobot application
diff --git a/core/jaxl.class.php b/core/jaxl.class.php
index a604277..a1d4250 100644
--- a/core/jaxl.class.php
+++ b/core/jaxl.class.php
@@ -1,884 +1,893 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
declare(ticks=1);
// Set JAXL_BASE_PATH if not already defined by application code
if(!@constant('JAXL_BASE_PATH'))
define('JAXL_BASE_PATH', dirname(dirname(__FILE__)));
/**
* Autoload method for Jaxl library and it's applications
*
* @param string|array $classNames core class name required in PHP environment
* @param object $jaxl Jaxl object which require these classes. Optional but always required while including implemented XEP's in PHP environment
*/
function jaxl_require($classNames, $jaxl=false) {
static $included = array();
$tagMap = array(
// core classes
'JAXLBosh' => '/core/jaxl.bosh.php',
'JAXLCron' => '/core/jaxl.cron.php',
'JAXLHTTPd' => '/core/jaxl.httpd.php',
'JAXLog' => '/core/jaxl.logger.php',
'JAXLXml' => '/core/jaxl.parser.php',
'JAXLPlugin' => '/core/jaxl.plugin.php',
'JAXLUtil' => '/core/jaxl.util.php',
'JAXLS5B' => '/core/jaxl.s5b.php',
'JAXLException' => '/core/jaxl.exception.php',
'XML' => '/core/jaxl.xml.php',
// xmpp classes
'XMPP' => '/xmpp/xmpp.class.php',
'XMPPGet' => '/xmpp/xmpp.get.php',
'XMPPSend' => '/xmpp/xmpp.send.php',
'XMPPAuth' => '/xmpp/xmpp.auth.php'
);
if(!is_array($classNames)) $classNames = array('0'=>$classNames);
foreach($classNames as $key => $className) {
$xep = substr($className, 4, 4);
if(substr($className, 0, 4) == 'JAXL'
&& is_numeric($xep)
) { // is XEP
if(!isset($included[$className])) {
require_once JAXL_BASE_PATH.'/xep/jaxl.'.$xep.'.php';
$included[$className] = true;
}
call_user_func(array('JAXL'.$xep, 'init'), $jaxl);
} // is Core file
else if(isset($tagMap[$className])) {
require_once JAXL_BASE_PATH.$tagMap[$className];
$included[$className] = true;
}
}
return;
}
// Include core classes and xmpp base
jaxl_require(array(
'JAXLog',
'JAXLUtil',
'JAXLPlugin',
'JAXLCron',
'JAXLException',
'XML',
'XMPP',
));
+
+ // number of running instance(s)
+ global $jaxl_instance_cnt;
+ $jaxl_instance_cnt = 1;
/**
* Jaxl class extending base XMPP class
*
* Jaxl library core is like any of your desktop Instant Messaging (IM) clients.
* Include Jaxl core in you application and start connecting and managing multiple XMPP accounts
* Packaged library is custom configured for running <b>single instance</b> Jaxl applications
*
* For connecting <b>multiple instance</b> XMPP accounts inside your application rewrite Jaxl controller
* using combination of env/jaxl.php, env/jaxl.ini and env/jaxl.conf
*/
class JAXL extends XMPP {
/**
* Client version of the connected Jaxl instance
*/
const version = '2.1.2';
/**
* Client name of the connected Jaxl instance
*/
const name = 'Jaxl :: Jabber XMPP Client Library';
/**
* Custom config passed to Jaxl constructor
*
* @var array
*/
var $config = array();
/**
* Username of connecting Jaxl instance
*
* @var string
*/
var $user = false;
/**
* Password of connecting Jaxl instance
*
* @var string
*/
var $pass = false;
/**
* Hostname for the connecting Jaxl instance
*
* @var string
*/
var $host = 'localhost';
/**
* Port for the connecting Jaxl instance
*
* @var integer
*/
var $port = 5222;
/**
* Full JID of the connected Jaxl instance
*
* @var string
*/
var $jid = false;
/**
* Bare JID of the connected Jaxl instance
*
* @var string
*/
var $bareJid = false;
/**
* Domain for the connecting Jaxl instance
*
* @var string
*/
var $domain = 'localhost';
/**
* Resource for the connecting Jaxl instance
*
* @var string
*/
var $resource = false;
/**
* Local cache of roster list and related info maintained by Jaxl instance
*/
var $roster = array();
/**
* Jaxl will track presence stanza's and update local $roster cache
*/
var $trackPresence = true;
/**
* Configure Jaxl instance to auto-accept subscription requests
*/
var $autoSubscribe = false;
/**
* Log Level of the connected Jaxl instance
*
* @var integer
*/
var $logLevel = 1;
/**
* Enable/Disable automatic log rotation for this Jaxl instance
*
* @var bool|integer
*/
var $logRotate = false;
/**
* Absolute path of log file for this Jaxl instance
*/
var $logPath = '/var/log/jaxl.log';
/**
* Absolute path of pid file for this Jaxl instance
*/
var $pidPath = '/var/run/jaxl.pid';
/**
* Enable/Disable shutdown callback on SIGH terms
*
* @var bool
*/
var $sigh = true;
/**
* Process Id of the connected Jaxl instance
*
* @var bool|integer
*/
var $pid = false;
/**
* Mode of the connected Jaxl instance (cgi or cli)
*
* @var bool|string
*/
var $mode = false;
/**
* Jabber auth mechanism performed by this Jaxl instance
*
* @var false|string
*/
var $authType = false;
/**
* Jaxl instance dumps usage statistics periodically. Disabled if set to "false"
*
* @var bool|integer
*/
var $dumpStat = 300;
/**
* List of XMPP feature supported by this Jaxl instance
*
* @var array
*/
var $features = array();
/**
* XMPP entity category for the connected Jaxl instance
*
* @var string
*/
var $category = 'client';
/**
* XMPP entity type for the connected Jaxl instance
*
* @var string
*/
var $type = 'bot';
/**
* Default language of the connected Jaxl instance
*/
var $lang = 'en';
/**
* Location to system temporary folder
*/
var $tmpPath = null;
/**
* IP address of the host Jaxl instance is running upon.
* To be used by STUN client implementations.
*/
var $ip = null;
/**
* PHP OpenSSL module info
*/
var $openSSL = false;
/**
* @return string $name Returns name of this Jaxl client
*/
function getName() {
return JAXL::name;
}
/**
* @return float $version Returns version of this Jaxl client
*/
function getVersion() {
return JAXL::version;
}
/**
* Discover items
*/
function discoItems($jid, $callback, $node=false) {
$this->JAXL0030('discoItems', $jid, $this->jid, $callback, $node);
}
/**
* Discover info
*/
function discoInfo($jid, $callback, $node=false) {
$this->JAXL0030('discoInfo', $jid, $this->jid, $callback, $node);
}
/**
* Shutdown Jaxl instance cleanly
*
* shutdown method is auto invoked when Jaxl instance receives a SIGH term.
* Before cleanly shutting down this method callbacks registered using <b>jaxl_pre_shutdown</b> hook.
*
* @param mixed $signal This is passed as paramater to callbacks registered using <b>jaxl_pre_shutdown</b> hook
*/
function shutdown($signal=false) {
$this->log("[[JAXL]] Shutting down ...");
$this->executePlugin('jaxl_pre_shutdown', $signal);
if($this->stream) $this->endStream();
$this->stream = false;
}
/**
* Perform authentication for connecting Jaxl instance
*
* @param string $type Authentication mechanism to proceed with. Supported auth types are:
* - DIGEST-MD5
* - PLAIN
* - X-FACEBOOK-PLATFORM
* - ANONYMOUS
*/
function auth($type) {
$this->authType = $type;
return XMPPSend::startAuth($this);
}
/**
* Set status of the connected Jaxl instance
*
* @param bool|string $status
* @param bool|string $show
* @param bool|integer $priority
* @param bool $caps
*/
function setStatus($status=false, $show=false, $priority=false, $caps=false, $vcard=false) {
$child = array();
$child['status'] = ($status === false ? 'Online using Jaxl library http://code.google.com/p/jaxl' : $status);
$child['show'] = ($show === false ? 'chat' : $show);
$child['priority'] = ($priority === false ? 1 : $priority);
if($caps) $child['payload'] = $this->JAXL0115('getCaps', $this->features);
if($vcard) $child['payload'] .= $this->JAXL0153('getUpdateData', false);
return XMPPSend::presence($this, false, false, $child, false);
}
/**
* Send authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send authorization request
*/
function subscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribe');
}
/**
* Accept authorization request from $toJid
*
* @param string $toJid JID who's authorization request Jaxl instance wants to accept
*/
function subscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribed');
}
/**
* Send cancel authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send cancel authorization request
*/
function unsubscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribe');
}
/**
* Accept cancel authorization request from $toJid
*
* @param string $toJid JID who's cancel authorization request Jaxl instance wants to accept
*/
function unsubscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribed');
}
/**
* Retrieve connected Jaxl instance roster list from the server
*
* @param mixed $callback Method to be callback'd when roster list is received from the server
*/
function getRosterList($callback=false) {
$payload = '<query xmlns="jabber:iq:roster"/>';
if($callback === false) $callback = array($this, '_handleRosterList');
return XMPPSend::iq($this, "get", $payload, false, $this->jid, $callback);
}
/**
* Add a new jabber account in connected Jaxl instance roster list
*
* @param string $jid JID to be added in the roster list
* @param string $group Group name
* @param bool|string $name Name of JID to be added
*/
function addRoster($jid, $group, $name=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Update subscription of a jabber account in roster list
*
* @param string $jid JID to be updated inside roster list
* @param string $group Updated group name
* @param bool|string $subscription Updated subscription type
*/
function updateRoster($jid, $group, $name=false, $subscription=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
if($subscription) $payload .= ' subscription="'.$subscription.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Delete a jabber account from roster list
*
* @param string $jid JID to be removed from the roster list
*/
function deleteRoster($jid) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'" subscription="remove">';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Send an XMPP message
*
* @param string $to JID to whom message is sent
* @param string $message Message to be sent
* @param string $from (Optional) JID from whom this message should be sent
* @param string $type (Optional) Type of message stanza to be delivered
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessage($to, $message, $from=false, $type='chat', $id=false) {
$child = array();
$child['body'] = $message;
return XMPPSend::message($this, $to, $from, $child, $type, $id);
}
/**
* Send multiple XMPP messages in one go
*
* @param array $to array of JID's to whom this presence stanza should be send
* @param array $from (Optional) array of JID from whom this presence stanza should originate
* @param array $child (Optional) array of arrays specifying child objects of the stanza
* @param array $type (Optional) array of type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessages($to, $from=false, $child=false, $type='chat', $id=false) {
return XMPPSend::message($this, $to, $from, $child, $type);
}
/**
* Send an XMPP presence stanza
*
* @param string $to (Optional) JID to whom this presence stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param array $child (Optional) array specifying child objects of the stanza
* @param string $type (Optional) Type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendPresence($to=false, $from=false, $child=false, $type=false, $id=false) {
return XMPPSend::presence($this, $to, $from, $child, $type, $id);
}
/**
* Send an XMPP iq stanza
*
* @param string $type Type of iq stanza to send
* @param string $payload (Optional) XML string to be transmitted
* @param string $to (Optional) JID to whom this iq stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param string|array $callback (Optional) Callback method which will handle "result" type stanza rcved
* @param integer $id (Optional) Add an id attribute to transmitted stanza (auto-generated if not provided)
*/
function sendIQ($type, $payload=false, $to=false, $from=false, $callback=false, $id=false) {
return XMPPSend::iq($this, $type, $payload, $to, $from, $callback, $id);
}
/**
* Logs library core and application debug data into the log file
*
* @param string $log Datum to be logged
* @param integer $level Log level for passed datum
*/
function log($log, $level=1) {
JAXLog::log($log, $level, $this);
}
/**
* Instead of using jaxl_require method applications can use $jaxl->requires to include XEP's in PHP environment
*
* @param string $class Class name of the XEP to be included e.g. JAXL0045 for including XEP-0045 a.k.a. Multi-user chat
*/
function requires($class) {
jaxl_require($class, $this);
}
/**
* Use this method instead of JAXLPlugin::add to register a callback for connected instance only
*/
function addPlugin($hook, $callback, $priority=10) {
JAXLPlugin::add($hook, $callback, $priority, $this->uid);
}
/**
* Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
*/
function removePlugin($hook, $callback, $priority=10) {
JAXLPlugin::remove($hook, $callback, $priority, $this->uid);
}
/**
* Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
*/
function executePlugin($hook, $payload) {
return JAXLPlugin::execute($hook, $payload, $this);
}
/**
* Starts Jaxl Core
*
* This method should be called after Jaxl initialization and hook registration inside your application code
* Optionally, you can pass 'jaxl_post_connect' and 'jaxl_get_auth_mech' response type directly to this method
* In that case application code SHOULD NOT register callbacks to above mentioned hooks
*
* @param string $arg[0] Optionally application code can pre-choose what Jaxl core should do after establishing socket connection.
* Following are the valid options:
* a) startStream
* b) startComponent
* c) startBosh
*/
function startCore($mode=false) {
if($mode) {
switch($mode) {
case 'stream':
$this->addPlugin('jaxl_post_connect', array($this, 'startStream'));
break;
case 'component':
$this->addPlugin('jaxl_post_connect', array($this, 'startComponent'));
break;
case 'bosh':
$this->startBosh();
break;
default:
break;
}
}
if($this->mode == 'cli') {
try {
if($this->connect()) {
while($this->stream) {
$this->getXML();
}
}
}
catch(JAXLException $e) {
die($e->getMessage());
}
/* Exit Jaxl after end of loop */
exit;
}
}
/**
* Starts a socket server at 127.0.0.1:port
*
* startHTTPd converts Jaxl instance into a Jaxl socket server (may or may not be a HTTP server)
* Same Jaxl socket server instance <b>SHOULD NOT</b> be used for XMPP communications.
* Instead separate "new Jaxl();" instances should be created for such XMPP communications.
*
* @param integer $port Port at which to start the socket server
* @param integer $maxq JAXLHTTPd socket server max queue
*/
function startHTTPd($port, $maxq) {
JAXLHTTPd::start(array(
'port' => $port,
'maxq' => $maxq
));
}
/**
* Start instance in bosh mode
*/
function startBosh() {
$this->JAXL0206('startStream');
}
/**
* Start instance in component mode
*/
function startComponent($payload, $jaxl) {
$this->JAXL0114('startStream', $payload);
}
/**
* Jaxl core constructor
*
* Jaxl instance configures itself using the constants inside your application jaxl.ini.
* However, passed array of configuration options overrides the value inside jaxl.ini.
* If no configuration are found or passed for a particular value,
* Jaxl falls back to default config options.
*
* @param $config Array of configuration options
* @todo Use DNS SRV lookup to set $jaxl->host from provided domain info
*/
function __construct($config=array()) {
+ global $jaxl_instance_cnt;
+ parent::__construct($config);
+
+ $this->uid = $jaxl_instance_cnt++;
$this->ip = gethostbyname(php_uname('n'));
$this->mode = (PHP_SAPI == "cli") ? PHP_SAPI : "cgi";
$this->config = $config;
$this->pid = getmypid();
- $this->uid = rand(10, 99999);
/* Mandatory params to be supplied either by jaxl.ini constants or constructor $config array */
$this->user = $this->getConfigByPriority(@$config['user'], "JAXL_USER_NAME", $this->user);
$this->pass = $this->getConfigByPriority(@$config['pass'], "JAXL_USER_PASS", $this->pass);
$this->domain = $this->getConfigByPriority(@$config['domain'], "JAXL_HOST_DOMAIN", $this->domain);
$this->bareJid = $this->user."@".$this->domain;
/* Optional params if not configured using jaxl.ini or $config take default values */
$this->host = $this->getConfigByPriority(@$config['host'], "JAXL_HOST_NAME", $this->domain);
$this->port = $this->getConfigByPriority(@$config['port'], "JAXL_HOST_PORT", $this->port);
- $this->resource = $this->getConfigByPriority(@$config['resource'], "JAXL_USER_RESC", "jaxl.".time());
+ $this->resource = $this->getConfigByPriority(@$config['resource'], "JAXL_USER_RESC", "jaxl.".$this->uid.".".$this->clocked);
$this->logLevel = $this->getConfigByPriority(@$config['logLevel'], "JAXL_LOG_LEVEL", $this->logLevel);
$this->logRotate = $this->getConfigByPriority(@$config['logRotate'], "JAXL_LOG_ROTATE", $this->logRotate);
$this->logPath = $this->getConfigByPriority(@$config['logPath'], "JAXL_LOG_PATH", $this->logPath);
if(!file_exists($this->logPath) && !touch($this->logPath)) throw new JAXLException("Log file ".$this->logPath." doesn't exists");
$this->pidPath = $this->getConfigByPriority(@$config['pidPath'], "JAXL_PID_PATH", $this->pidPath);
if($this->mode == "cli" && !file_exists($this->pidPath) && !touch($this->pidPath)) throw new JAXLException("Pid file ".$this->pidPath." doesn't exists");
/* Resolve temporary folder path */
if(function_exists('sys_get_temp_dir')) $this->tmpPath = sys_get_temp_dir();
$this->tmpPath = $this->getConfigByPriority(@$config['tmpPath'], "JAXL_TMP_PATH", $this->tmpPath);
if($this->tmpPath && !file_exists($this->tmpPath)) throw new JAXLException("Tmp directory ".$this->tmpPath." doesn't exists");
/* Handle pre-choosen auth type mechanism */
$this->authType = $this->getConfigByPriority(@$config['authType'], "JAXL_AUTH_TYPE", $this->authType);
if($this->authType) $this->addPlugin('jaxl_get_auth_mech', array($this, 'doAuth'));
/* Presence handling */
$this->trackPresence = isset($config['trackPresence']) ? $config['trackPresence'] : true;
$this->autoSubscribe = isset($config['autoSubscribe']) ? $config['autoSubscribe'] : false;
$this->addPlugin('jaxl_get_presence', array($this, '_handlePresence'), 0);
/* Optional params which can be configured only via constructor $config */
$this->sigh = isset($config['sigh']) ? $config['sigh'] : true;
$this->dumpStat = isset($config['dumpStat']) ? $config['dumpStat'] : 300;
- /* Configure instance for platforms and call parent construct */
+ /* Configure instance for platforms */
$this->configure($config);
- parent::__construct($config);
$this->xml = new XML();
/* Initialize JAXLCron and register instance cron jobs */
JAXLCron::init($this);
if($this->dumpStat) JAXLCron::add(array($this, 'dumpStat'), $this->dumpStat);
if($this->logRotate) JAXLCron::add(array('JAXLog', 'logRotate'), $this->logRotate);
// include service discovery XEP-0030 and it's extensions, recommended for every XMPP entity
$this->requires(array(
'JAXL0030',
'JAXL0128'
));
}
/**
* Return Jaxl instance config param depending upon user choice and default values
*/
function getConfigByPriority($config, $constant, $default) {
return ($config === null) ? (@constant($constant) === null ? $default : constant($constant)) : $config;
}
/**
* Configures Jaxl instance to run across various platforms (*nix/windows)
*
* Configure method tunes connecting Jaxl instance for
* OS compatibility, SSL support and dependencies over PHP methods
*/
protected function configure() {
// register shutdown function
if(!JAXLUtil::isWin() && JAXLUtil::pcntlEnabled() && $this->sigh) {
pcntl_signal(SIGTERM, array($this, "shutdown"));
pcntl_signal(SIGINT, array($this, "shutdown"));
- $this->log("[[JAXL]] Registering callbacks for CTRL+C and kill.");
+ $this->log("[[JAXL]] Registering callbacks for CTRL+C and kill.", 4);
}
else {
- $this->log("[[JAXL]] No callbacks registered for CTRL+C and kill.");
+ $this->log("[[JAXL]] No callbacks registered for CTRL+C and kill.", 4);
}
// check Jaxl dependency on PHP extension in cli mode
if($this->mode == "cli") {
if(($this->openSSL = JAXLUtil::sslEnabled()))
- $this->log("[[JAXL]] OpenSSL extension is loaded.");
+ $this->log("[[JAXL]] OpenSSL extension is loaded.", 4);
else
- $this->log("[[JAXL]] OpenSSL extension not loaded.");
+ $this->log("[[JAXL]] OpenSSL extension not loaded.", 4);
if(!function_exists('fsockopen'))
throw new JAXLException("[[JAXL]] Requires fsockopen method");
if(@is_writable($this->pidPath))
file_put_contents($this->pidPath, $this->pid);
}
// check Jaxl dependency on PHP extension in cgi mode
if($this->mode == "cgi") {
if(!function_exists('curl_init'))
throw new JAXLException("[[JAXL]] Requires CURL PHP extension");
if(!function_exists('json_encode'))
throw new JAXLException("[[JAXL]] Requires JSON PHP extension.");
}
}
/**
* Dumps Jaxl instance usage statistics
*
* Jaxl instance periodically calls this methods every JAXL::$dumpStat seconds.
*/
function dumpStat() {
- $stat = "[[JAXL]] Memory usage: ".round(memory_get_usage()/pow(1024,2), 2)." Mb";
- if(function_exists('memory_get_peak_usage'))
- $stat .= ", Peak usage: ".round(memory_get_peak_usage()/pow(1024,2), 2)." Mb";
- $this->log($stat, 0);
+ $stat = "[[JAXL]] Memory:".round(memory_get_usage()/pow(1024,2), 2)."Mb";
+ if(function_exists('memory_get_peak_usage')) $stat .= ", PeakMemory:".round(memory_get_peak_usage()/pow(1024,2), 2)."Mb";
+ $stat .= ", obuffer: ".strlen($this->obuffer);
+ $stat .= ", buffer: ".strlen($this->buffer);
+ $stat .= ", RcvdRate: ".$this->totalRcvdSize/$this->clock."Kb";
+ $stat .= ", SentRate: ".$this->totalSentSize/$this->clock."Kb";
+ $this->log($stat, 1);
}
/**
* Magic method for calling XEP's included by the JAXL instance
*
* Application <b>should never</b> call an XEP method directly using <code>JAXL0045::joinRoom()</code>
* instead use <code>$jaxl->JAXL0045('joinRoom', $param1, ..)</code> to call methods provided by included XEP's
*
* @param string $xep XMPP extension (XEP) class name e.g. JAXL0045 for XEP-0045 a.k.a. Multi-User chat extension
* @param array $param Array of parameters where $param[0]='methodName' is the method called inside JAXL0045 class
*
* @return mixed $return Return value of called XEP method
*/
function __call($xep, $param) {
$method = array_shift($param);
array_unshift($param, $this);
if(substr($xep, 0, 4) == 'JAXL') {
$xep = substr($xep, 4, 4);
if(is_numeric($xep)
&& class_exists('JAXL'.$xep)
) { return call_user_func_array(array('JAXL'.$xep, $method), $param); }
else { $this->log("[[JAXL]] JAXL$xep Doesn't exists in the environment"); }
}
}
/**
* Perform pre-choosen auth type for the Jaxl instance
*/
function doAuth($mechanism) {
return XMPPSend::startAuth($this);
}
/**
* Adds a node (if doesn't exists) for $jid inside local $roster cache
*/
function _addRosterNode($jid, $inRoster=true) {
if(!isset($this->roster[$jid]))
$this->roster[$jid] = array(
'groups'=>array(),
'name'=>'',
'subscription'=>'',
'presence'=>array(),
'inRoster'=>$inRoster
);
return;
}
/**
* Core method that accepts retrieved roster list and manage local cache
*/
function _handleRosterList($payload, $jaxl) {
- if(is_array($payload['queryItemJid'])) {
+ if(@is_array($payload['queryItemJid'])) {
foreach($payload['queryItemJid'] as $key=>$jid) {
$this->_addRosterNode($jid);
- $this->roster[$jid]['groups'] = $payload['queryItemGrp'][$key];
- $this->roster[$jid]['name'] = $payload['queryItemName'][$key];
- $this->roster[$jid]['subscription'] = $payload['queryItemSub'][$key];
+ $this->roster[$jid]['groups'] = @$payload['queryItemGrp'][$key];
+ $this->roster[$jid]['name'] = @$payload['queryItemName'][$key];
+ $this->roster[$jid]['subscription'] = @$payload['queryItemSub'][$key];
}
}
else {
- $jid = $payload['queryItemJid'];
+ $jid = @$payload['queryItemJid'];
$this->_addRosterNode($jid);
- $this->roster[$jid]['groups'] = $payload['queryItemGrp'];
- $this->roster[$jid]['name'] = $payload['queryItemName'];
- $this->roster[$jid]['subscription'] = $payload['queryItemSub'];
+ $this->roster[$jid]['groups'] = @$payload['queryItemGrp'];
+ $this->roster[$jid]['name'] = @$payload['queryItemName'];
+ $this->roster[$jid]['subscription'] = @$payload['queryItemSub'];
}
$this->executePlugin('jaxl_post_roster_update', $payload);
return $payload;
}
/**
* Tracks all incoming presence stanza's
*/
function _handlePresence($payloads, $jaxl) {
foreach($payloads as $payload) {
if($this->trackPresence) {
// update local $roster cache
$jid = JAXLUtil::getBareJid($payload['from']);
$this->_addRosterNode($jid, false);
if(!isset($this->roster[$jid]['presence'][$payload['from']])) $this->roster[$jid]['presence'][$payload['from']] = array();
$this->roster[$jid]['presence'][$payload['from']]['type'] = $payload['type'] == '' ? 'available' : $payload['type'];
$this->roster[$jid]['presence'][$payload['from']]['status'] = $payload['status'];
$this->roster[$jid]['presence'][$payload['from']]['show'] = $payload['show'];
$this->roster[$jid]['presence'][$payload['from']]['priority'] = $payload['priority'];
}
if($payload['type'] == 'subscribe'
&& $this->autoSubscribe
) {
$this->subscribed($payload['from']);
$this->subscribe($payload['from']);
$this->executePlugin('jaxl_post_subscription_request', $payload);
}
else if($payload['type'] == 'subscribed') {
$this->executePlugin('jaxl_post_subscription_accept', $payload);
}
}
return $payloads;
}
}
?>
|
jaxl/JAXL | 041d4d3ce9e597ccda18cd58a1fb8abcdcbf0f7a | Cleaned up XMPP base class after stream_select() usage and fixed typo inside JAXL base class | diff --git a/core/jaxl.class.php b/core/jaxl.class.php
index 1c449a7..a604277 100644
--- a/core/jaxl.class.php
+++ b/core/jaxl.class.php
@@ -60,825 +60,825 @@
'JAXLBosh' => '/core/jaxl.bosh.php',
'JAXLCron' => '/core/jaxl.cron.php',
'JAXLHTTPd' => '/core/jaxl.httpd.php',
'JAXLog' => '/core/jaxl.logger.php',
'JAXLXml' => '/core/jaxl.parser.php',
'JAXLPlugin' => '/core/jaxl.plugin.php',
'JAXLUtil' => '/core/jaxl.util.php',
'JAXLS5B' => '/core/jaxl.s5b.php',
'JAXLException' => '/core/jaxl.exception.php',
'XML' => '/core/jaxl.xml.php',
// xmpp classes
'XMPP' => '/xmpp/xmpp.class.php',
'XMPPGet' => '/xmpp/xmpp.get.php',
'XMPPSend' => '/xmpp/xmpp.send.php',
'XMPPAuth' => '/xmpp/xmpp.auth.php'
);
if(!is_array($classNames)) $classNames = array('0'=>$classNames);
foreach($classNames as $key => $className) {
$xep = substr($className, 4, 4);
if(substr($className, 0, 4) == 'JAXL'
&& is_numeric($xep)
) { // is XEP
if(!isset($included[$className])) {
require_once JAXL_BASE_PATH.'/xep/jaxl.'.$xep.'.php';
$included[$className] = true;
}
call_user_func(array('JAXL'.$xep, 'init'), $jaxl);
} // is Core file
else if(isset($tagMap[$className])) {
require_once JAXL_BASE_PATH.$tagMap[$className];
$included[$className] = true;
}
}
return;
}
// Include core classes and xmpp base
jaxl_require(array(
'JAXLog',
'JAXLUtil',
'JAXLPlugin',
'JAXLCron',
'JAXLException',
'XML',
'XMPP',
));
/**
* Jaxl class extending base XMPP class
*
* Jaxl library core is like any of your desktop Instant Messaging (IM) clients.
* Include Jaxl core in you application and start connecting and managing multiple XMPP accounts
* Packaged library is custom configured for running <b>single instance</b> Jaxl applications
*
* For connecting <b>multiple instance</b> XMPP accounts inside your application rewrite Jaxl controller
* using combination of env/jaxl.php, env/jaxl.ini and env/jaxl.conf
*/
class JAXL extends XMPP {
/**
* Client version of the connected Jaxl instance
*/
const version = '2.1.2';
/**
* Client name of the connected Jaxl instance
*/
const name = 'Jaxl :: Jabber XMPP Client Library';
/**
* Custom config passed to Jaxl constructor
*
* @var array
*/
var $config = array();
/**
* Username of connecting Jaxl instance
*
* @var string
*/
var $user = false;
/**
* Password of connecting Jaxl instance
*
* @var string
*/
var $pass = false;
/**
* Hostname for the connecting Jaxl instance
*
* @var string
*/
var $host = 'localhost';
/**
* Port for the connecting Jaxl instance
*
* @var integer
*/
var $port = 5222;
/**
* Full JID of the connected Jaxl instance
*
* @var string
*/
var $jid = false;
/**
* Bare JID of the connected Jaxl instance
*
* @var string
*/
var $bareJid = false;
/**
* Domain for the connecting Jaxl instance
*
* @var string
*/
var $domain = 'localhost';
/**
* Resource for the connecting Jaxl instance
*
* @var string
*/
var $resource = false;
/**
* Local cache of roster list and related info maintained by Jaxl instance
*/
var $roster = array();
/**
* Jaxl will track presence stanza's and update local $roster cache
*/
var $trackPresence = true;
/**
* Configure Jaxl instance to auto-accept subscription requests
*/
var $autoSubscribe = false;
/**
* Log Level of the connected Jaxl instance
*
* @var integer
*/
var $logLevel = 1;
/**
* Enable/Disable automatic log rotation for this Jaxl instance
*
* @var bool|integer
*/
var $logRotate = false;
/**
* Absolute path of log file for this Jaxl instance
*/
var $logPath = '/var/log/jaxl.log';
/**
* Absolute path of pid file for this Jaxl instance
*/
var $pidPath = '/var/run/jaxl.pid';
/**
* Enable/Disable shutdown callback on SIGH terms
*
* @var bool
*/
var $sigh = true;
/**
* Process Id of the connected Jaxl instance
*
* @var bool|integer
*/
var $pid = false;
/**
* Mode of the connected Jaxl instance (cgi or cli)
*
* @var bool|string
*/
var $mode = false;
/**
* Jabber auth mechanism performed by this Jaxl instance
*
* @var false|string
*/
var $authType = false;
/**
* Jaxl instance dumps usage statistics periodically. Disabled if set to "false"
*
* @var bool|integer
*/
var $dumpStat = 300;
/**
* List of XMPP feature supported by this Jaxl instance
*
* @var array
*/
var $features = array();
/**
* XMPP entity category for the connected Jaxl instance
*
* @var string
*/
var $category = 'client';
/**
* XMPP entity type for the connected Jaxl instance
*
* @var string
*/
var $type = 'bot';
/**
* Default language of the connected Jaxl instance
*/
var $lang = 'en';
/**
* Location to system temporary folder
*/
var $tmpPath = null;
/**
* IP address of the host Jaxl instance is running upon.
* To be used by STUN client implementations.
*/
var $ip = null;
/**
* PHP OpenSSL module info
*/
var $openSSL = false;
/**
* @return string $name Returns name of this Jaxl client
*/
function getName() {
return JAXL::name;
}
/**
* @return float $version Returns version of this Jaxl client
*/
function getVersion() {
return JAXL::version;
}
/**
* Discover items
*/
function discoItems($jid, $callback, $node=false) {
$this->JAXL0030('discoItems', $jid, $this->jid, $callback, $node);
}
/**
* Discover info
*/
function discoInfo($jid, $callback, $node=false) {
$this->JAXL0030('discoInfo', $jid, $this->jid, $callback, $node);
}
/**
* Shutdown Jaxl instance cleanly
*
* shutdown method is auto invoked when Jaxl instance receives a SIGH term.
* Before cleanly shutting down this method callbacks registered using <b>jaxl_pre_shutdown</b> hook.
*
* @param mixed $signal This is passed as paramater to callbacks registered using <b>jaxl_pre_shutdown</b> hook
*/
function shutdown($signal=false) {
$this->log("[[JAXL]] Shutting down ...");
$this->executePlugin('jaxl_pre_shutdown', $signal);
if($this->stream) $this->endStream();
$this->stream = false;
}
/**
* Perform authentication for connecting Jaxl instance
*
* @param string $type Authentication mechanism to proceed with. Supported auth types are:
* - DIGEST-MD5
* - PLAIN
* - X-FACEBOOK-PLATFORM
* - ANONYMOUS
*/
function auth($type) {
$this->authType = $type;
return XMPPSend::startAuth($this);
}
/**
* Set status of the connected Jaxl instance
*
* @param bool|string $status
* @param bool|string $show
* @param bool|integer $priority
* @param bool $caps
*/
function setStatus($status=false, $show=false, $priority=false, $caps=false, $vcard=false) {
$child = array();
$child['status'] = ($status === false ? 'Online using Jaxl library http://code.google.com/p/jaxl' : $status);
$child['show'] = ($show === false ? 'chat' : $show);
$child['priority'] = ($priority === false ? 1 : $priority);
if($caps) $child['payload'] = $this->JAXL0115('getCaps', $this->features);
if($vcard) $child['payload'] .= $this->JAXL0153('getUpdateData', false);
return XMPPSend::presence($this, false, false, $child, false);
}
/**
* Send authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send authorization request
*/
function subscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribe');
}
/**
* Accept authorization request from $toJid
*
* @param string $toJid JID who's authorization request Jaxl instance wants to accept
*/
function subscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribed');
}
/**
* Send cancel authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send cancel authorization request
*/
function unsubscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribe');
}
/**
* Accept cancel authorization request from $toJid
*
* @param string $toJid JID who's cancel authorization request Jaxl instance wants to accept
*/
function unsubscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribed');
}
/**
* Retrieve connected Jaxl instance roster list from the server
*
* @param mixed $callback Method to be callback'd when roster list is received from the server
*/
function getRosterList($callback=false) {
$payload = '<query xmlns="jabber:iq:roster"/>';
if($callback === false) $callback = array($this, '_handleRosterList');
return XMPPSend::iq($this, "get", $payload, false, $this->jid, $callback);
}
/**
* Add a new jabber account in connected Jaxl instance roster list
*
* @param string $jid JID to be added in the roster list
* @param string $group Group name
* @param bool|string $name Name of JID to be added
*/
function addRoster($jid, $group, $name=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Update subscription of a jabber account in roster list
*
* @param string $jid JID to be updated inside roster list
* @param string $group Updated group name
* @param bool|string $subscription Updated subscription type
*/
function updateRoster($jid, $group, $name=false, $subscription=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
if($subscription) $payload .= ' subscription="'.$subscription.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Delete a jabber account from roster list
*
* @param string $jid JID to be removed from the roster list
*/
function deleteRoster($jid) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'" subscription="remove">';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Send an XMPP message
*
* @param string $to JID to whom message is sent
* @param string $message Message to be sent
* @param string $from (Optional) JID from whom this message should be sent
* @param string $type (Optional) Type of message stanza to be delivered
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessage($to, $message, $from=false, $type='chat', $id=false) {
$child = array();
$child['body'] = $message;
return XMPPSend::message($this, $to, $from, $child, $type, $id);
}
/**
* Send multiple XMPP messages in one go
*
* @param array $to array of JID's to whom this presence stanza should be send
* @param array $from (Optional) array of JID from whom this presence stanza should originate
* @param array $child (Optional) array of arrays specifying child objects of the stanza
* @param array $type (Optional) array of type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessages($to, $from=false, $child=false, $type='chat', $id=false) {
return XMPPSend::message($this, $to, $from, $child, $type);
}
/**
* Send an XMPP presence stanza
*
* @param string $to (Optional) JID to whom this presence stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param array $child (Optional) array specifying child objects of the stanza
* @param string $type (Optional) Type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendPresence($to=false, $from=false, $child=false, $type=false, $id=false) {
return XMPPSend::presence($this, $to, $from, $child, $type, $id);
}
/**
* Send an XMPP iq stanza
*
* @param string $type Type of iq stanza to send
* @param string $payload (Optional) XML string to be transmitted
* @param string $to (Optional) JID to whom this iq stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param string|array $callback (Optional) Callback method which will handle "result" type stanza rcved
* @param integer $id (Optional) Add an id attribute to transmitted stanza (auto-generated if not provided)
*/
function sendIQ($type, $payload=false, $to=false, $from=false, $callback=false, $id=false) {
return XMPPSend::iq($this, $type, $payload, $to, $from, $callback, $id);
}
/**
* Logs library core and application debug data into the log file
*
* @param string $log Datum to be logged
* @param integer $level Log level for passed datum
*/
function log($log, $level=1) {
JAXLog::log($log, $level, $this);
}
/**
* Instead of using jaxl_require method applications can use $jaxl->requires to include XEP's in PHP environment
*
* @param string $class Class name of the XEP to be included e.g. JAXL0045 for including XEP-0045 a.k.a. Multi-user chat
*/
function requires($class) {
jaxl_require($class, $this);
}
/**
* Use this method instead of JAXLPlugin::add to register a callback for connected instance only
*/
function addPlugin($hook, $callback, $priority=10) {
JAXLPlugin::add($hook, $callback, $priority, $this->uid);
}
/**
* Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
*/
function removePlugin($hook, $callback, $priority=10) {
JAXLPlugin::remove($hook, $callback, $priority, $this->uid);
}
/**
* Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
*/
- function executePlugin($hook, $callback, $priority=10) {
- JAXLPlugin::execute($hook, $callback, $priority, $this);
+ function executePlugin($hook, $payload) {
+ return JAXLPlugin::execute($hook, $payload, $this);
}
/**
* Starts Jaxl Core
*
* This method should be called after Jaxl initialization and hook registration inside your application code
* Optionally, you can pass 'jaxl_post_connect' and 'jaxl_get_auth_mech' response type directly to this method
* In that case application code SHOULD NOT register callbacks to above mentioned hooks
*
* @param string $arg[0] Optionally application code can pre-choose what Jaxl core should do after establishing socket connection.
* Following are the valid options:
* a) startStream
* b) startComponent
* c) startBosh
*/
function startCore($mode=false) {
if($mode) {
switch($mode) {
case 'stream':
$this->addPlugin('jaxl_post_connect', array($this, 'startStream'));
break;
case 'component':
$this->addPlugin('jaxl_post_connect', array($this, 'startComponent'));
break;
case 'bosh':
$this->startBosh();
break;
default:
break;
}
}
if($this->mode == 'cli') {
try {
if($this->connect()) {
while($this->stream) {
$this->getXML();
}
}
}
catch(JAXLException $e) {
die($e->getMessage());
}
/* Exit Jaxl after end of loop */
exit;
}
}
/**
* Starts a socket server at 127.0.0.1:port
*
* startHTTPd converts Jaxl instance into a Jaxl socket server (may or may not be a HTTP server)
* Same Jaxl socket server instance <b>SHOULD NOT</b> be used for XMPP communications.
* Instead separate "new Jaxl();" instances should be created for such XMPP communications.
*
* @param integer $port Port at which to start the socket server
* @param integer $maxq JAXLHTTPd socket server max queue
*/
function startHTTPd($port, $maxq) {
JAXLHTTPd::start(array(
'port' => $port,
'maxq' => $maxq
));
}
/**
* Start instance in bosh mode
*/
function startBosh() {
$this->JAXL0206('startStream');
}
/**
* Start instance in component mode
*/
function startComponent($payload, $jaxl) {
$this->JAXL0114('startStream', $payload);
}
/**
* Jaxl core constructor
*
* Jaxl instance configures itself using the constants inside your application jaxl.ini.
* However, passed array of configuration options overrides the value inside jaxl.ini.
* If no configuration are found or passed for a particular value,
* Jaxl falls back to default config options.
*
* @param $config Array of configuration options
* @todo Use DNS SRV lookup to set $jaxl->host from provided domain info
*/
function __construct($config=array()) {
$this->ip = gethostbyname(php_uname('n'));
$this->mode = (PHP_SAPI == "cli") ? PHP_SAPI : "cgi";
$this->config = $config;
$this->pid = getmypid();
$this->uid = rand(10, 99999);
/* Mandatory params to be supplied either by jaxl.ini constants or constructor $config array */
$this->user = $this->getConfigByPriority(@$config['user'], "JAXL_USER_NAME", $this->user);
$this->pass = $this->getConfigByPriority(@$config['pass'], "JAXL_USER_PASS", $this->pass);
$this->domain = $this->getConfigByPriority(@$config['domain'], "JAXL_HOST_DOMAIN", $this->domain);
$this->bareJid = $this->user."@".$this->domain;
/* Optional params if not configured using jaxl.ini or $config take default values */
$this->host = $this->getConfigByPriority(@$config['host'], "JAXL_HOST_NAME", $this->domain);
$this->port = $this->getConfigByPriority(@$config['port'], "JAXL_HOST_PORT", $this->port);
$this->resource = $this->getConfigByPriority(@$config['resource'], "JAXL_USER_RESC", "jaxl.".time());
$this->logLevel = $this->getConfigByPriority(@$config['logLevel'], "JAXL_LOG_LEVEL", $this->logLevel);
$this->logRotate = $this->getConfigByPriority(@$config['logRotate'], "JAXL_LOG_ROTATE", $this->logRotate);
$this->logPath = $this->getConfigByPriority(@$config['logPath'], "JAXL_LOG_PATH", $this->logPath);
if(!file_exists($this->logPath) && !touch($this->logPath)) throw new JAXLException("Log file ".$this->logPath." doesn't exists");
$this->pidPath = $this->getConfigByPriority(@$config['pidPath'], "JAXL_PID_PATH", $this->pidPath);
if($this->mode == "cli" && !file_exists($this->pidPath) && !touch($this->pidPath)) throw new JAXLException("Pid file ".$this->pidPath." doesn't exists");
/* Resolve temporary folder path */
if(function_exists('sys_get_temp_dir')) $this->tmpPath = sys_get_temp_dir();
$this->tmpPath = $this->getConfigByPriority(@$config['tmpPath'], "JAXL_TMP_PATH", $this->tmpPath);
if($this->tmpPath && !file_exists($this->tmpPath)) throw new JAXLException("Tmp directory ".$this->tmpPath." doesn't exists");
/* Handle pre-choosen auth type mechanism */
$this->authType = $this->getConfigByPriority(@$config['authType'], "JAXL_AUTH_TYPE", $this->authType);
if($this->authType) $this->addPlugin('jaxl_get_auth_mech', array($this, 'doAuth'));
/* Presence handling */
$this->trackPresence = isset($config['trackPresence']) ? $config['trackPresence'] : true;
$this->autoSubscribe = isset($config['autoSubscribe']) ? $config['autoSubscribe'] : false;
$this->addPlugin('jaxl_get_presence', array($this, '_handlePresence'), 0);
/* Optional params which can be configured only via constructor $config */
$this->sigh = isset($config['sigh']) ? $config['sigh'] : true;
$this->dumpStat = isset($config['dumpStat']) ? $config['dumpStat'] : 300;
/* Configure instance for platforms and call parent construct */
$this->configure($config);
parent::__construct($config);
$this->xml = new XML();
/* Initialize JAXLCron and register instance cron jobs */
JAXLCron::init($this);
if($this->dumpStat) JAXLCron::add(array($this, 'dumpStat'), $this->dumpStat);
if($this->logRotate) JAXLCron::add(array('JAXLog', 'logRotate'), $this->logRotate);
// include service discovery XEP-0030 and it's extensions, recommended for every XMPP entity
$this->requires(array(
'JAXL0030',
'JAXL0128'
));
}
/**
* Return Jaxl instance config param depending upon user choice and default values
*/
function getConfigByPriority($config, $constant, $default) {
return ($config === null) ? (@constant($constant) === null ? $default : constant($constant)) : $config;
}
/**
* Configures Jaxl instance to run across various platforms (*nix/windows)
*
* Configure method tunes connecting Jaxl instance for
* OS compatibility, SSL support and dependencies over PHP methods
*/
protected function configure() {
// register shutdown function
if(!JAXLUtil::isWin() && JAXLUtil::pcntlEnabled() && $this->sigh) {
pcntl_signal(SIGTERM, array($this, "shutdown"));
pcntl_signal(SIGINT, array($this, "shutdown"));
$this->log("[[JAXL]] Registering callbacks for CTRL+C and kill.");
}
else {
$this->log("[[JAXL]] No callbacks registered for CTRL+C and kill.");
}
// check Jaxl dependency on PHP extension in cli mode
if($this->mode == "cli") {
if(($this->openSSL = JAXLUtil::sslEnabled()))
$this->log("[[JAXL]] OpenSSL extension is loaded.");
else
$this->log("[[JAXL]] OpenSSL extension not loaded.");
if(!function_exists('fsockopen'))
throw new JAXLException("[[JAXL]] Requires fsockopen method");
if(@is_writable($this->pidPath))
file_put_contents($this->pidPath, $this->pid);
}
// check Jaxl dependency on PHP extension in cgi mode
if($this->mode == "cgi") {
if(!function_exists('curl_init'))
throw new JAXLException("[[JAXL]] Requires CURL PHP extension");
if(!function_exists('json_encode'))
throw new JAXLException("[[JAXL]] Requires JSON PHP extension.");
}
}
/**
* Dumps Jaxl instance usage statistics
*
* Jaxl instance periodically calls this methods every JAXL::$dumpStat seconds.
*/
function dumpStat() {
$stat = "[[JAXL]] Memory usage: ".round(memory_get_usage()/pow(1024,2), 2)." Mb";
if(function_exists('memory_get_peak_usage'))
$stat .= ", Peak usage: ".round(memory_get_peak_usage()/pow(1024,2), 2)." Mb";
$this->log($stat, 0);
}
/**
* Magic method for calling XEP's included by the JAXL instance
*
* Application <b>should never</b> call an XEP method directly using <code>JAXL0045::joinRoom()</code>
* instead use <code>$jaxl->JAXL0045('joinRoom', $param1, ..)</code> to call methods provided by included XEP's
*
* @param string $xep XMPP extension (XEP) class name e.g. JAXL0045 for XEP-0045 a.k.a. Multi-User chat extension
* @param array $param Array of parameters where $param[0]='methodName' is the method called inside JAXL0045 class
*
* @return mixed $return Return value of called XEP method
*/
function __call($xep, $param) {
$method = array_shift($param);
array_unshift($param, $this);
if(substr($xep, 0, 4) == 'JAXL') {
$xep = substr($xep, 4, 4);
if(is_numeric($xep)
&& class_exists('JAXL'.$xep)
) { return call_user_func_array(array('JAXL'.$xep, $method), $param); }
else { $this->log("[[JAXL]] JAXL$xep Doesn't exists in the environment"); }
}
}
/**
* Perform pre-choosen auth type for the Jaxl instance
*/
function doAuth($mechanism) {
return XMPPSend::startAuth($this);
}
/**
* Adds a node (if doesn't exists) for $jid inside local $roster cache
*/
function _addRosterNode($jid, $inRoster=true) {
if(!isset($this->roster[$jid]))
$this->roster[$jid] = array(
'groups'=>array(),
'name'=>'',
'subscription'=>'',
'presence'=>array(),
'inRoster'=>$inRoster
);
return;
}
/**
* Core method that accepts retrieved roster list and manage local cache
*/
function _handleRosterList($payload, $jaxl) {
if(is_array($payload['queryItemJid'])) {
foreach($payload['queryItemJid'] as $key=>$jid) {
$this->_addRosterNode($jid);
$this->roster[$jid]['groups'] = $payload['queryItemGrp'][$key];
$this->roster[$jid]['name'] = $payload['queryItemName'][$key];
$this->roster[$jid]['subscription'] = $payload['queryItemSub'][$key];
}
}
else {
$jid = $payload['queryItemJid'];
$this->_addRosterNode($jid);
$this->roster[$jid]['groups'] = $payload['queryItemGrp'];
$this->roster[$jid]['name'] = $payload['queryItemName'];
$this->roster[$jid]['subscription'] = $payload['queryItemSub'];
}
$this->executePlugin('jaxl_post_roster_update', $payload);
return $payload;
}
/**
* Tracks all incoming presence stanza's
*/
function _handlePresence($payloads, $jaxl) {
foreach($payloads as $payload) {
if($this->trackPresence) {
// update local $roster cache
$jid = JAXLUtil::getBareJid($payload['from']);
$this->_addRosterNode($jid, false);
if(!isset($this->roster[$jid]['presence'][$payload['from']])) $this->roster[$jid]['presence'][$payload['from']] = array();
$this->roster[$jid]['presence'][$payload['from']]['type'] = $payload['type'] == '' ? 'available' : $payload['type'];
$this->roster[$jid]['presence'][$payload['from']]['status'] = $payload['status'];
$this->roster[$jid]['presence'][$payload['from']]['show'] = $payload['show'];
$this->roster[$jid]['presence'][$payload['from']]['priority'] = $payload['priority'];
}
if($payload['type'] == 'subscribe'
&& $this->autoSubscribe
) {
$this->subscribed($payload['from']);
$this->subscribe($payload['from']);
$this->executePlugin('jaxl_post_subscription_request', $payload);
}
else if($payload['type'] == 'subscribed') {
$this->executePlugin('jaxl_post_subscription_accept', $payload);
}
}
return $payloads;
}
}
?>
diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index 5c3cd0b..5bd281c 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,451 +1,429 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
-
+
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
var $streamBlocking = 1;
- /**
- * Nap in seconds between two socket reads
- *
- * @var integer
- */
- var $getSleep = 1;
-
- /**
- * Number of packets to read in one socket read
- *
- * @var integer
- */
- var $getPkts = false;
-
/**
* Size of each packet to be read from the socket
*/
var $getPktSize = false;
- /**
- * Number of empty packet read before aborting further reads
- */
- var $getEmptyLines = false;
-
/**
* Maximum rate at which XMPP stanza's can flow out
*/
var $sendRate = false;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
$this->clocked = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
- $this->getPkts = isset($config['getPkts']) ? $config['getPkts'] : 1600;
- $this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 2048;
- $this->getEmptyLines = isset($config['getEmptyLines']) ? $config['getEmptyLines'] : 15;
+ $this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 4096;
$this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : 0.1;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
$this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
$this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
$this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
$this->executePlugin('jaxl_post_connect', $ret);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = $this->executePlugin('jaxl_get_id', ++$this->lastid);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
* $option = null (read until data is available)
* $option = integer (read for so many seconds)
- * $option = bool (core rests for a second (if true) before reading data)
*/
function getXML($option=2) {
// reload pending buffer
$payload = $this->buffer;
$this->buffer = '';
// prepare streams to select
$read = array($this->stream); $write = array(); $except = array();
$secs = $option; $usecs = 0;
// get num changed streams
if(false === ($changed = @stream_select($read, $write, $except, $secs, $usecs))) {
$this->log("[[XMPPGet]] \nError while reading packet from stream", 5);
@fclose($this->stream);
$this->socket = null;
return false;
}
else if($changed > 0) { $payload .= @fread($this->stream, $this->getPktSize); }
else {}
// update clock
$now = time();
$this->clock += $now-$this->clocked;
$this->clocked = $now;
// route rcvd packet
$payload = trim($payload);
$payload = $this->executePlugin('jaxl_get_xml', $payload);
$this->handler($payload);
// flush obuffer
if($this->obuffer != '') {
$payload = $this->obuffer;
$this->obuffer = '';
$this->_sendXML($payload);
}
}
/**
* Send XMPP XML packet over connected stream
*/
function sendXML($xml, $force=false) {
$xml = $this->executePlugin('jaxl_send_xml', $xml);
-
+
if($this->mode == "cgi") {
$this->executePlugin('jaxl_send_body', $xml);
}
else {
if($this->rateLimit
&& !$force
&& $this->lastSendTime
&& JAXLUtil::getTime() - $this->lastSendTime < $this->sendRate
) { $this->obuffer .= $xml; }
else {
$xml = $this->obuffer.$xml;
$this->obuffer = '';
return $this->_sendXML($xml);
}
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
if($this->stream) {
$this->lastSendTime = JAXLUtil::getTime();
// prepare streams to select
$read = array(); $write = array($this->stream); $except = array();
$secs = null; $usecs = null;
// try sending packet
if(false === ($changed = @stream_select($read, $write, $except, $secs, $usecs))) {
$this->log("[[XMPPSend]] \nError while trying to send packet", 5);
}
else if($changed > 0) {
$ret = @fwrite($this->stream, $xml);
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
}
else {
$this->log("[[XMPPSend]] Failed\n".$xml);
throw new JAXLException("[[XMPPSend]] \nFailed");
}
return $ret;
}
else {
$this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
return false;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
if($payload == '') return '';
$this->log("[[XMPPGet]] \n".$payload, 4);
$buffer = array();
$payload = $this->executePlugin('jaxl_pre_handler', $payload);
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
$this->buffer = $xml;
break;
}
}
if(substr($xml, 0, 7) == '<stream')
$arr = $this->xml->xmlize($xml);
else
$arr = JAXLXml::parse($xml);
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
$jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
unset($buffer);
$this->executePlugin('jaxl_post_handler', $payload);
}
}
?>
|
jaxl/JAXL | c1d90f6d966bbf6f2f76ea7f404b31cac3d19b02 | XMPP base class now make use of socket_select() to poll opened stream efficiently (getting rid of annoying sleep) | diff --git a/CHANGELOG b/CHANGELOG
index 20851a9..7068948 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,309 +1,311 @@
version 2.1.2
-------------
+- XMPP base class now make use of socket_select() to poll opened stream efficiently (getting rid of annoying sleep)
+ Updated JAXLCron method to adjust to new core changes
- Added hook for jaxl_get_bosh_curl_error which is called when bosh end point returns a non-zero errno
Updated Jaxl core session variable names to avoid clash with existing session vars
Updated boshchat.php to make use of jaxl_get_bosh_curl_error to disconnect intelligently
- PHP CMS looking to integrate Jaxl in their core can now force disable auto start of php session by Jaxl core
Simple pass 'boshSession' as false with jaxl constructor config array
- Entire Jaxl core including xmpp/, xep/ and core/ class files now make use of JAXL::addPlugin instead of JAXLPlugin to register per instance callbacks
- JAXLPlugin can now register a callback for a dedicated jaxl instance in a multi-instance jaxl application
Class functionality remains backward compatible.
- JAXLog class now also dump connect instance uid per log line
- XMPP instance iq id now defaults to a random value between 1 and 9
Also added jaxl_get_id event hook for apps to customize iq id for the connected Jaxl instance
Also as compared to default numeric iq id, Jaxl core now uses hex iq id's
- Every jaxl instance per php process id now generate it's own unique id JAXL::$uid
- Jaxl core doesn't go for a session if it's optional as indicated by the xmpp server
- Fixed boshChat postBind issues as reported by issue#26 (http://code.google.com/p/jaxl/issues/detail?id=26)
- Fixed jaxl constructor config read warning and XEP 0114 now make use of JAXL::getConfigByPriority method
- Removed warning while reading user config inside Jaxl constructor
Upgraded Jaxl Parser class which was malfunctioning on CentOS PHP 5.1.6 (cli)
- Added bosh error response handling and appropriate logging inside XMPP over Bosh core files
- Code cleanup inside jaxl logger class.
Fixed getConfigByPriority method which was malfunctioning in specific cases
- JAXLog class now using inbuild php function (error_log)
- Checking in first version of XEP-0016 (Privacy Lists), XEP-0055 (Jabber Search), XEP-0077 (In-Band Registration), XEP-0144 (Roster Item Exchange), XEP-0153 (vCard-Based Avatars), XEP-0237 (Roster Versioning)
- On auth faliure core doesn't throw exception since XMPP over Bosh apps are not held inside a try catch block (a better fix may be possible in future)
- XMPP over BOSH xep wasn't passing back Jaxl instance obj for jaxl_post_disconnect hook, fixed that for clean disconnect
- Jaxl core attempts to create log and pid files if doesn't already exists
Also instead of die() core throws relevant exception message wherever required
XMPP base classes throws relevant exception with message wherever required
- First commit of JAXLException class. JAXL core now uses JAXLException
- Jaxl constructor dies if logPath, pidPath and tmpPath doesn't exists on the system
- Core updates JAXL::resource after successful binding to match resource assigned by the connecting server
- Updated echobot sample example to make use of autoSubscribe core feature
Also registers callback for jaxl_post_subscription_request and jaxl_post_subscription_accept hooks
- Updated echobot and boshchat application to use in memory roster cache maintained by Jaxl core.
App files should register callback on hook jaxl_post_roster_update to get notified everytime local roster cache is updated
- Added provision for local roster cache management inside Jaxl core.
Retrived roster lists are cached in memory (see updated echobot.php sample example).
Also added provision for presence tracking (JAXL::trackPresence).
If enabled Jaxl core keep a track of jid availability and update local roster cache accordingly.
Also added provision for auto-accept subscription (JAXL::autoSubscribe).
- Removed XMPP::isConnected variable which used to tell status of connected socket stream.
This is equivalent to checking XMPP:stream variable for true/false
- Added a (kind of) buggy support for '/xml()' inside parser xpath
- If Jaxl instance has being configured for auto periodic ping (XEP-0199), pings are holded till auth completion.
Also if server responds 'feature-not-implemented' for first ping XEP-0199 automatically deleted periodic ping cron tab
- Corrected handling of error type iq stanza's (removed jaxl_get_iq_error hook)
- Added iq error code xpath inside JAXLXml class
- Completed missing JAXLCron::delete method for removing a previously registered cron tab
- Checking in first version of XEP-0049 (Private XML Storage) (not yet tested)
- Checking in first version of XEP-0191 (Simple Communication Blocking) (not yet tested)
- Added JAXL_PING_INTERVAL configuration option inside jaxl.ini
- XEP-0199 (XMPP Ping) can now automatically ping the connected server periodically for keeping connection alive on long running bots
(see echobot.php sample app for usage)
- Updated JAXLCron::add method to accept a number of arguments while adding bckgrnd jobs
These list of arguments is passed back to the application method
- Updated IQ handling inside XEP-0202 which wasn't returning iq stanza back resulting in no ping/pong
- Updated echobot to show usage of JAXL::discoItems and JAXL::discoInfo inside application code
- Added tagMap xpath for service identity and feature nodes in service discovery resultset
- JAXL core now auto includes XEP-0128 along with XEP-0030 on startup.
Also added two methods JAXL::discoItems and JAXL::discoInfo for service discovery
- Checking in first version of XEP-0128 (Service Discovery Extension)
- Fixed bug where message and presence stanza builder were not using passed id value as attribute
- Removed jaxl_pre_curl event hook which was only used internally by XEP-0124
- Jaxl now shutdown gracefully is encryption is required and openssl PHP module is not loaded in the environment
- For every registered callback on XMPP hooks, callback'd method will receive two params.
A payload and reference of Jaxl instance for whom XMPP event has occured.
Updated sample application code to use passed back Jaxl instance reference instead of global jaxl variable.
- As a library convention XEP's exposing user space configuration parameters via JAXL constructor SHOULD utilize JAXL::getConfigByPriority method
Added JAXL_TMP_PATH option inside jaxl.ini
- Jaxl::tmp is now Jaxl::tmpPath. Also added Jaxl config param to specify custom tmp path location
Jaxl client also self detect the IP of the host it is running upon (to be used by STUN/TURN utilities in Jingle negotitation)
- Removed JAXLUtil::includePath and JAXLUtil::getAppFilePath methods which are now redundant after removing jaxl.ini and jaxl.conf from lib core
- Removed global defines JAXL_BASE_PATH, JAXL_APP_BASE_PATH, JAXL_BOSH_APP_ABS_PATH from inside jaxl.ini (No more required by apps to specify these values)
- Removing env/jaxl.php and env/jaxl.conf (were required if you run your apps using `jaxl` command line utility)
Updated env/jaxl.ini so that projects can now directly include their app setting via jaxl.ini (before including core/jaxl.class.php)
- Added JAXL::bareJid public variable for usage inside applications.
XMPP base class now return bool on socket connect completion (used by PHPUnit test cases)
- Removing build.sh file from library for next release
Users should simply download, extract, include and write their app code without caring about the build script from 2.1.2 release
- As a library convention to include XEP's use JAXL::requires() method, while to include any core/ or xmpp/ base class use jaxl_require() method.
Updated library code and xep's to adhere to this convention.
Jaxl instance now provide a system specific /tmp folder location accessible by JAXL::tmp
- Removed JAXL_NAME and JAXL_VERSION constants.
Instead const variables are now defined per instance accessible by getName() and getVersion() methods.
Updated XEP-0030,0092,0115 to use the same
- Moved indivisual XEP's working parameter (0114,0124) from JAXL core class to XEP classes itself.
XEP's make use of JAXL::config array for parsing user options.
- Added JAXL_COMPONENT_PASS option inside jaxl.ini. Updated build.sh with new /app file paths.
Updated XEP-0114,0124,0206 to use array style configs as defined inside JAXL class
- Removed dependency upon jaxl.ini from all sample applications.
First checkin of sample sendMessage.php app.
- Config parameters for XEP's like 0114 and 0206 are now saved as an array inside JAXL class (later on they will be moved inside respective XEP's).
Added constructor config option to pre-choose an auth mechanism to be performed
if an auth mech is pre-chosen app files SHOULD not register callback for jaxl_get_auth_mech hook.
Bosh cookie settings can now be passed along with Jaxl constructor.
Added support for publishing vcard-temp:x:update node along with presence stanzas.
Jaxl instance can run in 3 modes a.k.a. stream,component and bosh mode
applications should use JAXL::startCore('mode') to configure instance for a specific mode.
- Removed redundant NS variable from inside XEP-0124
- Moved JAXLHTTPd setting defines inside the class (if gone missing CPU usage peaks to 100%)
- Added jaxl_httpd_pre_shutdown, jaxl_httpd_get_http_request, jaxl_httpd_get_sock_request event hooks inside JAXLHTTPd class
- Added JAXLS5B path (SOCKS5 implementation) inside jaxl_require method
- Removed all occurance of JAXL::$action variable from /core and /xep class files
- Updated boshChat and boshMUChat sample application which no longer user JAXL::$action variable inside application code
- Updated preFetchBOSH and preFetchXMPP sample example.
Application code don't need any JAXL::$action variable now
Neither application code need to define JAXL_BASE_PATH (optional from now on)
- JAXL core and XEP-0206 have no relation and dependency upon JAXL::$action variable now.
- Deprecated jaxl_get_body hook which was only for XEP-0124 working.
Also cleaned up XEP-0124 code by removing processBody method which is now handled inside preHandler itself.
- Defining JAXL_BASE_PATH inside application code made optional.
Developers can directly include /path/to/jaxl/core/jaxl.class.php and start writing applications.
Also added a JAXL::startCore() method (see usage in /app/preFetchXMPP.php).
Jaxl magic method for calling XEP methods now logs a warning inside jaxl.log if XEP doesn't exists in the environment
- Added tag map for XMPP message thread and subject child elements
- Fixed typo where in case of streamError proper description namespace was not parsed/displayed
- Disabled BOSH session close if application is running in boshOut=false mode
Suggested by MOVIM dev team who were experiencing loss of session data on end of script
- JAXL::log method 2nd parameter now defaults to logLevel=1 (passing 2nd param is now optional)
- Fixed XPath for iq stanza error condition and error NS extraction inside jaxl.parser.class
- First checkin of XEP-0184 Message Receipts
- Added support for usage of name() xpath function inside tag maps of JAXLXml class.
Also added some documentation for methods available inside JAXLXml class
- Fixed JAXLPlugin::remove method to properly remove and manage callback registry.
Also added some documentation for JAXLPlugin class methods
- Added JAXL contructor config option to disable BOSH module auto-output behaviour.
This is utilized inside app/preFetchBOSH.php sample example
- First checkin of sample application code pre-fetching XMPP/Jabber data for web page population using BOSH XEP
- Added a sample application file which can be used to pre-fetch XMPP/Jabber data for a webpage without using BOSH XEP or Ajax requests
As per the discussion on google groups (http://bit.ly/aKavZB) with MOVIM team
- JAXL library is now $jaxl independent, you can use anything like $var = new JAXL(); instance your applications now
JAXLUtil::encryptPassword now accepts username/password during SASL auth.
Previously it used to auto detect the same from JAXL instance, now core has to manually pass these param
- Added JAXL::startHTTPd method with appropriate docblock on how to convert Jaxl instance into a Jaxl socket (web) server.
Comments also explains how to still maintaining XMPP communication in the background
- Updated JAXLHTTPd class to use new constants inside jaxl.ini
- Added jaxl_get_stream_error event handler.
Registered callback methods also receive array form of received XMPP XML stanza
- Connecting Jaxl instance now fallback to default value 'localhost' for host,domain,boshHost,boshPort,boshSuffix
If these values are not configured either using jaxl.ini constants or constructor
- Provided a sendIQ method per JAXL instance.
Recommended that applications and XEP's should directly use this method for sending <iq/> type stanza
DONOT use XMPPSend methods inside your application code from here on
- Added configuration options for JAXL HTTPd server and JAXL Bosh Component Manager inside jaxl.ini
- Fixed type in XEP-0202 (Entity Time). XEP was not sending <iq/> id in response to get request
- Jaxl library is now phpdocs ready. Added extended documentation for JAXL core class, rest to be added
- All core classes inside core/, xmpp/ and xep/ folder now make use of jaxl->log method
JAXL Core constructor are now well prepared so that inclusion of jaxl.ini is now optional
Application code too should use jaxl->log instead of JAXLog::log method for logging purpose
- Reshuffled core instance paramaters between JAXL and XMPP class
Also Jaxl core now logs at level 1 instead of 0 (i.e. all logs goes inside jaxl.log and not on console)
- JAXL class now make use of endStream method inside XMPP base class while disconnecting.
Also XMPPSend::endStream now forces xmpp stanza delivery (escaping JAXL internal buffer)
http://code.google.com/p/jaxl/issues/detail?id=23
- Added endStream method inside XMPP base class and startSession,startBind methods inside XMPPSend class
XMPP::sendXML now accepts a $force parameter for escaping XMPP stanza's from JAXL internal buffer
- Updated the way Jaxl core calls XEP 0115 method (entity caps) to match documentation
XEP method's should accept jaxl instance as first paramater
- First checkin of PEP (Personal Eventing), User Location, User Mood, User Activity and User Tune XEP's
- Completed methods discoFeatures, discoNodes, discoNodeInfo, discoNodeMeta and discoNodeItems in PubSub XEP
- Hardcoded client category, type, lang and name. TODO: Make them configurable in future
- Cleaned up XEP 0030 (Service Discovery) and XEP 0115 (Entity Capabilities)
- Updated XMPP base class to use performance configuration parameters (now customizable with JAXL constructor)
- jaxl.conf will be removed from jaxl core in future, 1st step towards this goal
- Moved bulk of core configs from jaxl.conf
- Added more configuration options relating to client performance e.g. getPkts, getPktSize etc
- Fixed client mode by detecting sapi type instead of $_REQUEST['jaxl'] variable
- Now every implemented XEP should have an 'init' method which will accept only one parameter (jaxl instance itself)
- Jaxl core now converts transmitted stanza's into xmlentities (http://code.google.com/p/jaxl/issues/detail?id=22)
- Created a top level 'patch' folder which contains various patches sent by developers using 'git diff > patch' utility
- Fixed typo in namespace inside 0030 (thanks to Thomas Baquet for the patch)
- First checkin of PubSub XEP (untested)
- Indented build.sh and moved define's from top of JAXLHTTPd class to jaxl.ini
- Added JAXLHTTPd inside Jaxl core (a simple socket select server)
- Fixed sync of background iq and other stanza requests with browser ajax calls
- Updated left out methods in XMPP over BOSH xep to accept jaxl instance as first method
- All XEP methods available in application landspace, now accepts jaxl instance as first parameter. Updated core jaxl class magic method to handle the same.
If you are calling XEP methods as specified in the documentation, this change will not hurt your running applications
- Updated echobot sample application to utilize XEP 0054 (VCard Temp) and 0202 (Entity Time)
- First checkin of missing vcard-temp xep
- Added xmlentities JAXLUtil method
- Jaxl Parser now default parses xXmlns node for message stanzas
- Added PCRE_DOTALL and PCRE_MULTILINE pattern modifier for bosh unwrapBody method
- Added utility methods like urldecode, urlencode, htmlEntities, stripHTML and splitJid inside jaxl.js
- Updated sample application jaxl.ini to reflect changes in env/jaxl.ini
version 2.1.1
-------------
- Updated XMPPSend 'presence', 'message' and 'iq' methods to accept $jaxl instance as first parameter
if you are not calling these methods directly from your application code as mentioned in documentation
this change should not hurt you
- Added more comments to env/jaxl.ini and also added JAXL_LOG_ROTATE ini file option
- JAXL instance logs can be rotated every x seconds (logRotate config parameter) now
- Removed config param dumpTime, instead use dumpStat to specify stats dump period
- Base XMPP class now auto-flush output buffers filled because of library level rate limiter
- Added more options for JAXL constructor e.g.
boshHost, boshPort, boshSuffix, pidPath, logPath, logLevel, dumpStat, dumpTime
These param overwrites value specified inside jaxl.ini file
Also JAXL core will now periodically dump instance statistics
- Added an option in JAXL constructor to disable inbuild core rate limiter
- Added support when applications need to connect with external bosh endpoints
Bosh application code requires update for ->JAXL0206('startStream') method
- XMPPGet::handler replaces ->handler inside XEP-0124
- JAXLCron job now also passes connected instance to callback cron methods
- Updated base XMPP class now maintains a clock, updated sendXML method to respect library level rate limiting
- Base JAXL class now includes JAXLCron class for periodically dumping connected bot memory/usage stats
- First version of JAXLCron class for adding periodic jobs in the background
- XMPP payload handler moves from XMPPGet to base XMPP class, packets are then routed to XMPPGet class for further processing
- Updated xep-0124 to use instance bosh parameters instead of values defined inside jaxl.ini
- Provision to specify custom JAXL_BOSH_HOST inside jaxl.ini
- Instead of global logLevel and logPath, logger class now respects indivisual instance log settings
Helpful in multiple instance applications
- Updated base JAXL class to accept various other configuration parameters inside constructor
These param overwrites values defined inside jaxl.ini
- XMPPSend::xml method moves inside XMPP::sendXML (call using ->sendXML from within application code), as a part of library core cleanup
- Updated jaxl class to return back payload from called xep methods
- XMPP base method getXML can be instructed not to take a nap between stream reads
- Added jaxl_get_xml hook for taking control over incoming xml payload from xmpp stream
- Added support for disabling sig term registration, required by applications who already handle this in their core code
- Added capability of sending multiple message/presence stanza in one go inside jaxl base class
- Fixed typo in MUC Direct Invitation xep invite method
- getHandler should have accepted core instance by reference, fixed now. BOSH MUC Chat sample application header is now more appropriate
version 2.1.0
-------------
- First checkin of bosh MUC sample application
- Updated build file now packages bosh MUC chat sample application along with core classes
- Updated JAXLog class to accept instance inside log() method, application code should use ->log() to call JAXLog::log() method now
- Updated JAXLPlugin class to pass instance along with every XMPP event hook
- Updated jaxl_require method to call including XEP's init() method every time they are included using jaxl_require method
- Update jaxl.ini with some documentation/comments about JAXL_BOSH_COOKIE_DOMAIN parameter
- Updated echobot sample application code to pass instance while calling jaxl_require method
- Update XMPP SASL Auth class to accept instance while calculating SASL response.
Also passinginstance when jaxl_get_facebook_key hook is called
- Updated XMPP base class to accept component host name inside constructor.
Sending currentinstance with every XMPPSend, XMPPGet and JAXLog method calls
- Every XMPPGet method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Every XMPPSend method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Updated component bot sample application to show how to pass component host inside JAXL constructor.
Also updated jaxl_require call to accept current working instance
- Updated boshchat sample application to follow new rules of jaxl_require, also cleaned up the sample app code a bit
- Updated jaxl.ini of packaged sample applications to match /env/jaxl.ini
- Updated implemented XEP's init method to accept instance during initialization step
Send working instance with every XMPPSend method call
Almost every XEP's available method now accepts an additional instance so that XEP's can work independently for every instance inside a multiple jaxl instance application code
- Added magic method __call inside JAXL class
All application codes should now call a methods inside implemented XEP's like ->JAXLxxxx('method', , , ...)
Also added ->log method to be used by application codes
JAXLog::log() should not be called directly from application code
Updated XMPPSend methods to accept instance
Added ->requires() method that does a similar job as jaxl_require() which now also expects instance as one of the passed parameter.
version 2.0.4
-------------
- Updated XMPP base class and XMPP Get class to utilize new XMPPAuth class
- Updated jaxl_require method with new XMPPAuth class path
- Extracted XMPP SASL auth mechanism out of XMPP Get class, code cleanup
- unwrapBody method of XEP 0124 is now public
- Added #News block on top of README
- No more capital true, false, null inside Jaxl core to pass PHP_CodeSniffer tests
- :retab Jaxl library core to pass PHP_CodeSniffer tests
- Added Jabber Component Protocol example application bot
- Updated README with documentation link for Jabber component protocol
- Updated Entity Caps method to use list of passed feature list for verification code generation
- Updated MUC available methods doc link inside README
- Added experimental support for SCRAM-SHA-1, CRAM-MD5 and LOGIN auth mechanisms
version 2.0.3
-------------
- Updated Jaxl XML parsing class to handle multiple level nested child cases
- Updated README and bosh chat application with documentation link
- Fixed bosh application to run on localhost
- Added doc links inside echobot sample app
- Bosh sample application also use entity time XEP-0202 now
- Fix for sapi detection inside jaxl util
- jaxl.js updated to handle multiple ajax poll response payloads
- Bosh session manager now dumps ajax poll response on post handler callback
- Removed hardcoded ajax poll url inside boshchat application
- Updated component protocol XEP pre handshake event handling
version 2.0.2
-------------
- Packaged XEP 0202 (Entity Time)
- First checkin of Bosh related XEP 0124 and 0206
- Sample Bosh Chat example application
- Updated jaxl.class.php to save Bosh request action parameter
- jaxl.ini updated with Bosh related cookie options, default loglevel now set to 4
- jaxl.js checkin which should be used with bosh applications
- Updated base xmpp classes to provide integrated bosh support
- Outgoing presence and message stanza's too can include @id attribute now
version 2.0.1
-------------
- Typo fix in JAXLXml::$tagMap for errorCode
- Fix for handling overflooded roster list
- Packaged XEP 0115 (Entity capability) and XEP 0199 (XMPP Ping)
- Updated sample echobot to use XEP 0115 and XEP 0199
- Support for X-FACEBOOK-PLATFORM authentication
version 2.0.0
--------------
First checkin of:
- Restructed core library with event mechanism
- Packaged XEP 0004, 0030, 0045, 0050, 0085, 0092, 0114, 0133, 0249
- Sample echobot application
diff --git a/core/jaxl.cron.php b/core/jaxl.cron.php
index 1386227..0ea983a 100644
--- a/core/jaxl.cron.php
+++ b/core/jaxl.cron.php
@@ -1,93 +1,98 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl Cron Job
*
* Add periodic cron in your xmpp applications
*/
class JAXLCron {
-
+
+ private static $last = 0;
private static $cron = array();
public static function init($jaxl) {
$jaxl->addPlugin('jaxl_get_xml', array('JAXLCron', 'ticker'));
}
public static function ticker($payload, $jaxl) {
+ if(self::$last == $jaxl->clock) return $payload;
+
foreach(self::$cron as $interval => $jobs) {
foreach($jobs as $key => $job) {
if($jaxl->clock % $interval == 0 // if cron interval matches
|| $jaxl->clocked - $job['lastCall'] > $interval // if cron interval has already passed
) {
self::$cron[$interval][$key]['lastCall'] = $jaxl->clocked;
$arg = $job['arg'];
array_unshift($arg, $jaxl);
call_user_func_array($job['callback'], $arg);
}
}
}
+
+ self::$last = $jaxl->clock;
return $payload;
}
public static function add(/* $callback, $interval, $param1, $param2, .. */) {
$arg = func_get_args();
$callback = array_shift($arg);
$interval = array_shift($arg);
self::$cron[$interval][self::generateCbSignature($callback)] = array('callback'=>$callback, 'arg'=>$arg, 'lastCall'=>time());
}
public static function delete($callback, $interval) {
$sig = self::generateCbSignature($callback);
if(isset(self::$cron[$interval][$sig]))
unset(self::$cron[$interval][$sig]);
}
protected static function generateCbSignature($callback) {
return is_array($callback) ? md5(json_encode($callback)) : md5($callback);
}
}
?>
diff --git a/xmpp/xmpp.class.php b/xmpp/xmpp.class.php
index e2fa465..15970c1 100644
--- a/xmpp/xmpp.class.php
+++ b/xmpp/xmpp.class.php
@@ -1,444 +1,451 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'XMPPGet',
'XMPPSend'
));
/**
* Base XMPP class
*/
class XMPP {
/**
* Auth status of Jaxl instance
*
* @var bool
*/
var $auth = false;
/**
* Connected XMPP stream session requirement status
*
* @var bool
*/
var $sessionRequired = false;
/**
* SASL second auth challenge status
*
* @var bool
*/
var $secondChallenge = false;
/**
* Id of connected Jaxl instance
*
* @var integer
*/
var $lastid = 0;
/**
* Connected socket stream handler
*
* @var bool|object
*/
var $stream = false;
/**
* Connected socket stream id
*
* @var bool|integer
*/
var $streamId = false;
/**
* Socket stream connected host
*
* @var bool|string
*/
var $streamHost = false;
/**
* Socket stream version
*
* @var bool|integer
*/
var $streamVersion = false;
/**
* Last error number for connected socket stream
*
* @var bool|integer
*/
var $streamENum = false;
/**
* Last error string for connected socket stream
*
* @var bool|string
*/
var $streamEStr = false;
/**
* Timeout value for connecting socket stream
*
* @var bool|integer
*/
var $streamTimeout = false;
/**
* Blocking or Non-blocking socket stream
*
* @var bool
*/
- var $streamBlocking = 0;
+ var $streamBlocking = 1;
/**
* Nap in seconds between two socket reads
*
* @var integer
*/
var $getSleep = 1;
/**
* Number of packets to read in one socket read
*
* @var integer
*/
var $getPkts = false;
/**
* Size of each packet to be read from the socket
*/
var $getPktSize = false;
/**
* Number of empty packet read before aborting further reads
*/
var $getEmptyLines = false;
/**
* Maximum rate at which XMPP stanza's can flow out
*/
var $sendRate = false;
/**
* Input XMPP stream buffer
*/
var $buffer = '';
/**
* Output XMPP stream buffer
*/
var $obuffer = '';
/**
* Current value of instance clock
*/
var $clock = false;
/**
* When was instance clock last sync'd?
*/
var $clocked = false;
/**
* Enable/Disable rate limiting
*/
var $rateLimit = true;
/**
* Timestamp of last outbound XMPP packet
*/
var $lastSendTime = false;
/**
* XMPP constructor
*/
function __construct($config) {
$this->clock = 0;
$this->clocked = time();
/* Parse configuration parameter */
$this->lastid = rand(1, 9);
$this->streamTimeout = isset($config['streamTimeout']) ? $config['streamTimeout'] : 20;
$this->rateLimit = isset($config['rateLimit']) ? $config['rateLimit'] : true;
$this->getPkts = isset($config['getPkts']) ? $config['getPkts'] : 1600;
$this->getPktSize = isset($config['getPktSize']) ? $config['getPktSize'] : 2048;
$this->getEmptyLines = isset($config['getEmptyLines']) ? $config['getEmptyLines'] : 15;
$this->sendRate = isset($config['sendRate']) ? $config['sendRate'] : 0.1;
}
/**
* Open socket stream to jabber server host:port for connecting Jaxl instance
*/
function connect() {
if(!$this->stream) {
- if($this->stream = @fsockopen($this->host, $this->port, $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
- $this->log("[[XMPP]] Socket opened to the jabber host ".$this->host.":".$this->port." ...");
+ if($this->stream = @stream_socket_client("tcp://{$this->host}:{$this->port}", $this->streamENum, $this->streamEStr, $this->streamTimeout)) {
+ $this->log("[[XMPP]] \nSocket opened to the jabber host ".$this->host.":".$this->port." ...");
stream_set_blocking($this->stream, $this->streamBlocking);
stream_set_timeout($this->stream, $this->streamTimeout);
}
else {
- $this->log("[[XMPP]] Unable to open socket to the jabber host ".$this->host.":".$this->port." ...");
+ $this->log("[[XMPP]] \nUnable to open socket to the jabber host ".$this->host.":".$this->port." ...");
throw new JAXLException("[[XMPP]] Unable to open socket to the jabber host");
}
}
else {
- $this->log("[[XMPP]] Socket already opened to the jabber host ".$this->host.":".$this->port." ...");
+ $this->log("[[XMPP]] \nSocket already opened to the jabber host ".$this->host.":".$this->port." ...");
}
$ret = $this->stream ? true : false;
JAXLPlugin::execute('jaxl_post_connect', $ret, $this);
return $ret;
}
/**
* Send XMPP start stream
*/
function startStream() {
return XMPPSend::startStream($this);
}
/**
* Send XMPP end stream
*/
function endStream() {
return XMPPSend::endStream($this);
}
/**
* Send session start XMPP stanza
*/
function startSession() {
return XMPPSend::startSession($this, array('XMPPGet', 'postSession'));
}
/**
* Bind connected Jaxl instance to a resource
*/
function startBind() {
return XMPPSend::startBind($this, array('XMPPGet', 'postBind'));
}
/**
* Return back id for use with XMPP stanza's
*
* @return integer $id
*/
function getId() {
$id = JAXLPlugin::execute('jaxl_get_id', ++$this->lastid, $this);
if($id === $this->lastid) return dechex($this->uid + $this->lastid);
else return $id;
}
/**
* Read connected XMPP stream for new data
+ * $option = null (read until data is available)
+ * $option = integer (read for so many seconds)
+ * $option = bool (core rests for a second (if true) before reading data)
*/
- function getXML($nap=TRUE) {
- // sleep between two reads
- if($nap) sleep($this->getSleep);
-
- // initialize empty lines read
- $emptyLine = 0;
-
- // read previous buffer
+ function getXML($option=2) {
+ // reload pending buffer
$payload = $this->buffer;
$this->buffer = '';
-
- // read socket data
- for($i=0; $i<$this->getPkts; $i++) {
- if($this->stream) {
- $line = fread($this->stream, $this->getPktSize);
- if(strlen($line) == 0) {
- $emptyLine++;
- if($emptyLine > $this->getEmptyLines)
- break;
- }
- else {
- $payload .= $line;
- }
- }
+
+ // prepare streams to select
+ $read = array($this->stream); $write = array(); $except = array();
+ $secs = $option; $usecs = 0;
+
+ // get num changed streams
+ if(false === ($changed = @stream_select($read, $write, $except, $secs, $usecs))) {
+ $this->log("[[XMPPGet]] \nError while reading packet from stream", 5);
+ @fclose($this->stream);
+ $this->socket = null;
+ return false;
}
-
+ else if($changed > 0) { $payload .= @fread($this->stream, $this->getPktSize); }
+ else {}
+
// update clock
$now = time();
$this->clock += $now-$this->clocked;
$this->clocked = $now;
- // trim read data
+ // route rcvd packet
$payload = trim($payload);
$payload = JAXLPlugin::execute('jaxl_get_xml', $payload, $this);
- if($payload != '') $this->handler($payload);
+ $this->handler($payload);
// flush obuffer
if($this->obuffer != '') {
$payload = $this->obuffer;
$this->obuffer = '';
$this->_sendXML($payload);
}
}
/**
* Send XMPP XML packet over connected stream
*/
function sendXML($xml, $force=false) {
$xml = JAXLPlugin::execute('jaxl_send_xml', $xml, $this);
if($this->mode == "cgi") {
JAXLPlugin::execute('jaxl_send_body', $xml, $this);
}
else {
if($this->rateLimit
&& !$force
&& $this->lastSendTime
&& JAXLUtil::getTime() - $this->lastSendTime < $this->sendRate
) { $this->obuffer .= $xml; }
else {
$xml = $this->obuffer.$xml;
$this->obuffer = '';
return $this->_sendXML($xml);
}
}
}
/**
* Send XMPP XML packet over connected stream
*/
protected function _sendXML($xml) {
if($this->stream) {
$this->lastSendTime = JAXLUtil::getTime();
- if(($ret = fwrite($this->stream, $xml)) !== false) {
+
+ // prepare streams to select
+ $read = array(); $write = array($this->stream); $except = array();
+ $secs = null; $usecs = null;
+
+ // try sending packet
+ if(false === ($changed = @stream_select($read, $write, $except, $secs, $usecs))) {
+ $this->log("[[XMPPSend]] \nError while trying to send packet", 5);
+ }
+ else if($changed > 0) {
+ $ret = @fwrite($this->stream, $xml);
$this->log("[[XMPPSend]] $ret\n".$xml, 4);
}
else {
$this->log("[[XMPPSend]] Failed\n".$xml);
- throw new JAXLException("[[XMPPSend]] Failed");
+ throw new JAXLException("[[XMPPSend]] \nFailed");
}
return $ret;
}
else {
- $this->log("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
+ $this->log("[[XMPPSend]] \nJaxl stream not connected to jabber host, unable to send xmpp payload...");
throw new JAXLException("[[XMPPSend]] Jaxl stream not connected to jabber host, unable to send xmpp payload...");
return false;
}
}
/**
* Routes incoming XMPP data to appropriate handlers
*/
function handler($payload) {
+ if($payload == '') return '';
$this->log("[[XMPPGet]] \n".$payload, 4);
$buffer = array();
$payload = JAXLPlugin::execute('jaxl_pre_handler', $payload, $this);
$xmls = JAXLUtil::splitXML($payload);
$pktCnt = count($xmls);
foreach($xmls as $pktNo => $xml) {
if($pktNo == $pktCnt-1) {
if(substr($xml, -1, 1) != '>') {
$this->buffer = $xml;
break;
}
}
if(substr($xml, 0, 7) == '<stream')
$arr = $this->xml->xmlize($xml);
else
$arr = JAXLXml::parse($xml);
switch(true) {
case isset($arr['stream:stream']):
XMPPGet::streamStream($arr['stream:stream'], $this);
break;
case isset($arr['stream:features']):
XMPPGet::streamFeatures($arr['stream:features'], $this);
break;
case isset($arr['stream:error']):
XMPPGet::streamError($arr['stream:error'], $this);
break;
case isset($arr['failure']);
XMPPGet::failure($arr['failure'], $this);
break;
case isset($arr['proceed']):
XMPPGet::proceed($arr['proceed'], $this);
break;
case isset($arr['challenge']):
XMPPGet::challenge($arr['challenge'], $this);
break;
case isset($arr['success']):
XMPPGet::success($arr['success'], $this);
break;
case isset($arr['presence']):
$buffer['presence'][] = $arr['presence'];
break;
case isset($arr['message']):
$buffer['message'][] = $arr['message'];
break;
case isset($arr['iq']):
XMPPGet::iq($arr['iq'], $this);
break;
default:
- $jaxl->log("[[XMPPGet]] Unrecognized payload received from jabber server...");
+ $jaxl->log("[[XMPPGet]] \nUnrecognized payload received from jabber server...");
throw new JAXLException("[[XMPPGet]] Unrecognized payload received from jabber server...");
break;
}
}
if(isset($buffer['presence'])) XMPPGet::presence($buffer['presence'], $this);
if(isset($buffer['message'])) XMPPGet::message($buffer['message'], $this);
unset($buffer);
JAXLPlugin::execute('jaxl_post_handler', $payload, $this);
}
}
?>
diff --git a/xmpp/xmpp.get.php b/xmpp/xmpp.get.php
index 608d25b..cb8fc48 100644
--- a/xmpp/xmpp.get.php
+++ b/xmpp/xmpp.get.php
@@ -1,219 +1,217 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'JAXLXml',
'XMPPAuth',
'XMPPSend'
));
/**
* XMPP Get Class
* Provide methods for receiving all kind of xmpp streams and stanza's
*/
class XMPPGet {
public static function streamStream($arr, $jaxl) {
if($arr['@']["xmlns:stream"] != "http://etherx.jabber.org/streams") {
print "Unrecognized XMPP Stream...\n";
}
else if($arr['@']['xmlns'] == "jabber:component:accept") {
JAXLPlugin::execute('jaxl_post_start', $arr['@']['id'], $jaxl);
}
else if($arr['@']['xmlns'] == "jabber:client") {
$jaxl->streamId = $arr['@']['id'];
$jaxl->streamHost = $arr['@']['from'];
$jaxl->streamVersion = $arr['@']['version'];
}
}
public static function streamFeatures($arr, $jaxl) {
if(isset($arr["#"]["starttls"]) && ($arr["#"]["starttls"][0]["@"]["xmlns"] == "urn:ietf:params:xml:ns:xmpp-tls")) {
if($jaxl->openSSL) {
XMPPSend::startTLS($jaxl);
}
else {
$jaxl->log("[[XMPPGet]] OpenSSL extension required to proceed with TLS encryption");
throw new JAXLException("[[XMPPGet]] OpenSSL extension required to proceed with TLS encryption");
$jaxl->shutdown();
}
}
else if(isset($arr["#"]["mechanisms"]) && ($arr["#"]["mechanisms"][0]["@"]["xmlns"] == "urn:ietf:params:xml:ns:xmpp-sasl")) {
$mechanism = array();
foreach ($arr["#"]["mechanisms"][0]["#"]["mechanism"] as $row)
$mechanism[] = $row["#"];
JAXLPlugin::execute('jaxl_get_auth_mech', $mechanism, $jaxl);
}
else if(isset($arr["#"]["bind"]) && ($arr["#"]["bind"][0]["@"]["xmlns"] == "urn:ietf:params:xml:ns:xmpp-bind")) {
if(isset($arr["#"]["session"]))
if(!isset($arr["#"]["session"][0]["#"]["optional"]))
$jaxl->sessionRequired = true;
$jaxl->startBind();
}
}
public static function streamError($arr, $jaxl) {
$desc = key($arr['#']);
$xmlns = $arr['#'][$desc]['0']['@']['xmlns'];
JAXLPlugin::execute('jaxl_get_stream_error', $arr, $jaxl);
$jaxl->log("[[XMPPGet]] Stream error with description ".$desc." and xmlns ".$xmlns);
throw new JAXLException("[[XMPPGet]] Stream error with description ".$desc." and xmlns ".$xmlns);
return true;
}
public static function failure($arr, $jaxl) {
$xmlns = $arr['xmlns'];
switch($xmlns) {
case 'urn:ietf:params:xml:ns:xmpp-tls':
$jaxl->log("[[XMPPGet]] Unable to start TLS negotiation, see logs for detail...");
if($jaxl->mode == "cli") throw new JAXLException("[[XMPPGet]] Unable to start TLS negotiation, see logs for detail...");
JAXLPlugin::execute('jaxl_post_auth_failure', false, $jaxl);
$jaxl->shutdown('tlsFailure');
break;
case 'urn:ietf:params:xml:ns:xmpp-sasl':
$jaxl->log("[[XMPPGet]] Unable to complete SASL Auth, see logs for detail...");
if($jaxl->mode == "cli") throw new JAXLException("[[XMPPGet]] Unable to complete SASL Auth, see logs for detail...");
JAXLPlugin::execute('jaxl_post_auth_failure', false, $jaxl);
$jaxl->shutdown('saslFailure');
break;
default:
$jaxl->log("[[XMPPGet]] Uncatched failure xmlns received...");
if($jaxl->mode == "cli") throw new JAXLException("[[XMPPGet]] Uncatched failure xmlns received...");
break;
}
}
public static function proceed($arr, $jaxl) {
if($arr['xmlns'] == "urn:ietf:params:xml:ns:xmpp-tls") {
- stream_set_blocking($jaxl->stream, 1);
if(!@stream_socket_enable_crypto($jaxl->stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT))
stream_socket_enable_crypto($jaxl->stream, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
- stream_set_blocking($jaxl->stream, 0);
XMPPSend::startStream($jaxl);
}
}
public static function challenge($arr, $jaxl) {
if($arr['xmlns'] == "urn:ietf:params:xml:ns:xmpp-sasl") {
if($jaxl->secondChallenge) $xml = '<response xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>';
else $xml = XMPPAuth::getResponse($jaxl->authType, $arr['challenge'], $jaxl);
$jaxl->sendXML($xml);
}
}
public static function success($arr, $jaxl) {
if($arr['xmlns'] == "urn:ietf:params:xml:ns:xmpp-sasl") {
if($jaxl->mode == "cgi") JAXL0206::restartStream($jaxl);
else XMPPSend::startStream($jaxl);
}
}
public static function presence($arrs, $jaxl) {
$payload = array();
foreach($arrs as $arr) $payload[] = $arr;
JAXLPlugin::execute('jaxl_get_presence', $payload, $jaxl);
unset($payload);
return $arrs;
}
public static function message($arrs, $jaxl) {
$payload = array();
foreach($arrs as $arr) $payload[] = $arr;
JAXLPlugin::execute('jaxl_get_message', $payload, $jaxl);
unset($payload);
return $arrs;
}
public static function postBind($arr, $jaxl) {
if($arr["type"] == "result") {
$jaxl->jid = $arr["bindJid"];
list($user, $domain, $resource) = JAXLUtil::splitJid($jaxl->jid);
$jaxl->resource = $resource;
JAXLPlugin::execute('jaxl_post_bind', false, $jaxl);
if($jaxl->sessionRequired) {
$jaxl->startSession();
}
else {
$jaxl->auth = true;
$jaxl->log("[[XMPPGet]] Auth completed...");
JAXLPlugin::execute('jaxl_post_auth', false, $jaxl);
}
}
}
public static function postSession($arr, $jaxl) {
if($arr["type"] == "result") {
$jaxl->auth = true;
$jaxl->log("[[XMPPGet]] Auth completed...");
JAXLPlugin::execute('jaxl_post_auth', false, $jaxl);
}
}
public static function iq($arr, $jaxl) {
switch($arr['type']) {
case 'get':
JAXLPlugin::execute('jaxl_get_iq_get', $arr, $jaxl);
break;
case 'set':
JAXLPlugin::execute('jaxl_get_iq_set', $arr, $jaxl);
break;
case 'result':
JAXLPlugin::execute('jaxl_get_iq_'.$arr['id'], $arr, $jaxl);
break;
case 'error':
JAXLPlugin::execute('jaxl_get_iq_'.$arr['id'], $arr, $jaxl);
break;
}
return $arr;
}
}
?>
|
jaxl/JAXL | ff6eab4761ddac07bb864ca2e0fac6b577d1f137 | Fixed typo inside echobot.php app | diff --git a/app/echobot.php b/app/echobot.php
index 2c8f941..e03e938 100644
--- a/app/echobot.php
+++ b/app/echobot.php
@@ -1,107 +1,108 @@
<?php
/*
* Sample command line echobot using Jaxl library
* Usage: php echobot.php
* Read More: http://bit.ly/bz9KXb
*/
// Initialize Jaxl Library
require_once '../core/jaxl.class.php';
// Values passed to the constructor can also be defined as constants
// List of constants can be found inside "../../env/jaxl.ini"
// Note: Values passed to the constructor always overwrite defined constants
$jaxl = new JAXL(array(
'user'=>'',
'pass'=>'',
- 'domain'=>'talk.google.com',
+ 'host'=>'talk.google.com',
+ 'domain'=>'gmail.com',
'authType'=>'PLAIN',
'autoSubscribe'=>true,
'pingInterval'=>60,
'logLevel'=>5
));
// Include required XEP's
$jaxl->requires(array(
'JAXL0115', // Entity Capabilities
'JAXL0092', // Software Version
'JAXL0199', // XMPP Ping
'JAXL0203', // Delayed Delivery
'JAXL0202' // Entity Time
));
// Sample Echobot class
class echobot {
function postAuth($payload, $jaxl) {
$jaxl->discoItems($jaxl->domain, array($this, 'handleDiscoItems'));
$jaxl->getRosterList();
}
function handleDiscoItems($payload, $jaxl) {
if(!is_array($payload['queryItemJid']))
return $payload;
$items = array_unique($payload['queryItemJid']);
foreach($items as $item)
$jaxl->discoInfo($item, array($this, 'handleDiscoInfo'));
}
function handleDiscoInfo($payload, $jaxl) {
// print_r($payload);
}
function postRosterUpdate($payload, $jaxl) {
// Use $jaxl->roster which holds retrived roster list
// print_r($jaxl->roster);
// set echobot status
$jaxl->setStatus(false, false, false, true);
}
function getMessage($payloads, $jaxl) {
foreach($payloads as $payload) {
if($payload['offline'] != JAXL0203::$ns) {
if(strlen($payload['body']) > 0) {
// echo back the incoming message
$jaxl->sendMessage($payload['from'], $payload['body']);
}
}
}
}
function getPresence($payloads, $jaxl) {
foreach($payloads as $payload) {
// print_r($payload);
}
}
function postSubscriptionRequest($payload, $jaxl) {
$jaxl->log("Subscription request sent to ".$payload['from']);
}
function postSubscriptionAccept($payload, $jaxl) {
$jaxl->log("Subscription accepted by ".$payload['from']);
}
function getId($payload, $jaxl) {
return $payload;
}
}
// Add callbacks on various event handlers
$echobot = new echobot();
$jaxl->addPlugin('jaxl_post_auth', array($echobot, 'postAuth'));
$jaxl->addPlugin('jaxl_get_message', array($echobot, 'getMessage'));
$jaxl->addPlugin('jaxl_get_presence', array($echobot, 'getPresence'));
$jaxl->addPlugin('jaxl_post_roster_update', array($echobot, 'postRosterUpdate'));
$jaxl->addPlugin('jaxl_post_subscription_request', array($echobot, 'postSubscriptionRequest'));
$jaxl->addPlugin('jaxl_post_subscription_accept', array($echobot, 'postSubscriptionAccept'));
$jaxl->addPlugin('jaxl_get_id', array($echobot, 'getId'));
// Fire start Jaxl core
$jaxl->startCore("stream");
?>
|
jaxl/JAXL | 3b3d11e55d79948d31c34683a0631d06ff3562c5 | Auto detect bosh poll url in boshchat.php | diff --git a/app/boshchat.php b/app/boshchat.php
index 6a04e2c..47aa373 100644
--- a/app/boshchat.php
+++ b/app/boshchat.php
@@ -1,319 +1,319 @@
<?php
/*
* Sample browser based one-to-one chat application using Jaxl library
* Usage: Copy this application file (along with /path/to/jaxl/env/jaxl.js) into your web folder.
* Edit "BOSHCHAT_POLL_URL" below to suit your environment.
* Run this app file from the browser.
* Read more: http://bit.ly/aMozMy
*/
// Ajax poll url
- define('BOSHCHAT_POLL_URL', 'http://localhost/boshchat.php');
+ define('BOSHCHAT_POLL_URL', 'http://'.$_SERVER['HTTP_HOST'].'/boshchat.php');
// Admin jid who will receive all messages sent using this application ui
define('BOSHCHAT_ADMIN_JID', 'admin@localhost');
if(isset($_REQUEST['jaxl'])) { // Valid bosh request
// Initialize Jaxl Library
require_once '/usr/share/php/jaxl/core/jaxl.class.php';
$jaxl = new JAXL(array(
'host'=>'localhost',
'domain'=>'localhost',
'port'=>5222,
'boshHost'=>'localhost',
'authType'=>'DIGEST-MD5',
'logLevel'=>5
));
// Include required XEP's
$jaxl->requires(array(
'JAXL0115', // Entity Capabilities
'JAXL0085', // Chat State Notification
'JAXL0092', // Software Version
'JAXL0203', // Delayed Delivery
'JAXL0202', // Entity Time
'JAXL0206' // XMPP over Bosh
));
// Sample Bosh chat application class
class boshchat {
public static function postAuth($payload, $jaxl) {
$response = array('jaxl'=>'connected', 'jid'=>$jaxl->jid);
$jaxl->JAXL0206('out', $response);
}
public static function postRosterUpdate($payload, $jaxl) {
$response = array('jaxl'=>'rosterList', 'roster'=>$jaxl->roster);
$jaxl->JAXL0206('out', $response);
}
public static function postDisconnect($payload, $jaxl) {
$response = array('jaxl'=>'disconnected');
$jaxl->JAXL0206('out', $response);
}
public static function getMessage($payloads, $jaxl) {
$html = '';
foreach($payloads as $payload) {
// reject offline message
if($payload['offline'] != JAXL0203::$ns && $payload['type'] == 'chat') {
if(strlen($payload['body']) > 0) {
$html .= '<div class="mssgIn">';
$html .= '<p class="from">'.$payload['from'].'</p>';
$html .= '<p class="body">'.$payload['body'].'</p>';
$html .= '</div>';
}
else if(isset($payload['chatState']) && in_array($payload['chatState'], JAXL0085::$chatStates)) {
$html .= '<div class="presIn">';
$html .= '<p class="from">'.$payload['from'].' chat state '.$payload['chatState'].'</p>';
$html .= '</div>';
}
}
}
if($html != '') {
$response = array('jaxl'=>'message', 'message'=>urlencode($html));
$jaxl->JAXL0206('out', $response);
}
return $payloads;
}
public static function getPresence($payloads, $jaxl) {
$html = '';
foreach($payloads as $payload) {
if($payload['type'] == '' || in_array($payload['type'], array('available', 'unavailable'))) {
$html .= '<div class="presIn">';
$html .= '<p class="from">'.$payload['from'];
if($payload['type'] == 'unavailable') $html .= ' is now offline</p>';
else $html .= ' is now online</p>';
$html .= '</div>';
}
}
if($html != '') {
$response = array('jaxl'=>'presence', 'presence'=>urlencode($html));
$jaxl->JAXL0206('out', $response);
}
return $payloads;
}
public static function postEmptyBody($body, $jaxl) {
$response = array('jaxl'=>'pinged');
$jaxl->JAXL0206('out', $response);
}
public static function postAuthFailure($payload, $jaxl) {
$response = array('jaxl'=>'authFailed');
$jaxl->JAXL0206('out', $response);
}
public static function postCurlErr($payload, $jaxl) {
if($_REQUEST['jaxl'] == 'disconnect') self::postDisconnect($payload, $jaxl);
else $jaxl->JAXL0206('out', array('jaxl'=>'curlError', 'code'=>$payload['errno'], 'msg'=>$payload['errmsg']));
}
}
// Add callbacks on various event handlers
$jaxl->addPlugin('jaxl_post_auth_failure', array('boshchat', 'postAuthFailure'));
$jaxl->addPlugin('jaxl_post_auth', array('boshchat', 'postAuth'));
$jaxl->addPlugin('jaxl_post_disconnect', array('boshchat', 'postDisconnect'));
$jaxl->addPlugin('jaxl_get_empty_body', array('boshchat', 'postEmptyBody'));
$jaxl->addPlugin('jaxl_get_bosh_curl_error', array('boshchat', 'postCurlErr'));
$jaxl->addPlugin('jaxl_get_message', array('boshchat', 'getMessage'));
$jaxl->addPlugin('jaxl_get_presence', array('boshchat', 'getPresence'));
$jaxl->addPlugin('jaxl_post_roster_update', array('boshchat', 'postRosterUpdate'));
// Handle incoming bosh request
switch($_REQUEST['jaxl']) {
case 'connect':
$jaxl->user = $_POST['user'];
$jaxl->pass = $_POST['pass'];
$jaxl->startCore('bosh');
break;
case 'disconnect':
$jaxl->JAXL0206('endStream');
break;
case 'getRosterList':
$jaxl->getRosterList();
break;
case 'setStatus':
$jaxl->setStatus(FALSE, FALSE, FALSE, TRUE);
break;
case 'message':
$jaxl->sendMessage(BOSHCHAT_ADMIN_JID, $_POST['message']);
break;
case 'ping':
$jaxl->JAXL0206('ping');
break;
case 'jaxl':
$jaxl->JAXL0206('jaxl', $_REQUEST['xml']);
break;
default:
$response = array('jaxl'=>'400', 'desc'=>$_REQUEST['jaxl']." not implemented");
$jaxl->JAXL0206('out', $response);
break;
}
}
if(!isset($_REQUEST['jaxl'])) {
// Serve application UI if $_REQUEST['jaxl'] is not set
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" dir="ltr">
<head profile="http://gmpg.org/xfn/11">
<link rel="SHORTCUT ICON" href="http://im.jaxl.im/favicon.ico" type="image/x-icon">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Web Chat Application using Jaxl Library</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jaxl.js"></script>
<script type="text/javascript">jaxl.pollUrl = "<?php echo BOSHCHAT_POLL_URL; ?>";</script>
<style type="text/css">
body { color:#444; background-color:#F7F7F7; font:62.5% "lucida grande","lucida sans unicode",helvetica,arial,sans-serif; }
label, input { margin-bottom:5px; }
#read { width:700px; height:250px; overflow-x:hidden; overflow-y:auto; background-color:#FFF; border:1px solid #E7E7E7; display:none; }
#read .mssgIn, #read .presIn { text-align:left; margin:5px; padding:0px 5px; border-bottom:1px solid #EEE; }
#read .presIn { background-color:#F7F7F7; font-size:11px; font-weight:normal; }
#read .mssgIn p.from, #read .presIn p.from { padding:0px; margin:0px; font-size:13px; }
#read .mssgIn p.from { font-weight:bold; }
#read .mssgIn p.body { padding:0px; margin:0px; font-size:12px; }
#write { width:698px; border:1px solid #E7E7E7; background-color:#FFF; height:20px; padding:1px; font-size:13px; color:#AAA; display:none; }
</style>
<script type="text/javascript">
var boshchat = {
payloadHandler: function(payload) {
if(payload.jaxl == 'authFailed') {
jaxl.connected = false;
$('#button input').val('Connect');
}
else if(payload.jaxl == 'connected') {
jaxl.connected = true;
jaxl.jid = payload.jid;
$('#uname').css('display', 'none');
$('#passwd').css('display', 'none');
$('#button input').val('Disconnect');
$('#read').css('display', 'block');
$('#write').css('display', 'block');
obj = new Object;
obj['jaxl'] = 'getRosterList';
jaxl.sendPayload(obj);
}
else if(payload.jaxl == 'rosterList') {
obj = new Object;
obj['jaxl'] = 'setStatus';
jaxl.sendPayload(obj);
}
else if(payload.jaxl == 'disconnected') {
jaxl.connected = false;
jaxl.disconnecting = false;
$('#read').css('display', 'none');
$('#write').css('display', 'none');
$('#uname').css('display', 'block');
$('#passwd').css('display', 'block');
$('#button input').val('Connect');
console.log('disconnected');
}
else if(payload.jaxl == 'message') {
boshchat.appendMessage(jaxl.urldecode(payload.message));
jaxl.ping();
}
else if(payload.jaxl == 'presence') {
boshchat.appendMessage(jaxl.urldecode(payload.presence));
jaxl.ping();
}
else if(payload.jaxl == 'pinged') {
jaxl.ping();
}
},
appendMessage: function(message) {
$('#read').append(message);
$('#read').animate({ scrollTop: $('#read').attr('scrollHeight') }, 300);
},
prepareMessage: function(jid, message) {
html = '';
html += '<div class="mssgIn">';
html += '<p class="from">'+jid+'</p>';
html += '<p class="body">'+message+'</div>';
html += '</div>';
return html;
}
};
jQuery(function($) {
$(document).ready(function() {
jaxl.payloadHandler = new Array('boshchat', 'payloadHandler');
$('#button input').click(function() {
if($(this).val() == 'Connect') {
$(this).val('Connecting...');
// prepare connect object
obj = new Object;
obj['user'] = $('#uname input').val();
obj['pass'] = $('#passwd input').val();
jaxl.connect(obj);
}
else if($(this).val() == 'Disconnect') {
$(this).val('Disconnecting...');
jaxl.disconnect();
}
});
$('#write').focus(function() {
$(this).val('');
$(this).css('color', '#444');
});
$('#write').blur(function() {
if($(this).val() == '') $(this).val('Type your message');
$(this).css('color', '#AAA');
});
$('#write').keydown(function(e) {
if(e.keyCode == 13 && jaxl.connected) {
message = $.trim($(this).val());
if(message.length == 0) return false;
$(this).val('');
boshchat.appendMessage(boshchat.prepareMessage(jaxl.jid, message));
obj = new Object;
obj['jaxl'] = 'message';
obj['message'] = message;
jaxl.sendPayload(obj);
}
});
});
});
</script>
</head>
<body>
<center>
<h1>Web Chat Application using Jaxl Library</h1>
<div id="uname">
<label>Username:</label>
<input type="text" value=""/>
</div>
<div id="passwd">
<label>Password:</label>
<input type="password" value=""/>
</div>
<div id="read"></div>
<input type="text" value="Type your message" id="write"></input>
<div id="button">
<label></label>
<input type="button" value="Connect"/>
</div>
</center>
</body>
</html>
|
jaxl/JAXL | f46348b8d93db021fd6b8d10d4746793fe7e93be | Added hook for jaxl_get_bosh_curl_error which is called when bosh end point returns a non-zero errno. Updated Jaxl core session variable names to avoid clash with existing session vars. Updated boshchat.php to make use of jaxl_get_bosh_curl_error to disconnect intelligently | diff --git a/CHANGELOG b/CHANGELOG
index c573da5..20851a9 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,306 +1,309 @@
version 2.1.2
-------------
+- Added hook for jaxl_get_bosh_curl_error which is called when bosh end point returns a non-zero errno
+ Updated Jaxl core session variable names to avoid clash with existing session vars
+ Updated boshchat.php to make use of jaxl_get_bosh_curl_error to disconnect intelligently
- PHP CMS looking to integrate Jaxl in their core can now force disable auto start of php session by Jaxl core
Simple pass 'boshSession' as false with jaxl constructor config array
- Entire Jaxl core including xmpp/, xep/ and core/ class files now make use of JAXL::addPlugin instead of JAXLPlugin to register per instance callbacks
- JAXLPlugin can now register a callback for a dedicated jaxl instance in a multi-instance jaxl application
Class functionality remains backward compatible.
- JAXLog class now also dump connect instance uid per log line
- XMPP instance iq id now defaults to a random value between 1 and 9
Also added jaxl_get_id event hook for apps to customize iq id for the connected Jaxl instance
Also as compared to default numeric iq id, Jaxl core now uses hex iq id's
- Every jaxl instance per php process id now generate it's own unique id JAXL::$uid
- Jaxl core doesn't go for a session if it's optional as indicated by the xmpp server
- Fixed boshChat postBind issues as reported by issue#26 (http://code.google.com/p/jaxl/issues/detail?id=26)
- Fixed jaxl constructor config read warning and XEP 0114 now make use of JAXL::getConfigByPriority method
- Removed warning while reading user config inside Jaxl constructor
Upgraded Jaxl Parser class which was malfunctioning on CentOS PHP 5.1.6 (cli)
- Added bosh error response handling and appropriate logging inside XMPP over Bosh core files
- Code cleanup inside jaxl logger class.
Fixed getConfigByPriority method which was malfunctioning in specific cases
- JAXLog class now using inbuild php function (error_log)
- Checking in first version of XEP-0016 (Privacy Lists), XEP-0055 (Jabber Search), XEP-0077 (In-Band Registration), XEP-0144 (Roster Item Exchange), XEP-0153 (vCard-Based Avatars), XEP-0237 (Roster Versioning)
- On auth faliure core doesn't throw exception since XMPP over Bosh apps are not held inside a try catch block (a better fix may be possible in future)
- XMPP over BOSH xep wasn't passing back Jaxl instance obj for jaxl_post_disconnect hook, fixed that for clean disconnect
- Jaxl core attempts to create log and pid files if doesn't already exists
Also instead of die() core throws relevant exception message wherever required
XMPP base classes throws relevant exception with message wherever required
- First commit of JAXLException class. JAXL core now uses JAXLException
- Jaxl constructor dies if logPath, pidPath and tmpPath doesn't exists on the system
- Core updates JAXL::resource after successful binding to match resource assigned by the connecting server
- Updated echobot sample example to make use of autoSubscribe core feature
Also registers callback for jaxl_post_subscription_request and jaxl_post_subscription_accept hooks
- Updated echobot and boshchat application to use in memory roster cache maintained by Jaxl core.
App files should register callback on hook jaxl_post_roster_update to get notified everytime local roster cache is updated
- Added provision for local roster cache management inside Jaxl core.
Retrived roster lists are cached in memory (see updated echobot.php sample example).
Also added provision for presence tracking (JAXL::trackPresence).
If enabled Jaxl core keep a track of jid availability and update local roster cache accordingly.
Also added provision for auto-accept subscription (JAXL::autoSubscribe).
- Removed XMPP::isConnected variable which used to tell status of connected socket stream.
This is equivalent to checking XMPP:stream variable for true/false
- Added a (kind of) buggy support for '/xml()' inside parser xpath
- If Jaxl instance has being configured for auto periodic ping (XEP-0199), pings are holded till auth completion.
Also if server responds 'feature-not-implemented' for first ping XEP-0199 automatically deleted periodic ping cron tab
- Corrected handling of error type iq stanza's (removed jaxl_get_iq_error hook)
- Added iq error code xpath inside JAXLXml class
- Completed missing JAXLCron::delete method for removing a previously registered cron tab
- Checking in first version of XEP-0049 (Private XML Storage) (not yet tested)
- Checking in first version of XEP-0191 (Simple Communication Blocking) (not yet tested)
- Added JAXL_PING_INTERVAL configuration option inside jaxl.ini
- XEP-0199 (XMPP Ping) can now automatically ping the connected server periodically for keeping connection alive on long running bots
(see echobot.php sample app for usage)
- Updated JAXLCron::add method to accept a number of arguments while adding bckgrnd jobs
These list of arguments is passed back to the application method
- Updated IQ handling inside XEP-0202 which wasn't returning iq stanza back resulting in no ping/pong
- Updated echobot to show usage of JAXL::discoItems and JAXL::discoInfo inside application code
- Added tagMap xpath for service identity and feature nodes in service discovery resultset
- JAXL core now auto includes XEP-0128 along with XEP-0030 on startup.
Also added two methods JAXL::discoItems and JAXL::discoInfo for service discovery
- Checking in first version of XEP-0128 (Service Discovery Extension)
- Fixed bug where message and presence stanza builder were not using passed id value as attribute
- Removed jaxl_pre_curl event hook which was only used internally by XEP-0124
- Jaxl now shutdown gracefully is encryption is required and openssl PHP module is not loaded in the environment
- For every registered callback on XMPP hooks, callback'd method will receive two params.
A payload and reference of Jaxl instance for whom XMPP event has occured.
Updated sample application code to use passed back Jaxl instance reference instead of global jaxl variable.
- As a library convention XEP's exposing user space configuration parameters via JAXL constructor SHOULD utilize JAXL::getConfigByPriority method
Added JAXL_TMP_PATH option inside jaxl.ini
- Jaxl::tmp is now Jaxl::tmpPath. Also added Jaxl config param to specify custom tmp path location
Jaxl client also self detect the IP of the host it is running upon (to be used by STUN/TURN utilities in Jingle negotitation)
- Removed JAXLUtil::includePath and JAXLUtil::getAppFilePath methods which are now redundant after removing jaxl.ini and jaxl.conf from lib core
- Removed global defines JAXL_BASE_PATH, JAXL_APP_BASE_PATH, JAXL_BOSH_APP_ABS_PATH from inside jaxl.ini (No more required by apps to specify these values)
- Removing env/jaxl.php and env/jaxl.conf (were required if you run your apps using `jaxl` command line utility)
Updated env/jaxl.ini so that projects can now directly include their app setting via jaxl.ini (before including core/jaxl.class.php)
- Added JAXL::bareJid public variable for usage inside applications.
XMPP base class now return bool on socket connect completion (used by PHPUnit test cases)
- Removing build.sh file from library for next release
Users should simply download, extract, include and write their app code without caring about the build script from 2.1.2 release
- As a library convention to include XEP's use JAXL::requires() method, while to include any core/ or xmpp/ base class use jaxl_require() method.
Updated library code and xep's to adhere to this convention.
Jaxl instance now provide a system specific /tmp folder location accessible by JAXL::tmp
- Removed JAXL_NAME and JAXL_VERSION constants.
Instead const variables are now defined per instance accessible by getName() and getVersion() methods.
Updated XEP-0030,0092,0115 to use the same
- Moved indivisual XEP's working parameter (0114,0124) from JAXL core class to XEP classes itself.
XEP's make use of JAXL::config array for parsing user options.
- Added JAXL_COMPONENT_PASS option inside jaxl.ini. Updated build.sh with new /app file paths.
Updated XEP-0114,0124,0206 to use array style configs as defined inside JAXL class
- Removed dependency upon jaxl.ini from all sample applications.
First checkin of sample sendMessage.php app.
- Config parameters for XEP's like 0114 and 0206 are now saved as an array inside JAXL class (later on they will be moved inside respective XEP's).
Added constructor config option to pre-choose an auth mechanism to be performed
if an auth mech is pre-chosen app files SHOULD not register callback for jaxl_get_auth_mech hook.
Bosh cookie settings can now be passed along with Jaxl constructor.
Added support for publishing vcard-temp:x:update node along with presence stanzas.
Jaxl instance can run in 3 modes a.k.a. stream,component and bosh mode
applications should use JAXL::startCore('mode') to configure instance for a specific mode.
- Removed redundant NS variable from inside XEP-0124
- Moved JAXLHTTPd setting defines inside the class (if gone missing CPU usage peaks to 100%)
- Added jaxl_httpd_pre_shutdown, jaxl_httpd_get_http_request, jaxl_httpd_get_sock_request event hooks inside JAXLHTTPd class
- Added JAXLS5B path (SOCKS5 implementation) inside jaxl_require method
- Removed all occurance of JAXL::$action variable from /core and /xep class files
- Updated boshChat and boshMUChat sample application which no longer user JAXL::$action variable inside application code
- Updated preFetchBOSH and preFetchXMPP sample example.
Application code don't need any JAXL::$action variable now
Neither application code need to define JAXL_BASE_PATH (optional from now on)
- JAXL core and XEP-0206 have no relation and dependency upon JAXL::$action variable now.
- Deprecated jaxl_get_body hook which was only for XEP-0124 working.
Also cleaned up XEP-0124 code by removing processBody method which is now handled inside preHandler itself.
- Defining JAXL_BASE_PATH inside application code made optional.
Developers can directly include /path/to/jaxl/core/jaxl.class.php and start writing applications.
Also added a JAXL::startCore() method (see usage in /app/preFetchXMPP.php).
Jaxl magic method for calling XEP methods now logs a warning inside jaxl.log if XEP doesn't exists in the environment
- Added tag map for XMPP message thread and subject child elements
- Fixed typo where in case of streamError proper description namespace was not parsed/displayed
- Disabled BOSH session close if application is running in boshOut=false mode
Suggested by MOVIM dev team who were experiencing loss of session data on end of script
- JAXL::log method 2nd parameter now defaults to logLevel=1 (passing 2nd param is now optional)
- Fixed XPath for iq stanza error condition and error NS extraction inside jaxl.parser.class
- First checkin of XEP-0184 Message Receipts
- Added support for usage of name() xpath function inside tag maps of JAXLXml class.
Also added some documentation for methods available inside JAXLXml class
- Fixed JAXLPlugin::remove method to properly remove and manage callback registry.
Also added some documentation for JAXLPlugin class methods
- Added JAXL contructor config option to disable BOSH module auto-output behaviour.
This is utilized inside app/preFetchBOSH.php sample example
- First checkin of sample application code pre-fetching XMPP/Jabber data for web page population using BOSH XEP
- Added a sample application file which can be used to pre-fetch XMPP/Jabber data for a webpage without using BOSH XEP or Ajax requests
As per the discussion on google groups (http://bit.ly/aKavZB) with MOVIM team
- JAXL library is now $jaxl independent, you can use anything like $var = new JAXL(); instance your applications now
JAXLUtil::encryptPassword now accepts username/password during SASL auth.
Previously it used to auto detect the same from JAXL instance, now core has to manually pass these param
- Added JAXL::startHTTPd method with appropriate docblock on how to convert Jaxl instance into a Jaxl socket (web) server.
Comments also explains how to still maintaining XMPP communication in the background
- Updated JAXLHTTPd class to use new constants inside jaxl.ini
- Added jaxl_get_stream_error event handler.
Registered callback methods also receive array form of received XMPP XML stanza
- Connecting Jaxl instance now fallback to default value 'localhost' for host,domain,boshHost,boshPort,boshSuffix
If these values are not configured either using jaxl.ini constants or constructor
- Provided a sendIQ method per JAXL instance.
Recommended that applications and XEP's should directly use this method for sending <iq/> type stanza
DONOT use XMPPSend methods inside your application code from here on
- Added configuration options for JAXL HTTPd server and JAXL Bosh Component Manager inside jaxl.ini
- Fixed type in XEP-0202 (Entity Time). XEP was not sending <iq/> id in response to get request
- Jaxl library is now phpdocs ready. Added extended documentation for JAXL core class, rest to be added
- All core classes inside core/, xmpp/ and xep/ folder now make use of jaxl->log method
JAXL Core constructor are now well prepared so that inclusion of jaxl.ini is now optional
Application code too should use jaxl->log instead of JAXLog::log method for logging purpose
- Reshuffled core instance paramaters between JAXL and XMPP class
Also Jaxl core now logs at level 1 instead of 0 (i.e. all logs goes inside jaxl.log and not on console)
- JAXL class now make use of endStream method inside XMPP base class while disconnecting.
Also XMPPSend::endStream now forces xmpp stanza delivery (escaping JAXL internal buffer)
http://code.google.com/p/jaxl/issues/detail?id=23
- Added endStream method inside XMPP base class and startSession,startBind methods inside XMPPSend class
XMPP::sendXML now accepts a $force parameter for escaping XMPP stanza's from JAXL internal buffer
- Updated the way Jaxl core calls XEP 0115 method (entity caps) to match documentation
XEP method's should accept jaxl instance as first paramater
- First checkin of PEP (Personal Eventing), User Location, User Mood, User Activity and User Tune XEP's
- Completed methods discoFeatures, discoNodes, discoNodeInfo, discoNodeMeta and discoNodeItems in PubSub XEP
- Hardcoded client category, type, lang and name. TODO: Make them configurable in future
- Cleaned up XEP 0030 (Service Discovery) and XEP 0115 (Entity Capabilities)
- Updated XMPP base class to use performance configuration parameters (now customizable with JAXL constructor)
- jaxl.conf will be removed from jaxl core in future, 1st step towards this goal
- Moved bulk of core configs from jaxl.conf
- Added more configuration options relating to client performance e.g. getPkts, getPktSize etc
- Fixed client mode by detecting sapi type instead of $_REQUEST['jaxl'] variable
- Now every implemented XEP should have an 'init' method which will accept only one parameter (jaxl instance itself)
- Jaxl core now converts transmitted stanza's into xmlentities (http://code.google.com/p/jaxl/issues/detail?id=22)
- Created a top level 'patch' folder which contains various patches sent by developers using 'git diff > patch' utility
- Fixed typo in namespace inside 0030 (thanks to Thomas Baquet for the patch)
- First checkin of PubSub XEP (untested)
- Indented build.sh and moved define's from top of JAXLHTTPd class to jaxl.ini
- Added JAXLHTTPd inside Jaxl core (a simple socket select server)
- Fixed sync of background iq and other stanza requests with browser ajax calls
- Updated left out methods in XMPP over BOSH xep to accept jaxl instance as first method
- All XEP methods available in application landspace, now accepts jaxl instance as first parameter. Updated core jaxl class magic method to handle the same.
If you are calling XEP methods as specified in the documentation, this change will not hurt your running applications
- Updated echobot sample application to utilize XEP 0054 (VCard Temp) and 0202 (Entity Time)
- First checkin of missing vcard-temp xep
- Added xmlentities JAXLUtil method
- Jaxl Parser now default parses xXmlns node for message stanzas
- Added PCRE_DOTALL and PCRE_MULTILINE pattern modifier for bosh unwrapBody method
- Added utility methods like urldecode, urlencode, htmlEntities, stripHTML and splitJid inside jaxl.js
- Updated sample application jaxl.ini to reflect changes in env/jaxl.ini
version 2.1.1
-------------
- Updated XMPPSend 'presence', 'message' and 'iq' methods to accept $jaxl instance as first parameter
if you are not calling these methods directly from your application code as mentioned in documentation
this change should not hurt you
- Added more comments to env/jaxl.ini and also added JAXL_LOG_ROTATE ini file option
- JAXL instance logs can be rotated every x seconds (logRotate config parameter) now
- Removed config param dumpTime, instead use dumpStat to specify stats dump period
- Base XMPP class now auto-flush output buffers filled because of library level rate limiter
- Added more options for JAXL constructor e.g.
boshHost, boshPort, boshSuffix, pidPath, logPath, logLevel, dumpStat, dumpTime
These param overwrites value specified inside jaxl.ini file
Also JAXL core will now periodically dump instance statistics
- Added an option in JAXL constructor to disable inbuild core rate limiter
- Added support when applications need to connect with external bosh endpoints
Bosh application code requires update for ->JAXL0206('startStream') method
- XMPPGet::handler replaces ->handler inside XEP-0124
- JAXLCron job now also passes connected instance to callback cron methods
- Updated base XMPP class now maintains a clock, updated sendXML method to respect library level rate limiting
- Base JAXL class now includes JAXLCron class for periodically dumping connected bot memory/usage stats
- First version of JAXLCron class for adding periodic jobs in the background
- XMPP payload handler moves from XMPPGet to base XMPP class, packets are then routed to XMPPGet class for further processing
- Updated xep-0124 to use instance bosh parameters instead of values defined inside jaxl.ini
- Provision to specify custom JAXL_BOSH_HOST inside jaxl.ini
- Instead of global logLevel and logPath, logger class now respects indivisual instance log settings
Helpful in multiple instance applications
- Updated base JAXL class to accept various other configuration parameters inside constructor
These param overwrites values defined inside jaxl.ini
- XMPPSend::xml method moves inside XMPP::sendXML (call using ->sendXML from within application code), as a part of library core cleanup
- Updated jaxl class to return back payload from called xep methods
- XMPP base method getXML can be instructed not to take a nap between stream reads
- Added jaxl_get_xml hook for taking control over incoming xml payload from xmpp stream
- Added support for disabling sig term registration, required by applications who already handle this in their core code
- Added capability of sending multiple message/presence stanza in one go inside jaxl base class
- Fixed typo in MUC Direct Invitation xep invite method
- getHandler should have accepted core instance by reference, fixed now. BOSH MUC Chat sample application header is now more appropriate
version 2.1.0
-------------
- First checkin of bosh MUC sample application
- Updated build file now packages bosh MUC chat sample application along with core classes
- Updated JAXLog class to accept instance inside log() method, application code should use ->log() to call JAXLog::log() method now
- Updated JAXLPlugin class to pass instance along with every XMPP event hook
- Updated jaxl_require method to call including XEP's init() method every time they are included using jaxl_require method
- Update jaxl.ini with some documentation/comments about JAXL_BOSH_COOKIE_DOMAIN parameter
- Updated echobot sample application code to pass instance while calling jaxl_require method
- Update XMPP SASL Auth class to accept instance while calculating SASL response.
Also passinginstance when jaxl_get_facebook_key hook is called
- Updated XMPP base class to accept component host name inside constructor.
Sending currentinstance with every XMPPSend, XMPPGet and JAXLog method calls
- Every XMPPGet method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Every XMPPSend method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Updated component bot sample application to show how to pass component host inside JAXL constructor.
Also updated jaxl_require call to accept current working instance
- Updated boshchat sample application to follow new rules of jaxl_require, also cleaned up the sample app code a bit
- Updated jaxl.ini of packaged sample applications to match /env/jaxl.ini
- Updated implemented XEP's init method to accept instance during initialization step
Send working instance with every XMPPSend method call
Almost every XEP's available method now accepts an additional instance so that XEP's can work independently for every instance inside a multiple jaxl instance application code
- Added magic method __call inside JAXL class
All application codes should now call a methods inside implemented XEP's like ->JAXLxxxx('method', , , ...)
Also added ->log method to be used by application codes
JAXLog::log() should not be called directly from application code
Updated XMPPSend methods to accept instance
Added ->requires() method that does a similar job as jaxl_require() which now also expects instance as one of the passed parameter.
version 2.0.4
-------------
- Updated XMPP base class and XMPP Get class to utilize new XMPPAuth class
- Updated jaxl_require method with new XMPPAuth class path
- Extracted XMPP SASL auth mechanism out of XMPP Get class, code cleanup
- unwrapBody method of XEP 0124 is now public
- Added #News block on top of README
- No more capital true, false, null inside Jaxl core to pass PHP_CodeSniffer tests
- :retab Jaxl library core to pass PHP_CodeSniffer tests
- Added Jabber Component Protocol example application bot
- Updated README with documentation link for Jabber component protocol
- Updated Entity Caps method to use list of passed feature list for verification code generation
- Updated MUC available methods doc link inside README
- Added experimental support for SCRAM-SHA-1, CRAM-MD5 and LOGIN auth mechanisms
version 2.0.3
-------------
- Updated Jaxl XML parsing class to handle multiple level nested child cases
- Updated README and bosh chat application with documentation link
- Fixed bosh application to run on localhost
- Added doc links inside echobot sample app
- Bosh sample application also use entity time XEP-0202 now
- Fix for sapi detection inside jaxl util
- jaxl.js updated to handle multiple ajax poll response payloads
- Bosh session manager now dumps ajax poll response on post handler callback
- Removed hardcoded ajax poll url inside boshchat application
- Updated component protocol XEP pre handshake event handling
version 2.0.2
-------------
- Packaged XEP 0202 (Entity Time)
- First checkin of Bosh related XEP 0124 and 0206
- Sample Bosh Chat example application
- Updated jaxl.class.php to save Bosh request action parameter
- jaxl.ini updated with Bosh related cookie options, default loglevel now set to 4
- jaxl.js checkin which should be used with bosh applications
- Updated base xmpp classes to provide integrated bosh support
- Outgoing presence and message stanza's too can include @id attribute now
version 2.0.1
-------------
- Typo fix in JAXLXml::$tagMap for errorCode
- Fix for handling overflooded roster list
- Packaged XEP 0115 (Entity capability) and XEP 0199 (XMPP Ping)
- Updated sample echobot to use XEP 0115 and XEP 0199
- Support for X-FACEBOOK-PLATFORM authentication
version 2.0.0
--------------
First checkin of:
- Restructed core library with event mechanism
- Packaged XEP 0004, 0030, 0045, 0050, 0085, 0092, 0114, 0133, 0249
- Sample echobot application
diff --git a/app/boshchat.php b/app/boshchat.php
index 76022eb..6a04e2c 100644
--- a/app/boshchat.php
+++ b/app/boshchat.php
@@ -1,313 +1,319 @@
<?php
/*
* Sample browser based one-to-one chat application using Jaxl library
* Usage: Copy this application file (along with /path/to/jaxl/env/jaxl.js) into your web folder.
* Edit "BOSHCHAT_POLL_URL" below to suit your environment.
* Run this app file from the browser.
* Read more: http://bit.ly/aMozMy
*/
// Ajax poll url
define('BOSHCHAT_POLL_URL', 'http://localhost/boshchat.php');
// Admin jid who will receive all messages sent using this application ui
define('BOSHCHAT_ADMIN_JID', 'admin@localhost');
if(isset($_REQUEST['jaxl'])) { // Valid bosh request
// Initialize Jaxl Library
require_once '/usr/share/php/jaxl/core/jaxl.class.php';
$jaxl = new JAXL(array(
'host'=>'localhost',
'domain'=>'localhost',
'port'=>5222,
'boshHost'=>'localhost',
'authType'=>'DIGEST-MD5',
'logLevel'=>5
));
// Include required XEP's
$jaxl->requires(array(
'JAXL0115', // Entity Capabilities
'JAXL0085', // Chat State Notification
'JAXL0092', // Software Version
'JAXL0203', // Delayed Delivery
'JAXL0202', // Entity Time
'JAXL0206' // XMPP over Bosh
));
// Sample Bosh chat application class
class boshchat {
public static function postAuth($payload, $jaxl) {
$response = array('jaxl'=>'connected', 'jid'=>$jaxl->jid);
$jaxl->JAXL0206('out', $response);
}
public static function postRosterUpdate($payload, $jaxl) {
$response = array('jaxl'=>'rosterList', 'roster'=>$jaxl->roster);
$jaxl->JAXL0206('out', $response);
}
public static function postDisconnect($payload, $jaxl) {
$response = array('jaxl'=>'disconnected');
$jaxl->JAXL0206('out', $response);
}
public static function getMessage($payloads, $jaxl) {
$html = '';
foreach($payloads as $payload) {
// reject offline message
if($payload['offline'] != JAXL0203::$ns && $payload['type'] == 'chat') {
if(strlen($payload['body']) > 0) {
$html .= '<div class="mssgIn">';
$html .= '<p class="from">'.$payload['from'].'</p>';
$html .= '<p class="body">'.$payload['body'].'</p>';
$html .= '</div>';
}
else if(isset($payload['chatState']) && in_array($payload['chatState'], JAXL0085::$chatStates)) {
$html .= '<div class="presIn">';
$html .= '<p class="from">'.$payload['from'].' chat state '.$payload['chatState'].'</p>';
$html .= '</div>';
}
}
}
if($html != '') {
$response = array('jaxl'=>'message', 'message'=>urlencode($html));
$jaxl->JAXL0206('out', $response);
}
return $payloads;
}
public static function getPresence($payloads, $jaxl) {
$html = '';
foreach($payloads as $payload) {
if($payload['type'] == '' || in_array($payload['type'], array('available', 'unavailable'))) {
$html .= '<div class="presIn">';
$html .= '<p class="from">'.$payload['from'];
if($payload['type'] == 'unavailable') $html .= ' is now offline</p>';
else $html .= ' is now online</p>';
$html .= '</div>';
}
}
if($html != '') {
$response = array('jaxl'=>'presence', 'presence'=>urlencode($html));
$jaxl->JAXL0206('out', $response);
}
return $payloads;
}
public static function postEmptyBody($body, $jaxl) {
$response = array('jaxl'=>'pinged');
$jaxl->JAXL0206('out', $response);
}
public static function postAuthFailure($payload, $jaxl) {
$response = array('jaxl'=>'authFailed');
$jaxl->JAXL0206('out', $response);
}
+
+ public static function postCurlErr($payload, $jaxl) {
+ if($_REQUEST['jaxl'] == 'disconnect') self::postDisconnect($payload, $jaxl);
+ else $jaxl->JAXL0206('out', array('jaxl'=>'curlError', 'code'=>$payload['errno'], 'msg'=>$payload['errmsg']));
+ }
}
// Add callbacks on various event handlers
$jaxl->addPlugin('jaxl_post_auth_failure', array('boshchat', 'postAuthFailure'));
$jaxl->addPlugin('jaxl_post_auth', array('boshchat', 'postAuth'));
$jaxl->addPlugin('jaxl_post_disconnect', array('boshchat', 'postDisconnect'));
$jaxl->addPlugin('jaxl_get_empty_body', array('boshchat', 'postEmptyBody'));
+ $jaxl->addPlugin('jaxl_get_bosh_curl_error', array('boshchat', 'postCurlErr'));
$jaxl->addPlugin('jaxl_get_message', array('boshchat', 'getMessage'));
$jaxl->addPlugin('jaxl_get_presence', array('boshchat', 'getPresence'));
$jaxl->addPlugin('jaxl_post_roster_update', array('boshchat', 'postRosterUpdate'));
// Handle incoming bosh request
switch($_REQUEST['jaxl']) {
case 'connect':
$jaxl->user = $_POST['user'];
$jaxl->pass = $_POST['pass'];
$jaxl->startCore('bosh');
break;
case 'disconnect':
$jaxl->JAXL0206('endStream');
break;
case 'getRosterList':
$jaxl->getRosterList();
break;
case 'setStatus':
$jaxl->setStatus(FALSE, FALSE, FALSE, TRUE);
break;
case 'message':
$jaxl->sendMessage(BOSHCHAT_ADMIN_JID, $_POST['message']);
break;
case 'ping':
$jaxl->JAXL0206('ping');
break;
case 'jaxl':
$jaxl->JAXL0206('jaxl', $_REQUEST['xml']);
break;
default:
$response = array('jaxl'=>'400', 'desc'=>$_REQUEST['jaxl']." not implemented");
$jaxl->JAXL0206('out', $response);
break;
}
}
if(!isset($_REQUEST['jaxl'])) {
// Serve application UI if $_REQUEST['jaxl'] is not set
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" dir="ltr">
<head profile="http://gmpg.org/xfn/11">
<link rel="SHORTCUT ICON" href="http://im.jaxl.im/favicon.ico" type="image/x-icon">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Web Chat Application using Jaxl Library</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jaxl.js"></script>
<script type="text/javascript">jaxl.pollUrl = "<?php echo BOSHCHAT_POLL_URL; ?>";</script>
<style type="text/css">
body { color:#444; background-color:#F7F7F7; font:62.5% "lucida grande","lucida sans unicode",helvetica,arial,sans-serif; }
label, input { margin-bottom:5px; }
#read { width:700px; height:250px; overflow-x:hidden; overflow-y:auto; background-color:#FFF; border:1px solid #E7E7E7; display:none; }
#read .mssgIn, #read .presIn { text-align:left; margin:5px; padding:0px 5px; border-bottom:1px solid #EEE; }
#read .presIn { background-color:#F7F7F7; font-size:11px; font-weight:normal; }
#read .mssgIn p.from, #read .presIn p.from { padding:0px; margin:0px; font-size:13px; }
#read .mssgIn p.from { font-weight:bold; }
#read .mssgIn p.body { padding:0px; margin:0px; font-size:12px; }
#write { width:698px; border:1px solid #E7E7E7; background-color:#FFF; height:20px; padding:1px; font-size:13px; color:#AAA; display:none; }
</style>
<script type="text/javascript">
var boshchat = {
payloadHandler: function(payload) {
if(payload.jaxl == 'authFailed') {
jaxl.connected = false;
$('#button input').val('Connect');
}
else if(payload.jaxl == 'connected') {
jaxl.connected = true;
jaxl.jid = payload.jid;
$('#uname').css('display', 'none');
$('#passwd').css('display', 'none');
$('#button input').val('Disconnect');
$('#read').css('display', 'block');
$('#write').css('display', 'block');
obj = new Object;
obj['jaxl'] = 'getRosterList';
jaxl.sendPayload(obj);
}
else if(payload.jaxl == 'rosterList') {
obj = new Object;
obj['jaxl'] = 'setStatus';
jaxl.sendPayload(obj);
}
else if(payload.jaxl == 'disconnected') {
jaxl.connected = false;
jaxl.disconnecting = false;
$('#read').css('display', 'none');
$('#write').css('display', 'none');
$('#uname').css('display', 'block');
$('#passwd').css('display', 'block');
$('#button input').val('Connect');
console.log('disconnected');
}
else if(payload.jaxl == 'message') {
boshchat.appendMessage(jaxl.urldecode(payload.message));
jaxl.ping();
}
else if(payload.jaxl == 'presence') {
boshchat.appendMessage(jaxl.urldecode(payload.presence));
jaxl.ping();
}
else if(payload.jaxl == 'pinged') {
jaxl.ping();
}
},
appendMessage: function(message) {
$('#read').append(message);
$('#read').animate({ scrollTop: $('#read').attr('scrollHeight') }, 300);
},
prepareMessage: function(jid, message) {
html = '';
html += '<div class="mssgIn">';
html += '<p class="from">'+jid+'</p>';
html += '<p class="body">'+message+'</div>';
html += '</div>';
return html;
}
};
jQuery(function($) {
$(document).ready(function() {
jaxl.payloadHandler = new Array('boshchat', 'payloadHandler');
$('#button input').click(function() {
if($(this).val() == 'Connect') {
$(this).val('Connecting...');
// prepare connect object
obj = new Object;
obj['user'] = $('#uname input').val();
obj['pass'] = $('#passwd input').val();
jaxl.connect(obj);
}
else if($(this).val() == 'Disconnect') {
$(this).val('Disconnecting...');
jaxl.disconnect();
}
});
$('#write').focus(function() {
$(this).val('');
$(this).css('color', '#444');
});
$('#write').blur(function() {
if($(this).val() == '') $(this).val('Type your message');
$(this).css('color', '#AAA');
});
$('#write').keydown(function(e) {
if(e.keyCode == 13 && jaxl.connected) {
message = $.trim($(this).val());
if(message.length == 0) return false;
$(this).val('');
boshchat.appendMessage(boshchat.prepareMessage(jaxl.jid, message));
obj = new Object;
obj['jaxl'] = 'message';
obj['message'] = message;
jaxl.sendPayload(obj);
}
});
});
});
</script>
</head>
<body>
<center>
<h1>Web Chat Application using Jaxl Library</h1>
<div id="uname">
<label>Username:</label>
<input type="text" value=""/>
</div>
<div id="passwd">
<label>Password:</label>
<input type="password" value=""/>
</div>
<div id="read"></div>
<input type="text" value="Type your message" id="write"></input>
<div id="button">
<label></label>
<input type="button" value="Connect"/>
</div>
</center>
</body>
</html>
diff --git a/xep/jaxl.0124.php b/xep/jaxl.0124.php
index ba40187..01380c7 100644
--- a/xep/jaxl.0124.php
+++ b/xep/jaxl.0124.php
@@ -1,265 +1,266 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0124: Bosh Implementation
* Maintain various attributes like rid, sid across requests
*/
class JAXL0124 {
private static $buffer = array();
private static $sess = false;
public static function init($jaxl) {
// initialize working parameters for this jaxl instance
$jaxl->bosh = array(
'host' => 'localhost',
'port' => 5280,
'suffix'=> 'http-bind',
'out' => true,
'outheaders' => 'Content-type: application/json',
'cookie'=> array(
'ttl' => 3600,
'path' => '/',
'domain'=> false,
'https' => false,
'httponly' => true
),
'hold' => '1',
'wait' => '30',
'polling' => '0',
'version' => '1.6',
'xmppversion' => '1.0',
'secure'=> true,
'content' => 'text/xml; charset=utf-8',
'headers' => array('Accept-Encoding: gzip, deflate','Content-Type: text/xml; charset=utf-8'),
'xmlns' => 'http://jabber.org/protocol/httpbind',
'xmlnsxmpp' => 'urn:xmpp:xbosh',
'url' => 'http://localhost:5280/http-bind',
'session' => true
);
// parse user options
$jaxl->bosh['host'] = $jaxl->getConfigByPriority(@$jaxl->config['boshHost'], "JAXL_BOSH_HOST", $jaxl->bosh['host']);
$jaxl->bosh['port'] = $jaxl->getConfigByPriority(@$jaxl->config['boshPort'], "JAXL_BOSH_PORT", $jaxl->bosh['port']);
$jaxl->bosh['suffix'] = $jaxl->getConfigByPriority(@$jaxl->config['boshSuffix'], "JAXL_BOSH_SUFFIX", $jaxl->bosh['suffix']);
$jaxl->bosh['out'] = $jaxl->getConfigByPriority(@$jaxl->config['boshOut'], "JAXL_BOSH_OUT", $jaxl->bosh['out']);
$jaxl->bosh['session'] = $jaxl->getConfigByPriority(@$jaxl->config['boshSession'], "JAXL_BOSH_SESSION", $jaxl->bosh['session']);
$jaxl->bosh['url'] = "http://".$jaxl->bosh['host'].":".$jaxl->bosh['port']."/".$jaxl->bosh['suffix']."/";
// cookie params
$jaxl->bosh['cookie']['ttl'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieTTL'], "JAXL_BOSH_COOKIE_TTL", $jaxl->bosh['cookie']['ttl']);
$jaxl->bosh['cookie']['path'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookiePath'], "JAXL_BOSH_COOKIE_PATH", $jaxl->bosh['cookie']['path']);
$jaxl->bosh['cookie']['domain'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieDomain'], "JAXL_BOSH_COOKIE_DOMAIN", $jaxl->bosh['cookie']['domain']);
$jaxl->bosh['cookie']['https'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieHTTPS'], "JAXL_BOSH_COOKIE_HTTPS", $jaxl->bosh['cookie']['https']);
$jaxl->bosh['cookie']['httponly'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieHTTPOnly'], "JAXL_BOSH_COOKIE_HTTP_ONLY", $jaxl->bosh['cookie']['httponly']);
// start session
self::startSession($jaxl);
$jaxl->addPlugin('jaxl_post_bind', array('JAXL0124', 'postBind'));
$jaxl->addPlugin('jaxl_send_xml', array('JAXL0124', 'wrapBody'));
$jaxl->addPlugin('jaxl_pre_handler', array('JAXL0124', 'preHandler'));
$jaxl->addPlugin('jaxl_post_handler', array('JAXL0124', 'postHandler'));
$jaxl->addPlugin('jaxl_send_body', array('JAXL0124', 'sendBody'));
self::loadSession($jaxl);
}
public static function startSession($jaxl) {
if(!$jaxl->bosh['session']) {
$jaxl->log("[[JAXL0124]] Not starting session as forced by constructor config", 5);
return;
}
session_set_cookie_params(
$jaxl->bosh['cookie']['ttl'],
$jaxl->bosh['cookie']['path'],
$jaxl->bosh['cookie']['domain'],
$jaxl->bosh['cookie']['https'],
$jaxl->bosh['cookie']['httponly']
);
session_start();
}
public static function postHandler($payload, $jaxl) {
if(!$jaxl->bosh['out']) return $payload;
$payload = json_encode(self::$buffer);
$jaxl->log("[[BoshOut]]\n".$payload, 5);
header($jaxl->bosh['outheaders']);
echo $payload;
exit;
}
public static function postBind($payload, $jaxl) {
$jaxl->bosh['jid'] = $jaxl->jid;
$_SESSION['jaxl_auth'] = true;
return;
}
public static function out($payload) {
self::$buffer[] = $payload;
}
public static function loadSession($jaxl) {
$jaxl->bosh['rid'] = isset($_SESSION['jaxl_rid']) ? (string) $_SESSION['jaxl_rid'] : rand(1000, 10000);
$jaxl->bosh['sid'] = isset($_SESSION['jaxl_sid']) ? (string) $_SESSION['jaxl_sid'] : false;
$jaxl->lastid = isset($_SESSION['jaxl_id']) ? $_SESSION['jaxl_id'] : $jaxl->lastid;
$jaxl->jid = isset($_SESSION['jaxl_jid']) ? $_SESSION['jaxl_jid'] : $jaxl->jid;
- $jaxl->log("Loading session data\n".json_encode($_SESSION), 5);
+ $jaxl->log("[[JAXL0124]] Loading session data\n".json_encode($_SESSION), 5);
}
public static function saveSession($xml, $jaxl) {
if($_SESSION['jaxl_auth'] === true) {
$_SESSION['jaxl_rid'] = isset($jaxl->bosh['rid']) ? $jaxl->bosh['rid'] : false;
$_SESSION['jaxl_sid'] = isset($jaxl->bosh['sid']) ? $jaxl->bosh['sid'] : false;
$_SESSION['jaxl_jid'] = $jaxl->jid;
$_SESSION['jaxl_id'] = $jaxl->lastid;
if($jaxl->bosh['out'] && $jaxl->bosh['session']) {
- $jaxl->log("[[JAXL0124]] Not closing session as forced by constructor config", 5);
session_write_close();
}
if(self::$sess && $jaxl->bosh['out']) {
list($body, $xml) = self::unwrapBody($xml);
- $jaxl->log("[[".$_REQUEST['jaxl']."]] Auth complete, sync now\n".json_encode($_SESSION), 5);
+ $jaxl->log("[[JAXL0124]] Auth complete, sync now\n".json_encode($_SESSION), 5);
return self::out(array('jaxl'=>'jaxl', 'xml'=>urlencode($xml)));
}
else {
self::$sess = true;
- $jaxl->log("[[".$_REQUEST['jaxl']."]] Auth complete, commiting session now\n".json_encode($_SESSION), 5);
+ $jaxl->log("[[JAXL0124]] Auth complete, commiting session now\n".json_encode($_SESSION), 5);
}
}
else {
- $jaxl->log("[[".$_REQUEST['jaxl']."]] Not authed yet, Not commiting session\n".json_encode($_SESSION), 5);
+ $jaxl->log("[[JAXL0124]] Not authed yet, Not commiting session\n".json_encode($_SESSION), 5);
}
return $xml;
}
public static function wrapBody($xml, $jaxl) {
$body = trim($xml);
if(substr($body, 1, 4) != 'body') {
$body = '';
$body .= '<body rid="'.++$jaxl->bosh['rid'].'"';
$body .= ' sid="'.$jaxl->bosh['sid'].'"';
$body .= ' xmlns="http://jabber.org/protocol/httpbind">';
$body .= $xml;
$body .= "</body>";
$_SESSION['jaxl_rid'] = $jaxl->bosh['rid'];
}
return $body;
}
public static function sendBody($xml, $jaxl) {
$xml = self::saveSession($xml, $jaxl);
if($xml != false) {
$jaxl->log("[[XMPPSend]] body\n".$xml, 4);
$payload = JAXLUtil::curl($jaxl->bosh['url'], 'POST', $jaxl->bosh['headers'], $xml);
// curl error handling
if($payload['errno'] != 0) {
$log = "[[JAXL0124]] Curl errno ".$payload['errno']." encountered";
switch($payload['errno']) {
case 7:
$log .= ". Failed to connect with ".$jaxl->bosh['url'];
break;
case 52:
$log .= ". Empty response rcvd from bosh endpoint";
break;
default:
break;
}
- $jaxl->log($log);
+
+ JAXLPlugin::execute('jaxl_get_bosh_curl_error', $payload, $jaxl);
+ $jaxl->log($log);
}
$payload = $payload['content'];
$jaxl->handler($payload);
}
return $xml;
}
public static function unwrapBody($payload) {
if(substr($payload, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $payload, $m);
else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $payload, $m);
if(isset($m[1][0])) $body = "<body ".$m[1][0].">";
else $body = "<body>";
if(isset($m[2][0])) $payload = $m[2][0];
else $payload = '';
return array($body, $payload);
}
public static function preHandler($payload, $jaxl) {
if(substr($payload, 1, 4) == "body") {
list($body, $payload) = self::unwrapBody($payload);
if($payload == '') {
if($_SESSION['jaxl_auth'] === 'disconnect') {
$_SESSION['jaxl_auth'] = false;
JAXLPlugin::execute('jaxl_post_disconnect', $body, $jaxl);
}
else {
JAXLPlugin::execute('jaxl_get_empty_body', $body, $jaxl);
}
}
if($_SESSION['jaxl_auth'] === 'connect') {
$arr = $jaxl->xml->xmlize($body);
if(isset($arr["body"]["@"]["sid"])) {
$_SESSION['jaxl_auth'] = false;
$_SESSION['jaxl_sid'] = $arr["body"]["@"]["sid"];
$jaxl->bosh['sid'] = $arr["body"]["@"]["sid"];
$jaxl->log("[[JAXL0124]] Updated session to ".json_encode($_SESSION), 5);
}
}
}
return $payload;
}
}
?>
diff --git a/xep/jaxl.0206.php b/xep/jaxl.0206.php
index 46275ee..64eaba7 100644
--- a/xep/jaxl.0206.php
+++ b/xep/jaxl.0206.php
@@ -1,129 +1,129 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0206: XMPP over BOSH
*
* Uses XEP-0124 to wrap XMPP stanza's inside <body/> wrapper
*/
class JAXL0206 {
public static function init($jaxl) {
$jaxl->log("[[JaxlAction]] ".$_REQUEST['jaxl']."\n".json_encode($_REQUEST), 5);
// Requires Bosh Session Manager
$jaxl->requires('JAXL0124');
}
public static function jaxl($jaxl, $xml) {
$jaxl->sendXML(urldecode($xml));
}
public static function startStream($jaxl) {
$_SESSION['jaxl_auth'] = 'connect';
$xml = "";
$xml .= "<body";
$xml .= " content='".$jaxl->bosh['content']."'";
$xml .= " hold='".$jaxl->bosh['hold']."'";
$xml .= " xmlns='".$jaxl->bosh['xmlns']."'";
$xml .= " wait='".$jaxl->bosh['wait']."'";
$xml .= " rid='".++$jaxl->bosh['rid']."'";
$xml .= " version='".$jaxl->bosh['version']."'";
$xml .= " polling='".$jaxl->bosh['polling']."'";
$xml .= " secure='".$jaxl->bosh['secure']."'";
$xml .= " xmlns:xmpp='".$jaxl->bosh['xmlnsxmpp']."'";
$xml .= " to='".$jaxl->domain."'";
$xml .= " route='xmpp:".$jaxl->host.":".$jaxl->port."'";
$xml .= " xmpp:version='".$jaxl->bosh['xmppversion']."'/>";
$jaxl->sendXML($xml);
}
public static function endStream($jaxl) {
- $_SESSION['auth'] = 'disconnect';
+ $_SESSION['jaxl_auth'] = 'disconnect';
$xml = "";
$xml .= "<body";
$xml .= " rid='".++$jaxl->bosh['rid']."'";
$xml .= " sid='".$jaxl->bosh['sid']."'";
$xml .= " type='terminate'";
$xml .= " xmlns='".$jaxl->bosh['xmlns']."'>";
$xml .= "<presence type='unavailable' xmlns='jabber:client'/>";
$xml .= "</body>";
$jaxl->sendXML($xml);
}
public static function restartStream($jaxl) {
$xml = "";
$xml .= "<body";
$xml .= " rid='".++$jaxl->bosh['rid']."'";
$xml .= " sid='".$jaxl->bosh['sid']."'";
$xml .= " xmlns='".$jaxl->bosh['xmlns']."'";
$xml .= " to='".$jaxl->host."'";
$xml .= " xmpp:restart='true'";
$xml .= " xmlns:xmpp='".$jaxl->bosh['xmlnsxmpp']."'/>";
- $_SESSION['auth'] = false;
+ $_SESSION['jaxl_auth'] = false;
$jaxl->sendXML($xml);
}
public static function ping($jaxl) {
$xml = '';
$xml .= '<body rid="'.++$jaxl->bosh['rid'].'"';
$xml .= ' sid="'.$jaxl->bosh['sid'].'"';
$xml .= ' xmlns="http://jabber.org/protocol/httpbind"/>';
- $_SESSION['auth'] = true;
+ $_SESSION['jaxl_auth'] = true;
$jaxl->sendXML($xml);
}
public static function out($jaxl, $payload) {
JAXL0124::out($payload);
}
}
?>
|
jaxl/JAXL | fafcbfc7eda19e586ff699a7e7c8d7750ace98a1 | PHP CMS looking to integrate Jaxl in their core can now force disable auto start of php session by Jaxl core. Simple pass 'boshSession' as false with jaxl constructor config array | diff --git a/CHANGELOG b/CHANGELOG
index 58d100b..c573da5 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,304 +1,306 @@
version 2.1.2
-------------
+- PHP CMS looking to integrate Jaxl in their core can now force disable auto start of php session by Jaxl core
+ Simple pass 'boshSession' as false with jaxl constructor config array
- Entire Jaxl core including xmpp/, xep/ and core/ class files now make use of JAXL::addPlugin instead of JAXLPlugin to register per instance callbacks
- JAXLPlugin can now register a callback for a dedicated jaxl instance in a multi-instance jaxl application
Class functionality remains backward compatible.
- JAXLog class now also dump connect instance uid per log line
- XMPP instance iq id now defaults to a random value between 1 and 9
Also added jaxl_get_id event hook for apps to customize iq id for the connected Jaxl instance
Also as compared to default numeric iq id, Jaxl core now uses hex iq id's
- Every jaxl instance per php process id now generate it's own unique id JAXL::$uid
- Jaxl core doesn't go for a session if it's optional as indicated by the xmpp server
- Fixed boshChat postBind issues as reported by issue#26 (http://code.google.com/p/jaxl/issues/detail?id=26)
- Fixed jaxl constructor config read warning and XEP 0114 now make use of JAXL::getConfigByPriority method
- Removed warning while reading user config inside Jaxl constructor
Upgraded Jaxl Parser class which was malfunctioning on CentOS PHP 5.1.6 (cli)
- Added bosh error response handling and appropriate logging inside XMPP over Bosh core files
- Code cleanup inside jaxl logger class.
Fixed getConfigByPriority method which was malfunctioning in specific cases
- JAXLog class now using inbuild php function (error_log)
- Checking in first version of XEP-0016 (Privacy Lists), XEP-0055 (Jabber Search), XEP-0077 (In-Band Registration), XEP-0144 (Roster Item Exchange), XEP-0153 (vCard-Based Avatars), XEP-0237 (Roster Versioning)
- On auth faliure core doesn't throw exception since XMPP over Bosh apps are not held inside a try catch block (a better fix may be possible in future)
- XMPP over BOSH xep wasn't passing back Jaxl instance obj for jaxl_post_disconnect hook, fixed that for clean disconnect
- Jaxl core attempts to create log and pid files if doesn't already exists
Also instead of die() core throws relevant exception message wherever required
XMPP base classes throws relevant exception with message wherever required
- First commit of JAXLException class. JAXL core now uses JAXLException
- Jaxl constructor dies if logPath, pidPath and tmpPath doesn't exists on the system
- Core updates JAXL::resource after successful binding to match resource assigned by the connecting server
- Updated echobot sample example to make use of autoSubscribe core feature
Also registers callback for jaxl_post_subscription_request and jaxl_post_subscription_accept hooks
- Updated echobot and boshchat application to use in memory roster cache maintained by Jaxl core.
App files should register callback on hook jaxl_post_roster_update to get notified everytime local roster cache is updated
- Added provision for local roster cache management inside Jaxl core.
Retrived roster lists are cached in memory (see updated echobot.php sample example).
Also added provision for presence tracking (JAXL::trackPresence).
If enabled Jaxl core keep a track of jid availability and update local roster cache accordingly.
Also added provision for auto-accept subscription (JAXL::autoSubscribe).
- Removed XMPP::isConnected variable which used to tell status of connected socket stream.
This is equivalent to checking XMPP:stream variable for true/false
- Added a (kind of) buggy support for '/xml()' inside parser xpath
- If Jaxl instance has being configured for auto periodic ping (XEP-0199), pings are holded till auth completion.
Also if server responds 'feature-not-implemented' for first ping XEP-0199 automatically deleted periodic ping cron tab
- Corrected handling of error type iq stanza's (removed jaxl_get_iq_error hook)
- Added iq error code xpath inside JAXLXml class
- Completed missing JAXLCron::delete method for removing a previously registered cron tab
- Checking in first version of XEP-0049 (Private XML Storage) (not yet tested)
- Checking in first version of XEP-0191 (Simple Communication Blocking) (not yet tested)
- Added JAXL_PING_INTERVAL configuration option inside jaxl.ini
- XEP-0199 (XMPP Ping) can now automatically ping the connected server periodically for keeping connection alive on long running bots
(see echobot.php sample app for usage)
- Updated JAXLCron::add method to accept a number of arguments while adding bckgrnd jobs
These list of arguments is passed back to the application method
- Updated IQ handling inside XEP-0202 which wasn't returning iq stanza back resulting in no ping/pong
- Updated echobot to show usage of JAXL::discoItems and JAXL::discoInfo inside application code
- Added tagMap xpath for service identity and feature nodes in service discovery resultset
- JAXL core now auto includes XEP-0128 along with XEP-0030 on startup.
Also added two methods JAXL::discoItems and JAXL::discoInfo for service discovery
- Checking in first version of XEP-0128 (Service Discovery Extension)
- Fixed bug where message and presence stanza builder were not using passed id value as attribute
- Removed jaxl_pre_curl event hook which was only used internally by XEP-0124
- Jaxl now shutdown gracefully is encryption is required and openssl PHP module is not loaded in the environment
- For every registered callback on XMPP hooks, callback'd method will receive two params.
A payload and reference of Jaxl instance for whom XMPP event has occured.
Updated sample application code to use passed back Jaxl instance reference instead of global jaxl variable.
- As a library convention XEP's exposing user space configuration parameters via JAXL constructor SHOULD utilize JAXL::getConfigByPriority method
Added JAXL_TMP_PATH option inside jaxl.ini
- Jaxl::tmp is now Jaxl::tmpPath. Also added Jaxl config param to specify custom tmp path location
Jaxl client also self detect the IP of the host it is running upon (to be used by STUN/TURN utilities in Jingle negotitation)
- Removed JAXLUtil::includePath and JAXLUtil::getAppFilePath methods which are now redundant after removing jaxl.ini and jaxl.conf from lib core
- Removed global defines JAXL_BASE_PATH, JAXL_APP_BASE_PATH, JAXL_BOSH_APP_ABS_PATH from inside jaxl.ini (No more required by apps to specify these values)
- Removing env/jaxl.php and env/jaxl.conf (were required if you run your apps using `jaxl` command line utility)
Updated env/jaxl.ini so that projects can now directly include their app setting via jaxl.ini (before including core/jaxl.class.php)
- Added JAXL::bareJid public variable for usage inside applications.
XMPP base class now return bool on socket connect completion (used by PHPUnit test cases)
- Removing build.sh file from library for next release
Users should simply download, extract, include and write their app code without caring about the build script from 2.1.2 release
- As a library convention to include XEP's use JAXL::requires() method, while to include any core/ or xmpp/ base class use jaxl_require() method.
Updated library code and xep's to adhere to this convention.
Jaxl instance now provide a system specific /tmp folder location accessible by JAXL::tmp
- Removed JAXL_NAME and JAXL_VERSION constants.
Instead const variables are now defined per instance accessible by getName() and getVersion() methods.
Updated XEP-0030,0092,0115 to use the same
- Moved indivisual XEP's working parameter (0114,0124) from JAXL core class to XEP classes itself.
XEP's make use of JAXL::config array for parsing user options.
- Added JAXL_COMPONENT_PASS option inside jaxl.ini. Updated build.sh with new /app file paths.
Updated XEP-0114,0124,0206 to use array style configs as defined inside JAXL class
- Removed dependency upon jaxl.ini from all sample applications.
First checkin of sample sendMessage.php app.
- Config parameters for XEP's like 0114 and 0206 are now saved as an array inside JAXL class (later on they will be moved inside respective XEP's).
Added constructor config option to pre-choose an auth mechanism to be performed
if an auth mech is pre-chosen app files SHOULD not register callback for jaxl_get_auth_mech hook.
Bosh cookie settings can now be passed along with Jaxl constructor.
Added support for publishing vcard-temp:x:update node along with presence stanzas.
Jaxl instance can run in 3 modes a.k.a. stream,component and bosh mode
applications should use JAXL::startCore('mode') to configure instance for a specific mode.
- Removed redundant NS variable from inside XEP-0124
- Moved JAXLHTTPd setting defines inside the class (if gone missing CPU usage peaks to 100%)
- Added jaxl_httpd_pre_shutdown, jaxl_httpd_get_http_request, jaxl_httpd_get_sock_request event hooks inside JAXLHTTPd class
- Added JAXLS5B path (SOCKS5 implementation) inside jaxl_require method
- Removed all occurance of JAXL::$action variable from /core and /xep class files
- Updated boshChat and boshMUChat sample application which no longer user JAXL::$action variable inside application code
- Updated preFetchBOSH and preFetchXMPP sample example.
Application code don't need any JAXL::$action variable now
Neither application code need to define JAXL_BASE_PATH (optional from now on)
- JAXL core and XEP-0206 have no relation and dependency upon JAXL::$action variable now.
- Deprecated jaxl_get_body hook which was only for XEP-0124 working.
Also cleaned up XEP-0124 code by removing processBody method which is now handled inside preHandler itself.
- Defining JAXL_BASE_PATH inside application code made optional.
Developers can directly include /path/to/jaxl/core/jaxl.class.php and start writing applications.
Also added a JAXL::startCore() method (see usage in /app/preFetchXMPP.php).
Jaxl magic method for calling XEP methods now logs a warning inside jaxl.log if XEP doesn't exists in the environment
- Added tag map for XMPP message thread and subject child elements
- Fixed typo where in case of streamError proper description namespace was not parsed/displayed
- Disabled BOSH session close if application is running in boshOut=false mode
Suggested by MOVIM dev team who were experiencing loss of session data on end of script
- JAXL::log method 2nd parameter now defaults to logLevel=1 (passing 2nd param is now optional)
- Fixed XPath for iq stanza error condition and error NS extraction inside jaxl.parser.class
- First checkin of XEP-0184 Message Receipts
- Added support for usage of name() xpath function inside tag maps of JAXLXml class.
Also added some documentation for methods available inside JAXLXml class
- Fixed JAXLPlugin::remove method to properly remove and manage callback registry.
Also added some documentation for JAXLPlugin class methods
- Added JAXL contructor config option to disable BOSH module auto-output behaviour.
This is utilized inside app/preFetchBOSH.php sample example
- First checkin of sample application code pre-fetching XMPP/Jabber data for web page population using BOSH XEP
- Added a sample application file which can be used to pre-fetch XMPP/Jabber data for a webpage without using BOSH XEP or Ajax requests
As per the discussion on google groups (http://bit.ly/aKavZB) with MOVIM team
- JAXL library is now $jaxl independent, you can use anything like $var = new JAXL(); instance your applications now
JAXLUtil::encryptPassword now accepts username/password during SASL auth.
Previously it used to auto detect the same from JAXL instance, now core has to manually pass these param
- Added JAXL::startHTTPd method with appropriate docblock on how to convert Jaxl instance into a Jaxl socket (web) server.
Comments also explains how to still maintaining XMPP communication in the background
- Updated JAXLHTTPd class to use new constants inside jaxl.ini
- Added jaxl_get_stream_error event handler.
Registered callback methods also receive array form of received XMPP XML stanza
- Connecting Jaxl instance now fallback to default value 'localhost' for host,domain,boshHost,boshPort,boshSuffix
If these values are not configured either using jaxl.ini constants or constructor
- Provided a sendIQ method per JAXL instance.
Recommended that applications and XEP's should directly use this method for sending <iq/> type stanza
DONOT use XMPPSend methods inside your application code from here on
- Added configuration options for JAXL HTTPd server and JAXL Bosh Component Manager inside jaxl.ini
- Fixed type in XEP-0202 (Entity Time). XEP was not sending <iq/> id in response to get request
- Jaxl library is now phpdocs ready. Added extended documentation for JAXL core class, rest to be added
- All core classes inside core/, xmpp/ and xep/ folder now make use of jaxl->log method
JAXL Core constructor are now well prepared so that inclusion of jaxl.ini is now optional
Application code too should use jaxl->log instead of JAXLog::log method for logging purpose
- Reshuffled core instance paramaters between JAXL and XMPP class
Also Jaxl core now logs at level 1 instead of 0 (i.e. all logs goes inside jaxl.log and not on console)
- JAXL class now make use of endStream method inside XMPP base class while disconnecting.
Also XMPPSend::endStream now forces xmpp stanza delivery (escaping JAXL internal buffer)
http://code.google.com/p/jaxl/issues/detail?id=23
- Added endStream method inside XMPP base class and startSession,startBind methods inside XMPPSend class
XMPP::sendXML now accepts a $force parameter for escaping XMPP stanza's from JAXL internal buffer
- Updated the way Jaxl core calls XEP 0115 method (entity caps) to match documentation
XEP method's should accept jaxl instance as first paramater
- First checkin of PEP (Personal Eventing), User Location, User Mood, User Activity and User Tune XEP's
- Completed methods discoFeatures, discoNodes, discoNodeInfo, discoNodeMeta and discoNodeItems in PubSub XEP
- Hardcoded client category, type, lang and name. TODO: Make them configurable in future
- Cleaned up XEP 0030 (Service Discovery) and XEP 0115 (Entity Capabilities)
- Updated XMPP base class to use performance configuration parameters (now customizable with JAXL constructor)
- jaxl.conf will be removed from jaxl core in future, 1st step towards this goal
- Moved bulk of core configs from jaxl.conf
- Added more configuration options relating to client performance e.g. getPkts, getPktSize etc
- Fixed client mode by detecting sapi type instead of $_REQUEST['jaxl'] variable
- Now every implemented XEP should have an 'init' method which will accept only one parameter (jaxl instance itself)
- Jaxl core now converts transmitted stanza's into xmlentities (http://code.google.com/p/jaxl/issues/detail?id=22)
- Created a top level 'patch' folder which contains various patches sent by developers using 'git diff > patch' utility
- Fixed typo in namespace inside 0030 (thanks to Thomas Baquet for the patch)
- First checkin of PubSub XEP (untested)
- Indented build.sh and moved define's from top of JAXLHTTPd class to jaxl.ini
- Added JAXLHTTPd inside Jaxl core (a simple socket select server)
- Fixed sync of background iq and other stanza requests with browser ajax calls
- Updated left out methods in XMPP over BOSH xep to accept jaxl instance as first method
- All XEP methods available in application landspace, now accepts jaxl instance as first parameter. Updated core jaxl class magic method to handle the same.
If you are calling XEP methods as specified in the documentation, this change will not hurt your running applications
- Updated echobot sample application to utilize XEP 0054 (VCard Temp) and 0202 (Entity Time)
- First checkin of missing vcard-temp xep
- Added xmlentities JAXLUtil method
- Jaxl Parser now default parses xXmlns node for message stanzas
- Added PCRE_DOTALL and PCRE_MULTILINE pattern modifier for bosh unwrapBody method
- Added utility methods like urldecode, urlencode, htmlEntities, stripHTML and splitJid inside jaxl.js
- Updated sample application jaxl.ini to reflect changes in env/jaxl.ini
version 2.1.1
-------------
- Updated XMPPSend 'presence', 'message' and 'iq' methods to accept $jaxl instance as first parameter
if you are not calling these methods directly from your application code as mentioned in documentation
this change should not hurt you
- Added more comments to env/jaxl.ini and also added JAXL_LOG_ROTATE ini file option
- JAXL instance logs can be rotated every x seconds (logRotate config parameter) now
- Removed config param dumpTime, instead use dumpStat to specify stats dump period
- Base XMPP class now auto-flush output buffers filled because of library level rate limiter
- Added more options for JAXL constructor e.g.
boshHost, boshPort, boshSuffix, pidPath, logPath, logLevel, dumpStat, dumpTime
These param overwrites value specified inside jaxl.ini file
Also JAXL core will now periodically dump instance statistics
- Added an option in JAXL constructor to disable inbuild core rate limiter
- Added support when applications need to connect with external bosh endpoints
Bosh application code requires update for ->JAXL0206('startStream') method
- XMPPGet::handler replaces ->handler inside XEP-0124
- JAXLCron job now also passes connected instance to callback cron methods
- Updated base XMPP class now maintains a clock, updated sendXML method to respect library level rate limiting
- Base JAXL class now includes JAXLCron class for periodically dumping connected bot memory/usage stats
- First version of JAXLCron class for adding periodic jobs in the background
- XMPP payload handler moves from XMPPGet to base XMPP class, packets are then routed to XMPPGet class for further processing
- Updated xep-0124 to use instance bosh parameters instead of values defined inside jaxl.ini
- Provision to specify custom JAXL_BOSH_HOST inside jaxl.ini
- Instead of global logLevel and logPath, logger class now respects indivisual instance log settings
Helpful in multiple instance applications
- Updated base JAXL class to accept various other configuration parameters inside constructor
These param overwrites values defined inside jaxl.ini
- XMPPSend::xml method moves inside XMPP::sendXML (call using ->sendXML from within application code), as a part of library core cleanup
- Updated jaxl class to return back payload from called xep methods
- XMPP base method getXML can be instructed not to take a nap between stream reads
- Added jaxl_get_xml hook for taking control over incoming xml payload from xmpp stream
- Added support for disabling sig term registration, required by applications who already handle this in their core code
- Added capability of sending multiple message/presence stanza in one go inside jaxl base class
- Fixed typo in MUC Direct Invitation xep invite method
- getHandler should have accepted core instance by reference, fixed now. BOSH MUC Chat sample application header is now more appropriate
version 2.1.0
-------------
- First checkin of bosh MUC sample application
- Updated build file now packages bosh MUC chat sample application along with core classes
- Updated JAXLog class to accept instance inside log() method, application code should use ->log() to call JAXLog::log() method now
- Updated JAXLPlugin class to pass instance along with every XMPP event hook
- Updated jaxl_require method to call including XEP's init() method every time they are included using jaxl_require method
- Update jaxl.ini with some documentation/comments about JAXL_BOSH_COOKIE_DOMAIN parameter
- Updated echobot sample application code to pass instance while calling jaxl_require method
- Update XMPP SASL Auth class to accept instance while calculating SASL response.
Also passinginstance when jaxl_get_facebook_key hook is called
- Updated XMPP base class to accept component host name inside constructor.
Sending currentinstance with every XMPPSend, XMPPGet and JAXLog method calls
- Every XMPPGet method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Every XMPPSend method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Updated component bot sample application to show how to pass component host inside JAXL constructor.
Also updated jaxl_require call to accept current working instance
- Updated boshchat sample application to follow new rules of jaxl_require, also cleaned up the sample app code a bit
- Updated jaxl.ini of packaged sample applications to match /env/jaxl.ini
- Updated implemented XEP's init method to accept instance during initialization step
Send working instance with every XMPPSend method call
Almost every XEP's available method now accepts an additional instance so that XEP's can work independently for every instance inside a multiple jaxl instance application code
- Added magic method __call inside JAXL class
All application codes should now call a methods inside implemented XEP's like ->JAXLxxxx('method', , , ...)
Also added ->log method to be used by application codes
JAXLog::log() should not be called directly from application code
Updated XMPPSend methods to accept instance
Added ->requires() method that does a similar job as jaxl_require() which now also expects instance as one of the passed parameter.
version 2.0.4
-------------
- Updated XMPP base class and XMPP Get class to utilize new XMPPAuth class
- Updated jaxl_require method with new XMPPAuth class path
- Extracted XMPP SASL auth mechanism out of XMPP Get class, code cleanup
- unwrapBody method of XEP 0124 is now public
- Added #News block on top of README
- No more capital true, false, null inside Jaxl core to pass PHP_CodeSniffer tests
- :retab Jaxl library core to pass PHP_CodeSniffer tests
- Added Jabber Component Protocol example application bot
- Updated README with documentation link for Jabber component protocol
- Updated Entity Caps method to use list of passed feature list for verification code generation
- Updated MUC available methods doc link inside README
- Added experimental support for SCRAM-SHA-1, CRAM-MD5 and LOGIN auth mechanisms
version 2.0.3
-------------
- Updated Jaxl XML parsing class to handle multiple level nested child cases
- Updated README and bosh chat application with documentation link
- Fixed bosh application to run on localhost
- Added doc links inside echobot sample app
- Bosh sample application also use entity time XEP-0202 now
- Fix for sapi detection inside jaxl util
- jaxl.js updated to handle multiple ajax poll response payloads
- Bosh session manager now dumps ajax poll response on post handler callback
- Removed hardcoded ajax poll url inside boshchat application
- Updated component protocol XEP pre handshake event handling
version 2.0.2
-------------
- Packaged XEP 0202 (Entity Time)
- First checkin of Bosh related XEP 0124 and 0206
- Sample Bosh Chat example application
- Updated jaxl.class.php to save Bosh request action parameter
- jaxl.ini updated with Bosh related cookie options, default loglevel now set to 4
- jaxl.js checkin which should be used with bosh applications
- Updated base xmpp classes to provide integrated bosh support
- Outgoing presence and message stanza's too can include @id attribute now
version 2.0.1
-------------
- Typo fix in JAXLXml::$tagMap for errorCode
- Fix for handling overflooded roster list
- Packaged XEP 0115 (Entity capability) and XEP 0199 (XMPP Ping)
- Updated sample echobot to use XEP 0115 and XEP 0199
- Support for X-FACEBOOK-PLATFORM authentication
version 2.0.0
--------------
First checkin of:
- Restructed core library with event mechanism
- Packaged XEP 0004, 0030, 0045, 0050, 0085, 0092, 0114, 0133, 0249
- Sample echobot application
diff --git a/xep/jaxl.0124.php b/xep/jaxl.0124.php
index 6231de9..ba40187 100644
--- a/xep/jaxl.0124.php
+++ b/xep/jaxl.0124.php
@@ -1,254 +1,265 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0124: Bosh Implementation
* Maintain various attributes like rid, sid across requests
*/
class JAXL0124 {
private static $buffer = array();
private static $sess = false;
public static function init($jaxl) {
// initialize working parameters for this jaxl instance
$jaxl->bosh = array(
'host' => 'localhost',
'port' => 5280,
'suffix'=> 'http-bind',
'out' => true,
'outheaders' => 'Content-type: application/json',
'cookie'=> array(
'ttl' => 3600,
'path' => '/',
'domain'=> false,
'https' => false,
'httponly' => true
),
'hold' => '1',
'wait' => '30',
'polling' => '0',
'version' => '1.6',
'xmppversion' => '1.0',
'secure'=> true,
'content' => 'text/xml; charset=utf-8',
'headers' => array('Accept-Encoding: gzip, deflate','Content-Type: text/xml; charset=utf-8'),
'xmlns' => 'http://jabber.org/protocol/httpbind',
'xmlnsxmpp' => 'urn:xmpp:xbosh',
- 'url' => 'http://localhost:5280/http-bind'
+ 'url' => 'http://localhost:5280/http-bind',
+ 'session' => true
);
// parse user options
$jaxl->bosh['host'] = $jaxl->getConfigByPriority(@$jaxl->config['boshHost'], "JAXL_BOSH_HOST", $jaxl->bosh['host']);
$jaxl->bosh['port'] = $jaxl->getConfigByPriority(@$jaxl->config['boshPort'], "JAXL_BOSH_PORT", $jaxl->bosh['port']);
$jaxl->bosh['suffix'] = $jaxl->getConfigByPriority(@$jaxl->config['boshSuffix'], "JAXL_BOSH_SUFFIX", $jaxl->bosh['suffix']);
$jaxl->bosh['out'] = $jaxl->getConfigByPriority(@$jaxl->config['boshOut'], "JAXL_BOSH_OUT", $jaxl->bosh['out']);
+ $jaxl->bosh['session'] = $jaxl->getConfigByPriority(@$jaxl->config['boshSession'], "JAXL_BOSH_SESSION", $jaxl->bosh['session']);
$jaxl->bosh['url'] = "http://".$jaxl->bosh['host'].":".$jaxl->bosh['port']."/".$jaxl->bosh['suffix']."/";
-
+
// cookie params
$jaxl->bosh['cookie']['ttl'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieTTL'], "JAXL_BOSH_COOKIE_TTL", $jaxl->bosh['cookie']['ttl']);
$jaxl->bosh['cookie']['path'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookiePath'], "JAXL_BOSH_COOKIE_PATH", $jaxl->bosh['cookie']['path']);
$jaxl->bosh['cookie']['domain'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieDomain'], "JAXL_BOSH_COOKIE_DOMAIN", $jaxl->bosh['cookie']['domain']);
$jaxl->bosh['cookie']['https'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieHTTPS'], "JAXL_BOSH_COOKIE_HTTPS", $jaxl->bosh['cookie']['https']);
$jaxl->bosh['cookie']['httponly'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieHTTPOnly'], "JAXL_BOSH_COOKIE_HTTP_ONLY", $jaxl->bosh['cookie']['httponly']);
-
- session_set_cookie_params(
- $jaxl->bosh['cookie']['ttl'],
- $jaxl->bosh['cookie']['path'],
- $jaxl->bosh['cookie']['domain'],
- $jaxl->bosh['cookie']['https'],
- $jaxl->bosh['cookie']['httponly']
- );
- session_start();
+
+ // start session
+ self::startSession($jaxl);
$jaxl->addPlugin('jaxl_post_bind', array('JAXL0124', 'postBind'));
$jaxl->addPlugin('jaxl_send_xml', array('JAXL0124', 'wrapBody'));
$jaxl->addPlugin('jaxl_pre_handler', array('JAXL0124', 'preHandler'));
$jaxl->addPlugin('jaxl_post_handler', array('JAXL0124', 'postHandler'));
$jaxl->addPlugin('jaxl_send_body', array('JAXL0124', 'sendBody'));
self::loadSession($jaxl);
}
+
+ public static function startSession($jaxl) {
+ if(!$jaxl->bosh['session']) {
+ $jaxl->log("[[JAXL0124]] Not starting session as forced by constructor config", 5);
+ return;
+ }
+
+ session_set_cookie_params(
+ $jaxl->bosh['cookie']['ttl'],
+ $jaxl->bosh['cookie']['path'],
+ $jaxl->bosh['cookie']['domain'],
+ $jaxl->bosh['cookie']['https'],
+ $jaxl->bosh['cookie']['httponly']
+ );
+ session_start();
+ }
public static function postHandler($payload, $jaxl) {
if(!$jaxl->bosh['out']) return $payload;
-
$payload = json_encode(self::$buffer);
$jaxl->log("[[BoshOut]]\n".$payload, 5);
header($jaxl->bosh['outheaders']);
echo $payload;
exit;
}
public static function postBind($payload, $jaxl) {
$jaxl->bosh['jid'] = $jaxl->jid;
- $_SESSION['auth'] = true;
+ $_SESSION['jaxl_auth'] = true;
return;
}
public static function out($payload) {
self::$buffer[] = $payload;
}
public static function loadSession($jaxl) {
- $jaxl->bosh['rid'] = isset($_SESSION['rid']) ? (string) $_SESSION['rid'] : rand(1000, 10000);
- $jaxl->bosh['sid'] = isset($_SESSION['sid']) ? (string) $_SESSION['sid'] : false;
- $jaxl->lastid = isset($_SESSION['id']) ? $_SESSION['id'] : $jaxl->lastid;
- $jaxl->jid = isset($_SESSION['jid']) ? $_SESSION['jid'] : $jaxl->jid;
+ $jaxl->bosh['rid'] = isset($_SESSION['jaxl_rid']) ? (string) $_SESSION['jaxl_rid'] : rand(1000, 10000);
+ $jaxl->bosh['sid'] = isset($_SESSION['jaxl_sid']) ? (string) $_SESSION['jaxl_sid'] : false;
+ $jaxl->lastid = isset($_SESSION['jaxl_id']) ? $_SESSION['jaxl_id'] : $jaxl->lastid;
+ $jaxl->jid = isset($_SESSION['jaxl_jid']) ? $_SESSION['jaxl_jid'] : $jaxl->jid;
$jaxl->log("Loading session data\n".json_encode($_SESSION), 5);
}
public static function saveSession($xml, $jaxl) {
- if($_SESSION['auth'] === true) {
- $_SESSION['rid'] = isset($jaxl->bosh['rid']) ? $jaxl->bosh['rid'] : false;
- $_SESSION['sid'] = isset($jaxl->bosh['sid']) ? $jaxl->bosh['sid'] : false;
- $_SESSION['jid'] = $jaxl->jid;
- $_SESSION['id'] = $jaxl->lastid;
-
- if($jaxl->bosh['out'])
+ if($_SESSION['jaxl_auth'] === true) {
+ $_SESSION['jaxl_rid'] = isset($jaxl->bosh['rid']) ? $jaxl->bosh['rid'] : false;
+ $_SESSION['jaxl_sid'] = isset($jaxl->bosh['sid']) ? $jaxl->bosh['sid'] : false;
+ $_SESSION['jaxl_jid'] = $jaxl->jid;
+ $_SESSION['jaxl_id'] = $jaxl->lastid;
+
+ if($jaxl->bosh['out'] && $jaxl->bosh['session']) {
+ $jaxl->log("[[JAXL0124]] Not closing session as forced by constructor config", 5);
session_write_close();
+ }
if(self::$sess && $jaxl->bosh['out']) {
list($body, $xml) = self::unwrapBody($xml);
$jaxl->log("[[".$_REQUEST['jaxl']."]] Auth complete, sync now\n".json_encode($_SESSION), 5);
return self::out(array('jaxl'=>'jaxl', 'xml'=>urlencode($xml)));
}
else {
self::$sess = true;
$jaxl->log("[[".$_REQUEST['jaxl']."]] Auth complete, commiting session now\n".json_encode($_SESSION), 5);
}
}
else {
$jaxl->log("[[".$_REQUEST['jaxl']."]] Not authed yet, Not commiting session\n".json_encode($_SESSION), 5);
}
return $xml;
}
public static function wrapBody($xml, $jaxl) {
$body = trim($xml);
-
if(substr($body, 1, 4) != 'body') {
$body = '';
$body .= '<body rid="'.++$jaxl->bosh['rid'].'"';
$body .= ' sid="'.$jaxl->bosh['sid'].'"';
$body .= ' xmlns="http://jabber.org/protocol/httpbind">';
$body .= $xml;
$body .= "</body>";
-
- $_SESSION['rid'] = $jaxl->bosh['rid'];
+ $_SESSION['jaxl_rid'] = $jaxl->bosh['rid'];
}
-
return $body;
}
public static function sendBody($xml, $jaxl) {
$xml = self::saveSession($xml, $jaxl);
if($xml != false) {
$jaxl->log("[[XMPPSend]] body\n".$xml, 4);
$payload = JAXLUtil::curl($jaxl->bosh['url'], 'POST', $jaxl->bosh['headers'], $xml);
// curl error handling
if($payload['errno'] != 0) {
$log = "[[JAXL0124]] Curl errno ".$payload['errno']." encountered";
switch($payload['errno']) {
case 7:
$log .= ". Failed to connect with ".$jaxl->bosh['url'];
break;
case 52:
$log .= ". Empty response rcvd from bosh endpoint";
break;
default:
break;
}
- $jaxl->log($log);
+ $jaxl->log($log);
}
$payload = $payload['content'];
$jaxl->handler($payload);
}
return $xml;
}
public static function unwrapBody($payload) {
if(substr($payload, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $payload, $m);
else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $payload, $m);
if(isset($m[1][0])) $body = "<body ".$m[1][0].">";
else $body = "<body>";
if(isset($m[2][0])) $payload = $m[2][0];
else $payload = '';
return array($body, $payload);
}
public static function preHandler($payload, $jaxl) {
if(substr($payload, 1, 4) == "body") {
list($body, $payload) = self::unwrapBody($payload);
if($payload == '') {
- if($_SESSION['auth'] === 'disconnect') {
- $_SESSION['auth'] = false;
+ if($_SESSION['jaxl_auth'] === 'disconnect') {
+ $_SESSION['jaxl_auth'] = false;
JAXLPlugin::execute('jaxl_post_disconnect', $body, $jaxl);
}
else {
JAXLPlugin::execute('jaxl_get_empty_body', $body, $jaxl);
}
}
- if($_SESSION['auth'] === 'connect') {
+ if($_SESSION['jaxl_auth'] === 'connect') {
$arr = $jaxl->xml->xmlize($body);
if(isset($arr["body"]["@"]["sid"])) {
- $_SESSION['auth'] = false;
- $_SESSION['sid'] = $arr["body"]["@"]["sid"];
+ $_SESSION['jaxl_auth'] = false;
+ $_SESSION['jaxl_sid'] = $arr["body"]["@"]["sid"];
$jaxl->bosh['sid'] = $arr["body"]["@"]["sid"];
+ $jaxl->log("[[JAXL0124]] Updated session to ".json_encode($_SESSION), 5);
}
}
}
return $payload;
}
}
?>
diff --git a/xep/jaxl.0206.php b/xep/jaxl.0206.php
index e835115..46275ee 100644
--- a/xep/jaxl.0206.php
+++ b/xep/jaxl.0206.php
@@ -1,128 +1,129 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
-
+
/**
* XEP-0206: XMPP over BOSH
*
* Uses XEP-0124 to wrap XMPP stanza's inside <body/> wrapper
*/
class JAXL0206 {
public static function init($jaxl) {
- // Requires Bosh Session Manager
- $jaxl->requires('JAXL0124');
$jaxl->log("[[JaxlAction]] ".$_REQUEST['jaxl']."\n".json_encode($_REQUEST), 5);
+
+ // Requires Bosh Session Manager
+ $jaxl->requires('JAXL0124');
}
public static function jaxl($jaxl, $xml) {
$jaxl->sendXML(urldecode($xml));
}
public static function startStream($jaxl) {
- $_SESSION['auth'] = 'connect';
+ $_SESSION['jaxl_auth'] = 'connect';
$xml = "";
$xml .= "<body";
$xml .= " content='".$jaxl->bosh['content']."'";
$xml .= " hold='".$jaxl->bosh['hold']."'";
$xml .= " xmlns='".$jaxl->bosh['xmlns']."'";
$xml .= " wait='".$jaxl->bosh['wait']."'";
$xml .= " rid='".++$jaxl->bosh['rid']."'";
$xml .= " version='".$jaxl->bosh['version']."'";
$xml .= " polling='".$jaxl->bosh['polling']."'";
$xml .= " secure='".$jaxl->bosh['secure']."'";
$xml .= " xmlns:xmpp='".$jaxl->bosh['xmlnsxmpp']."'";
$xml .= " to='".$jaxl->domain."'";
$xml .= " route='xmpp:".$jaxl->host.":".$jaxl->port."'";
$xml .= " xmpp:version='".$jaxl->bosh['xmppversion']."'/>";
$jaxl->sendXML($xml);
}
public static function endStream($jaxl) {
$_SESSION['auth'] = 'disconnect';
$xml = "";
$xml .= "<body";
$xml .= " rid='".++$jaxl->bosh['rid']."'";
$xml .= " sid='".$jaxl->bosh['sid']."'";
$xml .= " type='terminate'";
$xml .= " xmlns='".$jaxl->bosh['xmlns']."'>";
$xml .= "<presence type='unavailable' xmlns='jabber:client'/>";
$xml .= "</body>";
$jaxl->sendXML($xml);
}
public static function restartStream($jaxl) {
$xml = "";
$xml .= "<body";
$xml .= " rid='".++$jaxl->bosh['rid']."'";
$xml .= " sid='".$jaxl->bosh['sid']."'";
$xml .= " xmlns='".$jaxl->bosh['xmlns']."'";
$xml .= " to='".$jaxl->host."'";
$xml .= " xmpp:restart='true'";
$xml .= " xmlns:xmpp='".$jaxl->bosh['xmlnsxmpp']."'/>";
$_SESSION['auth'] = false;
$jaxl->sendXML($xml);
}
public static function ping($jaxl) {
$xml = '';
$xml .= '<body rid="'.++$jaxl->bosh['rid'].'"';
$xml .= ' sid="'.$jaxl->bosh['sid'].'"';
$xml .= ' xmlns="http://jabber.org/protocol/httpbind"/>';
$_SESSION['auth'] = true;
$jaxl->sendXML($xml);
}
public static function out($jaxl, $payload) {
JAXL0124::out($payload);
}
}
?>
|
jaxl/JAXL | 0a723c81017f84d336a7dea57cf5235a54359656 | Fixed typo in last commit for XEP 0114 | diff --git a/xep/jaxl.0114.php b/xep/jaxl.0114.php
index 05c2231..1ce7c3d 100644
--- a/xep/jaxl.0114.php
+++ b/xep/jaxl.0114.php
@@ -1,86 +1,86 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0114: Jabber Component Protocol
*/
class JAXL0114 {
public static function init($jaxl) {
// initialize working parameter for this jaxl instance
$jaxl->comp = array(
'host' => false,
'pass' => false
);
// parse user options
$jaxl->comp['host'] = $jaxl->getConfigByPriority(@$jaxl->config['compHost'], "JAXL_COMPONENT_HOST", $jaxl->comp['host']);
- $jaxl->pass['pass'] = $jaxl->getConfigByPriority(@$jaxl->config['compPass'], "JAXL_COMPONENT_PASS", $jaxl->comp['pass']);
+ $jaxl->comp['pass'] = $jaxl->getConfigByPriority(@$jaxl->config['compPass'], "JAXL_COMPONENT_PASS", $jaxl->comp['pass']);
// register required callbacks
$jaxl->addPlugin('jaxl_post_start', array('JAXL0114', 'handshake'));
$jaxl->addPlugin('jaxl_pre_handler', array('JAXL0114', 'preHandler'));
}
public static function startStream($jaxl, $payload) {
$xml = '<stream:stream xmlns="jabber:component:accept" xmlns:stream="http://etherx.jabber.org/streams" to="'.$jaxl->comp['host'].'">';
$jaxl->sendXML($xml);
}
public static function handshake($id, $jaxl) {
$hash = strtolower(sha1($id.$jaxl->comp['pass']));
$xml = '<handshake>'.$hash.'</handshake>';
$jaxl->sendXML($xml);
}
public static function preHandler($xml, $jaxl) {
if($xml == '<handshake/>') {
$xml = '';
JAXLPlugin::execute('jaxl_post_handshake', false, $jaxl);
}
return $xml;
}
}
?>
|
jaxl/JAXL | 43d54fa8aa7bb885af48c6aba5b794e96dea6e32 | Suppress warning thrown while enabling stream crypto | diff --git a/xmpp/xmpp.get.php b/xmpp/xmpp.get.php
index 0273d5d..608d25b 100644
--- a/xmpp/xmpp.get.php
+++ b/xmpp/xmpp.get.php
@@ -1,219 +1,219 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLog',
'JAXLXml',
'XMPPAuth',
'XMPPSend'
));
/**
* XMPP Get Class
* Provide methods for receiving all kind of xmpp streams and stanza's
*/
class XMPPGet {
public static function streamStream($arr, $jaxl) {
if($arr['@']["xmlns:stream"] != "http://etherx.jabber.org/streams") {
print "Unrecognized XMPP Stream...\n";
}
else if($arr['@']['xmlns'] == "jabber:component:accept") {
JAXLPlugin::execute('jaxl_post_start', $arr['@']['id'], $jaxl);
}
else if($arr['@']['xmlns'] == "jabber:client") {
$jaxl->streamId = $arr['@']['id'];
$jaxl->streamHost = $arr['@']['from'];
$jaxl->streamVersion = $arr['@']['version'];
}
}
public static function streamFeatures($arr, $jaxl) {
if(isset($arr["#"]["starttls"]) && ($arr["#"]["starttls"][0]["@"]["xmlns"] == "urn:ietf:params:xml:ns:xmpp-tls")) {
if($jaxl->openSSL) {
XMPPSend::startTLS($jaxl);
}
else {
$jaxl->log("[[XMPPGet]] OpenSSL extension required to proceed with TLS encryption");
throw new JAXLException("[[XMPPGet]] OpenSSL extension required to proceed with TLS encryption");
$jaxl->shutdown();
}
}
else if(isset($arr["#"]["mechanisms"]) && ($arr["#"]["mechanisms"][0]["@"]["xmlns"] == "urn:ietf:params:xml:ns:xmpp-sasl")) {
$mechanism = array();
foreach ($arr["#"]["mechanisms"][0]["#"]["mechanism"] as $row)
$mechanism[] = $row["#"];
JAXLPlugin::execute('jaxl_get_auth_mech', $mechanism, $jaxl);
}
else if(isset($arr["#"]["bind"]) && ($arr["#"]["bind"][0]["@"]["xmlns"] == "urn:ietf:params:xml:ns:xmpp-bind")) {
if(isset($arr["#"]["session"]))
if(!isset($arr["#"]["session"][0]["#"]["optional"]))
$jaxl->sessionRequired = true;
$jaxl->startBind();
}
}
public static function streamError($arr, $jaxl) {
$desc = key($arr['#']);
$xmlns = $arr['#'][$desc]['0']['@']['xmlns'];
JAXLPlugin::execute('jaxl_get_stream_error', $arr, $jaxl);
$jaxl->log("[[XMPPGet]] Stream error with description ".$desc." and xmlns ".$xmlns);
throw new JAXLException("[[XMPPGet]] Stream error with description ".$desc." and xmlns ".$xmlns);
return true;
}
public static function failure($arr, $jaxl) {
$xmlns = $arr['xmlns'];
switch($xmlns) {
case 'urn:ietf:params:xml:ns:xmpp-tls':
$jaxl->log("[[XMPPGet]] Unable to start TLS negotiation, see logs for detail...");
if($jaxl->mode == "cli") throw new JAXLException("[[XMPPGet]] Unable to start TLS negotiation, see logs for detail...");
JAXLPlugin::execute('jaxl_post_auth_failure', false, $jaxl);
$jaxl->shutdown('tlsFailure');
break;
case 'urn:ietf:params:xml:ns:xmpp-sasl':
$jaxl->log("[[XMPPGet]] Unable to complete SASL Auth, see logs for detail...");
if($jaxl->mode == "cli") throw new JAXLException("[[XMPPGet]] Unable to complete SASL Auth, see logs for detail...");
JAXLPlugin::execute('jaxl_post_auth_failure', false, $jaxl);
$jaxl->shutdown('saslFailure');
break;
default:
$jaxl->log("[[XMPPGet]] Uncatched failure xmlns received...");
if($jaxl->mode == "cli") throw new JAXLException("[[XMPPGet]] Uncatched failure xmlns received...");
break;
}
}
public static function proceed($arr, $jaxl) {
if($arr['xmlns'] == "urn:ietf:params:xml:ns:xmpp-tls") {
stream_set_blocking($jaxl->stream, 1);
- if(!stream_socket_enable_crypto($jaxl->stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT))
+ if(!@stream_socket_enable_crypto($jaxl->stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT))
stream_socket_enable_crypto($jaxl->stream, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
stream_set_blocking($jaxl->stream, 0);
XMPPSend::startStream($jaxl);
}
}
public static function challenge($arr, $jaxl) {
if($arr['xmlns'] == "urn:ietf:params:xml:ns:xmpp-sasl") {
if($jaxl->secondChallenge) $xml = '<response xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>';
else $xml = XMPPAuth::getResponse($jaxl->authType, $arr['challenge'], $jaxl);
$jaxl->sendXML($xml);
}
}
public static function success($arr, $jaxl) {
if($arr['xmlns'] == "urn:ietf:params:xml:ns:xmpp-sasl") {
if($jaxl->mode == "cgi") JAXL0206::restartStream($jaxl);
else XMPPSend::startStream($jaxl);
}
}
public static function presence($arrs, $jaxl) {
$payload = array();
foreach($arrs as $arr) $payload[] = $arr;
JAXLPlugin::execute('jaxl_get_presence', $payload, $jaxl);
unset($payload);
return $arrs;
}
public static function message($arrs, $jaxl) {
$payload = array();
foreach($arrs as $arr) $payload[] = $arr;
JAXLPlugin::execute('jaxl_get_message', $payload, $jaxl);
unset($payload);
return $arrs;
}
public static function postBind($arr, $jaxl) {
if($arr["type"] == "result") {
$jaxl->jid = $arr["bindJid"];
list($user, $domain, $resource) = JAXLUtil::splitJid($jaxl->jid);
$jaxl->resource = $resource;
JAXLPlugin::execute('jaxl_post_bind', false, $jaxl);
if($jaxl->sessionRequired) {
$jaxl->startSession();
}
else {
$jaxl->auth = true;
$jaxl->log("[[XMPPGet]] Auth completed...");
JAXLPlugin::execute('jaxl_post_auth', false, $jaxl);
}
}
}
public static function postSession($arr, $jaxl) {
if($arr["type"] == "result") {
$jaxl->auth = true;
$jaxl->log("[[XMPPGet]] Auth completed...");
JAXLPlugin::execute('jaxl_post_auth', false, $jaxl);
}
}
public static function iq($arr, $jaxl) {
switch($arr['type']) {
case 'get':
JAXLPlugin::execute('jaxl_get_iq_get', $arr, $jaxl);
break;
case 'set':
JAXLPlugin::execute('jaxl_get_iq_set', $arr, $jaxl);
break;
case 'result':
JAXLPlugin::execute('jaxl_get_iq_'.$arr['id'], $arr, $jaxl);
break;
case 'error':
JAXLPlugin::execute('jaxl_get_iq_'.$arr['id'], $arr, $jaxl);
break;
}
return $arr;
}
}
?>
|
jaxl/JAXL | d498738965958417e1cd50e0b0a2b24b66c871a1 | Entire Jaxl core including xmpp/, xep/ and core/ class files now make use of JAXL::addPlugin instead of JAXLPlugin to register per instance callbacks | diff --git a/CHANGELOG b/CHANGELOG
index d064813..58d100b 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,303 +1,304 @@
version 2.1.2
-------------
+- Entire Jaxl core including xmpp/, xep/ and core/ class files now make use of JAXL::addPlugin instead of JAXLPlugin to register per instance callbacks
- JAXLPlugin can now register a callback for a dedicated jaxl instance in a multi-instance jaxl application
Class functionality remains backward compatible.
- JAXLog class now also dump connect instance uid per log line
- XMPP instance iq id now defaults to a random value between 1 and 9
Also added jaxl_get_id event hook for apps to customize iq id for the connected Jaxl instance
Also as compared to default numeric iq id, Jaxl core now uses hex iq id's
- Every jaxl instance per php process id now generate it's own unique id JAXL::$uid
- Jaxl core doesn't go for a session if it's optional as indicated by the xmpp server
- Fixed boshChat postBind issues as reported by issue#26 (http://code.google.com/p/jaxl/issues/detail?id=26)
- Fixed jaxl constructor config read warning and XEP 0114 now make use of JAXL::getConfigByPriority method
- Removed warning while reading user config inside Jaxl constructor
Upgraded Jaxl Parser class which was malfunctioning on CentOS PHP 5.1.6 (cli)
- Added bosh error response handling and appropriate logging inside XMPP over Bosh core files
- Code cleanup inside jaxl logger class.
Fixed getConfigByPriority method which was malfunctioning in specific cases
- JAXLog class now using inbuild php function (error_log)
- Checking in first version of XEP-0016 (Privacy Lists), XEP-0055 (Jabber Search), XEP-0077 (In-Band Registration), XEP-0144 (Roster Item Exchange), XEP-0153 (vCard-Based Avatars), XEP-0237 (Roster Versioning)
- On auth faliure core doesn't throw exception since XMPP over Bosh apps are not held inside a try catch block (a better fix may be possible in future)
- XMPP over BOSH xep wasn't passing back Jaxl instance obj for jaxl_post_disconnect hook, fixed that for clean disconnect
- Jaxl core attempts to create log and pid files if doesn't already exists
Also instead of die() core throws relevant exception message wherever required
XMPP base classes throws relevant exception with message wherever required
- First commit of JAXLException class. JAXL core now uses JAXLException
- Jaxl constructor dies if logPath, pidPath and tmpPath doesn't exists on the system
- Core updates JAXL::resource after successful binding to match resource assigned by the connecting server
- Updated echobot sample example to make use of autoSubscribe core feature
Also registers callback for jaxl_post_subscription_request and jaxl_post_subscription_accept hooks
- Updated echobot and boshchat application to use in memory roster cache maintained by Jaxl core.
App files should register callback on hook jaxl_post_roster_update to get notified everytime local roster cache is updated
- Added provision for local roster cache management inside Jaxl core.
Retrived roster lists are cached in memory (see updated echobot.php sample example).
Also added provision for presence tracking (JAXL::trackPresence).
If enabled Jaxl core keep a track of jid availability and update local roster cache accordingly.
Also added provision for auto-accept subscription (JAXL::autoSubscribe).
- Removed XMPP::isConnected variable which used to tell status of connected socket stream.
This is equivalent to checking XMPP:stream variable for true/false
- Added a (kind of) buggy support for '/xml()' inside parser xpath
- If Jaxl instance has being configured for auto periodic ping (XEP-0199), pings are holded till auth completion.
Also if server responds 'feature-not-implemented' for first ping XEP-0199 automatically deleted periodic ping cron tab
- Corrected handling of error type iq stanza's (removed jaxl_get_iq_error hook)
- Added iq error code xpath inside JAXLXml class
- Completed missing JAXLCron::delete method for removing a previously registered cron tab
- Checking in first version of XEP-0049 (Private XML Storage) (not yet tested)
- Checking in first version of XEP-0191 (Simple Communication Blocking) (not yet tested)
- Added JAXL_PING_INTERVAL configuration option inside jaxl.ini
- XEP-0199 (XMPP Ping) can now automatically ping the connected server periodically for keeping connection alive on long running bots
(see echobot.php sample app for usage)
- Updated JAXLCron::add method to accept a number of arguments while adding bckgrnd jobs
These list of arguments is passed back to the application method
- Updated IQ handling inside XEP-0202 which wasn't returning iq stanza back resulting in no ping/pong
- Updated echobot to show usage of JAXL::discoItems and JAXL::discoInfo inside application code
- Added tagMap xpath for service identity and feature nodes in service discovery resultset
- JAXL core now auto includes XEP-0128 along with XEP-0030 on startup.
Also added two methods JAXL::discoItems and JAXL::discoInfo for service discovery
- Checking in first version of XEP-0128 (Service Discovery Extension)
- Fixed bug where message and presence stanza builder were not using passed id value as attribute
- Removed jaxl_pre_curl event hook which was only used internally by XEP-0124
- Jaxl now shutdown gracefully is encryption is required and openssl PHP module is not loaded in the environment
- For every registered callback on XMPP hooks, callback'd method will receive two params.
A payload and reference of Jaxl instance for whom XMPP event has occured.
Updated sample application code to use passed back Jaxl instance reference instead of global jaxl variable.
- As a library convention XEP's exposing user space configuration parameters via JAXL constructor SHOULD utilize JAXL::getConfigByPriority method
Added JAXL_TMP_PATH option inside jaxl.ini
- Jaxl::tmp is now Jaxl::tmpPath. Also added Jaxl config param to specify custom tmp path location
Jaxl client also self detect the IP of the host it is running upon (to be used by STUN/TURN utilities in Jingle negotitation)
- Removed JAXLUtil::includePath and JAXLUtil::getAppFilePath methods which are now redundant after removing jaxl.ini and jaxl.conf from lib core
- Removed global defines JAXL_BASE_PATH, JAXL_APP_BASE_PATH, JAXL_BOSH_APP_ABS_PATH from inside jaxl.ini (No more required by apps to specify these values)
- Removing env/jaxl.php and env/jaxl.conf (were required if you run your apps using `jaxl` command line utility)
Updated env/jaxl.ini so that projects can now directly include their app setting via jaxl.ini (before including core/jaxl.class.php)
- Added JAXL::bareJid public variable for usage inside applications.
XMPP base class now return bool on socket connect completion (used by PHPUnit test cases)
- Removing build.sh file from library for next release
Users should simply download, extract, include and write their app code without caring about the build script from 2.1.2 release
- As a library convention to include XEP's use JAXL::requires() method, while to include any core/ or xmpp/ base class use jaxl_require() method.
Updated library code and xep's to adhere to this convention.
Jaxl instance now provide a system specific /tmp folder location accessible by JAXL::tmp
- Removed JAXL_NAME and JAXL_VERSION constants.
Instead const variables are now defined per instance accessible by getName() and getVersion() methods.
Updated XEP-0030,0092,0115 to use the same
- Moved indivisual XEP's working parameter (0114,0124) from JAXL core class to XEP classes itself.
XEP's make use of JAXL::config array for parsing user options.
- Added JAXL_COMPONENT_PASS option inside jaxl.ini. Updated build.sh with new /app file paths.
Updated XEP-0114,0124,0206 to use array style configs as defined inside JAXL class
- Removed dependency upon jaxl.ini from all sample applications.
First checkin of sample sendMessage.php app.
- Config parameters for XEP's like 0114 and 0206 are now saved as an array inside JAXL class (later on they will be moved inside respective XEP's).
Added constructor config option to pre-choose an auth mechanism to be performed
if an auth mech is pre-chosen app files SHOULD not register callback for jaxl_get_auth_mech hook.
Bosh cookie settings can now be passed along with Jaxl constructor.
Added support for publishing vcard-temp:x:update node along with presence stanzas.
Jaxl instance can run in 3 modes a.k.a. stream,component and bosh mode
applications should use JAXL::startCore('mode') to configure instance for a specific mode.
- Removed redundant NS variable from inside XEP-0124
- Moved JAXLHTTPd setting defines inside the class (if gone missing CPU usage peaks to 100%)
- Added jaxl_httpd_pre_shutdown, jaxl_httpd_get_http_request, jaxl_httpd_get_sock_request event hooks inside JAXLHTTPd class
- Added JAXLS5B path (SOCKS5 implementation) inside jaxl_require method
- Removed all occurance of JAXL::$action variable from /core and /xep class files
- Updated boshChat and boshMUChat sample application which no longer user JAXL::$action variable inside application code
- Updated preFetchBOSH and preFetchXMPP sample example.
Application code don't need any JAXL::$action variable now
Neither application code need to define JAXL_BASE_PATH (optional from now on)
- JAXL core and XEP-0206 have no relation and dependency upon JAXL::$action variable now.
- Deprecated jaxl_get_body hook which was only for XEP-0124 working.
Also cleaned up XEP-0124 code by removing processBody method which is now handled inside preHandler itself.
- Defining JAXL_BASE_PATH inside application code made optional.
Developers can directly include /path/to/jaxl/core/jaxl.class.php and start writing applications.
Also added a JAXL::startCore() method (see usage in /app/preFetchXMPP.php).
Jaxl magic method for calling XEP methods now logs a warning inside jaxl.log if XEP doesn't exists in the environment
- Added tag map for XMPP message thread and subject child elements
- Fixed typo where in case of streamError proper description namespace was not parsed/displayed
- Disabled BOSH session close if application is running in boshOut=false mode
Suggested by MOVIM dev team who were experiencing loss of session data on end of script
- JAXL::log method 2nd parameter now defaults to logLevel=1 (passing 2nd param is now optional)
- Fixed XPath for iq stanza error condition and error NS extraction inside jaxl.parser.class
- First checkin of XEP-0184 Message Receipts
- Added support for usage of name() xpath function inside tag maps of JAXLXml class.
Also added some documentation for methods available inside JAXLXml class
- Fixed JAXLPlugin::remove method to properly remove and manage callback registry.
Also added some documentation for JAXLPlugin class methods
- Added JAXL contructor config option to disable BOSH module auto-output behaviour.
This is utilized inside app/preFetchBOSH.php sample example
- First checkin of sample application code pre-fetching XMPP/Jabber data for web page population using BOSH XEP
- Added a sample application file which can be used to pre-fetch XMPP/Jabber data for a webpage without using BOSH XEP or Ajax requests
As per the discussion on google groups (http://bit.ly/aKavZB) with MOVIM team
- JAXL library is now $jaxl independent, you can use anything like $var = new JAXL(); instance your applications now
JAXLUtil::encryptPassword now accepts username/password during SASL auth.
Previously it used to auto detect the same from JAXL instance, now core has to manually pass these param
- Added JAXL::startHTTPd method with appropriate docblock on how to convert Jaxl instance into a Jaxl socket (web) server.
Comments also explains how to still maintaining XMPP communication in the background
- Updated JAXLHTTPd class to use new constants inside jaxl.ini
- Added jaxl_get_stream_error event handler.
Registered callback methods also receive array form of received XMPP XML stanza
- Connecting Jaxl instance now fallback to default value 'localhost' for host,domain,boshHost,boshPort,boshSuffix
If these values are not configured either using jaxl.ini constants or constructor
- Provided a sendIQ method per JAXL instance.
Recommended that applications and XEP's should directly use this method for sending <iq/> type stanza
DONOT use XMPPSend methods inside your application code from here on
- Added configuration options for JAXL HTTPd server and JAXL Bosh Component Manager inside jaxl.ini
- Fixed type in XEP-0202 (Entity Time). XEP was not sending <iq/> id in response to get request
- Jaxl library is now phpdocs ready. Added extended documentation for JAXL core class, rest to be added
- All core classes inside core/, xmpp/ and xep/ folder now make use of jaxl->log method
JAXL Core constructor are now well prepared so that inclusion of jaxl.ini is now optional
Application code too should use jaxl->log instead of JAXLog::log method for logging purpose
- Reshuffled core instance paramaters between JAXL and XMPP class
Also Jaxl core now logs at level 1 instead of 0 (i.e. all logs goes inside jaxl.log and not on console)
- JAXL class now make use of endStream method inside XMPP base class while disconnecting.
Also XMPPSend::endStream now forces xmpp stanza delivery (escaping JAXL internal buffer)
http://code.google.com/p/jaxl/issues/detail?id=23
- Added endStream method inside XMPP base class and startSession,startBind methods inside XMPPSend class
XMPP::sendXML now accepts a $force parameter for escaping XMPP stanza's from JAXL internal buffer
- Updated the way Jaxl core calls XEP 0115 method (entity caps) to match documentation
XEP method's should accept jaxl instance as first paramater
- First checkin of PEP (Personal Eventing), User Location, User Mood, User Activity and User Tune XEP's
- Completed methods discoFeatures, discoNodes, discoNodeInfo, discoNodeMeta and discoNodeItems in PubSub XEP
- Hardcoded client category, type, lang and name. TODO: Make them configurable in future
- Cleaned up XEP 0030 (Service Discovery) and XEP 0115 (Entity Capabilities)
- Updated XMPP base class to use performance configuration parameters (now customizable with JAXL constructor)
- jaxl.conf will be removed from jaxl core in future, 1st step towards this goal
- Moved bulk of core configs from jaxl.conf
- Added more configuration options relating to client performance e.g. getPkts, getPktSize etc
- Fixed client mode by detecting sapi type instead of $_REQUEST['jaxl'] variable
- Now every implemented XEP should have an 'init' method which will accept only one parameter (jaxl instance itself)
- Jaxl core now converts transmitted stanza's into xmlentities (http://code.google.com/p/jaxl/issues/detail?id=22)
- Created a top level 'patch' folder which contains various patches sent by developers using 'git diff > patch' utility
- Fixed typo in namespace inside 0030 (thanks to Thomas Baquet for the patch)
- First checkin of PubSub XEP (untested)
- Indented build.sh and moved define's from top of JAXLHTTPd class to jaxl.ini
- Added JAXLHTTPd inside Jaxl core (a simple socket select server)
- Fixed sync of background iq and other stanza requests with browser ajax calls
- Updated left out methods in XMPP over BOSH xep to accept jaxl instance as first method
- All XEP methods available in application landspace, now accepts jaxl instance as first parameter. Updated core jaxl class magic method to handle the same.
If you are calling XEP methods as specified in the documentation, this change will not hurt your running applications
- Updated echobot sample application to utilize XEP 0054 (VCard Temp) and 0202 (Entity Time)
- First checkin of missing vcard-temp xep
- Added xmlentities JAXLUtil method
- Jaxl Parser now default parses xXmlns node for message stanzas
- Added PCRE_DOTALL and PCRE_MULTILINE pattern modifier for bosh unwrapBody method
- Added utility methods like urldecode, urlencode, htmlEntities, stripHTML and splitJid inside jaxl.js
- Updated sample application jaxl.ini to reflect changes in env/jaxl.ini
version 2.1.1
-------------
- Updated XMPPSend 'presence', 'message' and 'iq' methods to accept $jaxl instance as first parameter
if you are not calling these methods directly from your application code as mentioned in documentation
this change should not hurt you
- Added more comments to env/jaxl.ini and also added JAXL_LOG_ROTATE ini file option
- JAXL instance logs can be rotated every x seconds (logRotate config parameter) now
- Removed config param dumpTime, instead use dumpStat to specify stats dump period
- Base XMPP class now auto-flush output buffers filled because of library level rate limiter
- Added more options for JAXL constructor e.g.
boshHost, boshPort, boshSuffix, pidPath, logPath, logLevel, dumpStat, dumpTime
These param overwrites value specified inside jaxl.ini file
Also JAXL core will now periodically dump instance statistics
- Added an option in JAXL constructor to disable inbuild core rate limiter
- Added support when applications need to connect with external bosh endpoints
Bosh application code requires update for ->JAXL0206('startStream') method
- XMPPGet::handler replaces ->handler inside XEP-0124
- JAXLCron job now also passes connected instance to callback cron methods
- Updated base XMPP class now maintains a clock, updated sendXML method to respect library level rate limiting
- Base JAXL class now includes JAXLCron class for periodically dumping connected bot memory/usage stats
- First version of JAXLCron class for adding periodic jobs in the background
- XMPP payload handler moves from XMPPGet to base XMPP class, packets are then routed to XMPPGet class for further processing
- Updated xep-0124 to use instance bosh parameters instead of values defined inside jaxl.ini
- Provision to specify custom JAXL_BOSH_HOST inside jaxl.ini
- Instead of global logLevel and logPath, logger class now respects indivisual instance log settings
Helpful in multiple instance applications
- Updated base JAXL class to accept various other configuration parameters inside constructor
These param overwrites values defined inside jaxl.ini
- XMPPSend::xml method moves inside XMPP::sendXML (call using ->sendXML from within application code), as a part of library core cleanup
- Updated jaxl class to return back payload from called xep methods
- XMPP base method getXML can be instructed not to take a nap between stream reads
- Added jaxl_get_xml hook for taking control over incoming xml payload from xmpp stream
- Added support for disabling sig term registration, required by applications who already handle this in their core code
- Added capability of sending multiple message/presence stanza in one go inside jaxl base class
- Fixed typo in MUC Direct Invitation xep invite method
- getHandler should have accepted core instance by reference, fixed now. BOSH MUC Chat sample application header is now more appropriate
version 2.1.0
-------------
- First checkin of bosh MUC sample application
- Updated build file now packages bosh MUC chat sample application along with core classes
- Updated JAXLog class to accept instance inside log() method, application code should use ->log() to call JAXLog::log() method now
- Updated JAXLPlugin class to pass instance along with every XMPP event hook
- Updated jaxl_require method to call including XEP's init() method every time they are included using jaxl_require method
- Update jaxl.ini with some documentation/comments about JAXL_BOSH_COOKIE_DOMAIN parameter
- Updated echobot sample application code to pass instance while calling jaxl_require method
- Update XMPP SASL Auth class to accept instance while calculating SASL response.
Also passinginstance when jaxl_get_facebook_key hook is called
- Updated XMPP base class to accept component host name inside constructor.
Sending currentinstance with every XMPPSend, XMPPGet and JAXLog method calls
- Every XMPPGet method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Every XMPPSend method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Updated component bot sample application to show how to pass component host inside JAXL constructor.
Also updated jaxl_require call to accept current working instance
- Updated boshchat sample application to follow new rules of jaxl_require, also cleaned up the sample app code a bit
- Updated jaxl.ini of packaged sample applications to match /env/jaxl.ini
- Updated implemented XEP's init method to accept instance during initialization step
Send working instance with every XMPPSend method call
Almost every XEP's available method now accepts an additional instance so that XEP's can work independently for every instance inside a multiple jaxl instance application code
- Added magic method __call inside JAXL class
All application codes should now call a methods inside implemented XEP's like ->JAXLxxxx('method', , , ...)
Also added ->log method to be used by application codes
JAXLog::log() should not be called directly from application code
Updated XMPPSend methods to accept instance
Added ->requires() method that does a similar job as jaxl_require() which now also expects instance as one of the passed parameter.
version 2.0.4
-------------
- Updated XMPP base class and XMPP Get class to utilize new XMPPAuth class
- Updated jaxl_require method with new XMPPAuth class path
- Extracted XMPP SASL auth mechanism out of XMPP Get class, code cleanup
- unwrapBody method of XEP 0124 is now public
- Added #News block on top of README
- No more capital true, false, null inside Jaxl core to pass PHP_CodeSniffer tests
- :retab Jaxl library core to pass PHP_CodeSniffer tests
- Added Jabber Component Protocol example application bot
- Updated README with documentation link for Jabber component protocol
- Updated Entity Caps method to use list of passed feature list for verification code generation
- Updated MUC available methods doc link inside README
- Added experimental support for SCRAM-SHA-1, CRAM-MD5 and LOGIN auth mechanisms
version 2.0.3
-------------
- Updated Jaxl XML parsing class to handle multiple level nested child cases
- Updated README and bosh chat application with documentation link
- Fixed bosh application to run on localhost
- Added doc links inside echobot sample app
- Bosh sample application also use entity time XEP-0202 now
- Fix for sapi detection inside jaxl util
- jaxl.js updated to handle multiple ajax poll response payloads
- Bosh session manager now dumps ajax poll response on post handler callback
- Removed hardcoded ajax poll url inside boshchat application
- Updated component protocol XEP pre handshake event handling
version 2.0.2
-------------
- Packaged XEP 0202 (Entity Time)
- First checkin of Bosh related XEP 0124 and 0206
- Sample Bosh Chat example application
- Updated jaxl.class.php to save Bosh request action parameter
- jaxl.ini updated with Bosh related cookie options, default loglevel now set to 4
- jaxl.js checkin which should be used with bosh applications
- Updated base xmpp classes to provide integrated bosh support
- Outgoing presence and message stanza's too can include @id attribute now
version 2.0.1
-------------
- Typo fix in JAXLXml::$tagMap for errorCode
- Fix for handling overflooded roster list
- Packaged XEP 0115 (Entity capability) and XEP 0199 (XMPP Ping)
- Updated sample echobot to use XEP 0115 and XEP 0199
- Support for X-FACEBOOK-PLATFORM authentication
version 2.0.0
--------------
First checkin of:
- Restructed core library with event mechanism
- Packaged XEP 0004, 0030, 0045, 0050, 0085, 0092, 0114, 0133, 0249
- Sample echobot application
diff --git a/core/jaxl.class.php b/core/jaxl.class.php
index 3326a02..9828853 100644
--- a/core/jaxl.class.php
+++ b/core/jaxl.class.php
@@ -43,821 +43,835 @@
declare(ticks=1);
// Set JAXL_BASE_PATH if not already defined by application code
if(!@constant('JAXL_BASE_PATH'))
define('JAXL_BASE_PATH', dirname(dirname(__FILE__)));
/**
* Autoload method for Jaxl library and it's applications
*
* @param string|array $classNames core class name required in PHP environment
* @param object $jaxl Jaxl object which require these classes. Optional but always required while including implemented XEP's in PHP environment
*/
function jaxl_require($classNames, $jaxl=false) {
static $included = array();
$tagMap = array(
// core classes
'JAXLBosh' => '/core/jaxl.bosh.php',
'JAXLCron' => '/core/jaxl.cron.php',
'JAXLHTTPd' => '/core/jaxl.httpd.php',
'JAXLog' => '/core/jaxl.logger.php',
'JAXLXml' => '/core/jaxl.parser.php',
'JAXLPlugin' => '/core/jaxl.plugin.php',
'JAXLUtil' => '/core/jaxl.util.php',
'JAXLS5B' => '/core/jaxl.s5b.php',
'JAXLException' => '/core/jaxl.exception.php',
'XML' => '/core/jaxl.xml.php',
// xmpp classes
'XMPP' => '/xmpp/xmpp.class.php',
'XMPPGet' => '/xmpp/xmpp.get.php',
'XMPPSend' => '/xmpp/xmpp.send.php',
'XMPPAuth' => '/xmpp/xmpp.auth.php'
);
if(!is_array($classNames)) $classNames = array('0'=>$classNames);
foreach($classNames as $key => $className) {
$xep = substr($className, 4, 4);
if(substr($className, 0, 4) == 'JAXL'
&& is_numeric($xep)
) { // is XEP
if(!isset($included[$className])) {
require_once JAXL_BASE_PATH.'/xep/jaxl.'.$xep.'.php';
$included[$className] = true;
}
call_user_func(array('JAXL'.$xep, 'init'), $jaxl);
} // is Core file
else if(isset($tagMap[$className])) {
require_once JAXL_BASE_PATH.$tagMap[$className];
$included[$className] = true;
}
}
return;
}
// Include core classes and xmpp base
jaxl_require(array(
'JAXLog',
'JAXLUtil',
'JAXLPlugin',
'JAXLCron',
'JAXLException',
'XML',
'XMPP',
));
/**
* Jaxl class extending base XMPP class
*
* Jaxl library core is like any of your desktop Instant Messaging (IM) clients.
* Include Jaxl core in you application and start connecting and managing multiple XMPP accounts
* Packaged library is custom configured for running <b>single instance</b> Jaxl applications
*
* For connecting <b>multiple instance</b> XMPP accounts inside your application rewrite Jaxl controller
* using combination of env/jaxl.php, env/jaxl.ini and env/jaxl.conf
*/
class JAXL extends XMPP {
/**
* Client version of the connected Jaxl instance
*/
const version = '2.1.2';
/**
* Client name of the connected Jaxl instance
*/
const name = 'Jaxl :: Jabber XMPP Client Library';
/**
* Custom config passed to Jaxl constructor
*
* @var array
*/
var $config = array();
/**
* Username of connecting Jaxl instance
*
* @var string
*/
var $user = false;
/**
* Password of connecting Jaxl instance
*
* @var string
*/
var $pass = false;
/**
* Hostname for the connecting Jaxl instance
*
* @var string
*/
var $host = 'localhost';
/**
* Port for the connecting Jaxl instance
*
* @var integer
*/
var $port = 5222;
/**
* Full JID of the connected Jaxl instance
*
* @var string
*/
var $jid = false;
/**
* Bare JID of the connected Jaxl instance
*
* @var string
*/
var $bareJid = false;
/**
* Domain for the connecting Jaxl instance
*
* @var string
*/
var $domain = 'localhost';
/**
* Resource for the connecting Jaxl instance
*
* @var string
*/
var $resource = false;
/**
* Local cache of roster list and related info maintained by Jaxl instance
*/
var $roster = array();
/**
* Jaxl will track presence stanza's and update local $roster cache
*/
var $trackPresence = true;
/**
* Configure Jaxl instance to auto-accept subscription requests
*/
var $autoSubscribe = false;
/**
* Log Level of the connected Jaxl instance
*
* @var integer
*/
var $logLevel = 1;
/**
* Enable/Disable automatic log rotation for this Jaxl instance
*
* @var bool|integer
*/
var $logRotate = false;
/**
* Absolute path of log file for this Jaxl instance
*/
var $logPath = '/var/log/jaxl.log';
/**
* Absolute path of pid file for this Jaxl instance
*/
var $pidPath = '/var/run/jaxl.pid';
/**
* Enable/Disable shutdown callback on SIGH terms
*
* @var bool
*/
var $sigh = true;
/**
* Process Id of the connected Jaxl instance
*
* @var bool|integer
*/
var $pid = false;
/**
* Mode of the connected Jaxl instance (cgi or cli)
*
* @var bool|string
*/
var $mode = false;
/**
* Jabber auth mechanism performed by this Jaxl instance
*
* @var false|string
*/
var $authType = false;
/**
* Jaxl instance dumps usage statistics periodically. Disabled if set to "false"
*
* @var bool|integer
*/
var $dumpStat = 300;
/**
* List of XMPP feature supported by this Jaxl instance
*
* @var array
*/
var $features = array();
/**
* XMPP entity category for the connected Jaxl instance
*
* @var string
*/
var $category = 'client';
/**
* XMPP entity type for the connected Jaxl instance
*
* @var string
*/
var $type = 'bot';
/**
* Default language of the connected Jaxl instance
*/
var $lang = 'en';
/**
* Location to system temporary folder
*/
var $tmpPath = null;
/**
* IP address of the host Jaxl instance is running upon.
* To be used by STUN client implementations.
*/
var $ip = null;
/**
* PHP OpenSSL module info
*/
var $openSSL = false;
/**
* @return string $name Returns name of this Jaxl client
*/
function getName() {
return JAXL::name;
}
/**
* @return float $version Returns version of this Jaxl client
*/
function getVersion() {
return JAXL::version;
}
/**
* Discover items
*/
function discoItems($jid, $callback, $node=false) {
$this->JAXL0030('discoItems', $jid, $this->jid, $callback, $node);
}
/**
* Discover info
*/
function discoInfo($jid, $callback, $node=false) {
$this->JAXL0030('discoInfo', $jid, $this->jid, $callback, $node);
}
/**
* Shutdown Jaxl instance cleanly
*
* shutdown method is auto invoked when Jaxl instance receives a SIGH term.
* Before cleanly shutting down this method callbacks registered using <b>jaxl_pre_shutdown</b> hook.
*
* @param mixed $signal This is passed as paramater to callbacks registered using <b>jaxl_pre_shutdown</b> hook
*/
function shutdown($signal=false) {
$this->log("[[JAXL]] Shutting down ...");
JAXLPlugin::execute('jaxl_pre_shutdown', $signal, $this);
if($this->stream) $this->endStream();
$this->stream = false;
}
/**
* Perform authentication for connecting Jaxl instance
*
* @param string $type Authentication mechanism to proceed with. Supported auth types are:
* - DIGEST-MD5
* - PLAIN
* - X-FACEBOOK-PLATFORM
* - ANONYMOUS
*/
function auth($type) {
$this->authType = $type;
return XMPPSend::startAuth($this);
}
/**
* Set status of the connected Jaxl instance
*
* @param bool|string $status
* @param bool|string $show
* @param bool|integer $priority
* @param bool $caps
*/
function setStatus($status=false, $show=false, $priority=false, $caps=false, $vcard=false) {
$child = array();
$child['status'] = ($status === false ? 'Online using Jaxl library http://code.google.com/p/jaxl' : $status);
$child['show'] = ($show === false ? 'chat' : $show);
$child['priority'] = ($priority === false ? 1 : $priority);
if($caps) $child['payload'] = $this->JAXL0115('getCaps', $this->features);
if($vcard) $child['payload'] .= $this->JAXL0153('getUpdateData', false);
return XMPPSend::presence($this, false, false, $child, false);
}
/**
* Send authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send authorization request
*/
function subscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribe');
}
/**
* Accept authorization request from $toJid
*
* @param string $toJid JID who's authorization request Jaxl instance wants to accept
*/
function subscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'subscribed');
}
/**
* Send cancel authorization request to $toJid
*
* @param string $toJid JID whom Jaxl instance wants to send cancel authorization request
*/
function unsubscribe($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribe');
}
/**
* Accept cancel authorization request from $toJid
*
* @param string $toJid JID who's cancel authorization request Jaxl instance wants to accept
*/
function unsubscribed($toJid) {
return XMPPSend::presence($this, $toJid, false, false, 'unsubscribed');
}
/**
* Retrieve connected Jaxl instance roster list from the server
*
* @param mixed $callback Method to be callback'd when roster list is received from the server
*/
function getRosterList($callback=false) {
$payload = '<query xmlns="jabber:iq:roster"/>';
if($callback === false) $callback = array($this, '_handleRosterList');
return XMPPSend::iq($this, "get", $payload, false, $this->jid, $callback);
}
/**
* Add a new jabber account in connected Jaxl instance roster list
*
* @param string $jid JID to be added in the roster list
* @param string $group Group name
* @param bool|string $name Name of JID to be added
*/
function addRoster($jid, $group, $name=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Update subscription of a jabber account in roster list
*
* @param string $jid JID to be updated inside roster list
* @param string $group Updated group name
* @param bool|string $subscription Updated subscription type
*/
function updateRoster($jid, $group, $name=false, $subscription=false) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'"';
if($name) $payload .= ' name="'.$name.'"';
if($subscription) $payload .= ' subscription="'.$subscription.'"';
$payload .= '>';
$payload .= '<group>'.$group.'</group>';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Delete a jabber account from roster list
*
* @param string $jid JID to be removed from the roster list
*/
function deleteRoster($jid) {
$payload = '<query xmlns="jabber:iq:roster">';
$payload .= '<item jid="'.$jid.'" subscription="remove">';
$payload .= '</item>';
$payload .= '</query>';
return XMPPSend::iq($this, "set", $payload, false, $this->jid, false);
}
/**
* Send an XMPP message
*
* @param string $to JID to whom message is sent
* @param string $message Message to be sent
* @param string $from (Optional) JID from whom this message should be sent
* @param string $type (Optional) Type of message stanza to be delivered
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessage($to, $message, $from=false, $type='chat', $id=false) {
$child = array();
$child['body'] = $message;
return XMPPSend::message($this, $to, $from, $child, $type, $id);
}
/**
* Send multiple XMPP messages in one go
*
* @param array $to array of JID's to whom this presence stanza should be send
* @param array $from (Optional) array of JID from whom this presence stanza should originate
* @param array $child (Optional) array of arrays specifying child objects of the stanza
* @param array $type (Optional) array of type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendMessages($to, $from=false, $child=false, $type='chat', $id=false) {
return XMPPSend::message($this, $to, $from, $child, $type);
}
/**
* Send an XMPP presence stanza
*
* @param string $to (Optional) JID to whom this presence stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param array $child (Optional) array specifying child objects of the stanza
* @param string $type (Optional) Type of presence stanza to send
* @param integer $id (Optional) Add an id attribute to transmitted stanza (omitted if not provided)
*/
function sendPresence($to=false, $from=false, $child=false, $type=false, $id=false) {
return XMPPSend::presence($this, $to, $from, $child, $type, $id);
}
/**
* Send an XMPP iq stanza
*
* @param string $type Type of iq stanza to send
* @param string $payload (Optional) XML string to be transmitted
* @param string $to (Optional) JID to whom this iq stanza should be send
* @param string $from (Optional) JID from whom this presence stanza should originate
* @param string|array $callback (Optional) Callback method which will handle "result" type stanza rcved
* @param integer $id (Optional) Add an id attribute to transmitted stanza (auto-generated if not provided)
*/
function sendIQ($type, $payload=false, $to=false, $from=false, $callback=false, $id=false) {
return XMPPSend::iq($this, $type, $payload, $to, $from, $callback, $id);
}
/**
* Logs library core and application debug data into the log file
*
* @param string $log Datum to be logged
* @param integer $level Log level for passed datum
*/
function log($log, $level=1) {
JAXLog::log($log, $level, $this);
}
/**
* Instead of using jaxl_require method applications can use $jaxl->requires to include XEP's in PHP environment
*
* @param string $class Class name of the XEP to be included e.g. JAXL0045 for including XEP-0045 a.k.a. Multi-user chat
*/
function requires($class) {
jaxl_require($class, $this);
}
+ /**
+ * Use this method instead of JAXLPlugin::add to register a callback for connected instance only
+ */
+ function addPlugin($hook, $callback, $priority=10) {
+ JAXLPlugin::add($hook, $callback, $priority, $this->uid);
+ }
+
+ /**
+ * Use this method instead of JAXLPlugin::remove to remove a callback for connected instance only
+ */
+ function removePlugin($hook, $callback, $priority=10) {
+ JAXLPlugin::remove($hook, $callback, $priority, $this->uid);
+ }
+
/**
* Starts Jaxl Core
*
* This method should be called after Jaxl initialization and hook registration inside your application code
* Optionally, you can pass 'jaxl_post_connect' and 'jaxl_get_auth_mech' response type directly to this method
* In that case application code SHOULD NOT register callbacks to above mentioned hooks
*
* @param string $arg[0] Optionally application code can pre-choose what Jaxl core should do after establishing socket connection.
* Following are the valid options:
* a) startStream
* b) startComponent
* c) startBosh
*/
function startCore($mode=false) {
if($mode) {
switch($mode) {
case 'stream':
- JAXLPlugin::add('jaxl_post_connect', array($this, 'startStream'));
+ $this->addPlugin('jaxl_post_connect', array($this, 'startStream'));
break;
case 'component':
- JAXLPlugin::add('jaxl_post_connect', array($this, 'startComponent'));
+ $this->addPlugin('jaxl_post_connect', array($this, 'startComponent'));
break;
case 'bosh':
$this->startBosh();
break;
default:
break;
}
}
if($this->mode == 'cli') {
try {
if($this->connect()) {
while($this->stream) {
$this->getXML();
}
}
}
catch(JAXLException $e) {
die($e->getMessage());
}
/* Exit Jaxl after end of loop */
exit;
}
}
/**
* Starts a socket server at 127.0.0.1:port
*
* startHTTPd converts Jaxl instance into a Jaxl socket server (may or may not be a HTTP server)
* Same Jaxl socket server instance <b>SHOULD NOT</b> be used for XMPP communications.
* Instead separate "new Jaxl();" instances should be created for such XMPP communications.
*
* @param integer $port Port at which to start the socket server
* @param integer $maxq JAXLHTTPd socket server max queue
*/
function startHTTPd($port, $maxq) {
JAXLHTTPd::start(array(
'port' => $port,
'maxq' => $maxq
));
}
/**
* Start instance in bosh mode
*/
function startBosh() {
$this->JAXL0206('startStream');
}
/**
* Start instance in component mode
*/
function startComponent($payload, $jaxl) {
$this->JAXL0114('startStream', $payload);
}
/**
* Jaxl core constructor
*
* Jaxl instance configures itself using the constants inside your application jaxl.ini.
* However, passed array of configuration options overrides the value inside jaxl.ini.
* If no configuration are found or passed for a particular value,
* Jaxl falls back to default config options.
*
* @param $config Array of configuration options
* @todo Use DNS SRV lookup to set $jaxl->host from provided domain info
*/
function __construct($config=array()) {
$this->ip = gethostbyname(php_uname('n'));
$this->mode = (PHP_SAPI == "cli") ? PHP_SAPI : "cgi";
$this->config = $config;
$this->pid = getmypid();
$this->uid = rand(10, 99999);
/* Mandatory params to be supplied either by jaxl.ini constants or constructor $config array */
$this->user = $this->getConfigByPriority(@$config['user'], "JAXL_USER_NAME", $this->user);
$this->pass = $this->getConfigByPriority(@$config['pass'], "JAXL_USER_PASS", $this->pass);
$this->domain = $this->getConfigByPriority(@$config['domain'], "JAXL_HOST_DOMAIN", $this->domain);
$this->bareJid = $this->user."@".$this->domain;
/* Optional params if not configured using jaxl.ini or $config take default values */
$this->host = $this->getConfigByPriority(@$config['host'], "JAXL_HOST_NAME", $this->domain);
$this->port = $this->getConfigByPriority(@$config['port'], "JAXL_HOST_PORT", $this->port);
$this->resource = $this->getConfigByPriority(@$config['resource'], "JAXL_USER_RESC", "jaxl.".time());
$this->logLevel = $this->getConfigByPriority(@$config['logLevel'], "JAXL_LOG_LEVEL", $this->logLevel);
$this->logRotate = $this->getConfigByPriority(@$config['logRotate'], "JAXL_LOG_ROTATE", $this->logRotate);
$this->logPath = $this->getConfigByPriority(@$config['logPath'], "JAXL_LOG_PATH", $this->logPath);
if(!file_exists($this->logPath) && !touch($this->logPath)) throw new JAXLException("Log file ".$this->logPath." doesn't exists");
$this->pidPath = $this->getConfigByPriority(@$config['pidPath'], "JAXL_PID_PATH", $this->pidPath);
if($this->mode == "cli" && !file_exists($this->pidPath) && !touch($this->pidPath)) throw new JAXLException("Pid file ".$this->pidPath." doesn't exists");
/* Resolve temporary folder path */
if(function_exists('sys_get_temp_dir')) $this->tmpPath = sys_get_temp_dir();
$this->tmpPath = $this->getConfigByPriority(@$config['tmpPath'], "JAXL_TMP_PATH", $this->tmpPath);
if($this->tmpPath && !file_exists($this->tmpPath)) throw new JAXLException("Tmp directory ".$this->tmpPath." doesn't exists");
/* Handle pre-choosen auth type mechanism */
$this->authType = $this->getConfigByPriority(@$config['authType'], "JAXL_AUTH_TYPE", $this->authType);
- if($this->authType) JAXLPlugin::add('jaxl_get_auth_mech', array($this, 'doAuth'));
+ if($this->authType) $this->addPlugin('jaxl_get_auth_mech', array($this, 'doAuth'));
/* Presence handling */
$this->trackPresence = isset($config['trackPresence']) ? $config['trackPresence'] : true;
$this->autoSubscribe = isset($config['autoSubscribe']) ? $config['autoSubscribe'] : false;
- JAXLPlugin::add('jaxl_get_presence', array($this, '_handlePresence'), 0);
+ $this->addPlugin('jaxl_get_presence', array($this, '_handlePresence'), 0);
/* Optional params which can be configured only via constructor $config */
$this->sigh = isset($config['sigh']) ? $config['sigh'] : true;
$this->dumpStat = isset($config['dumpStat']) ? $config['dumpStat'] : 300;
/* Configure instance for platforms and call parent construct */
$this->configure($config);
parent::__construct($config);
$this->xml = new XML();
/* Initialize JAXLCron and register instance cron jobs */
- JAXLCron::init($jaxl);
+ JAXLCron::init($this);
if($this->dumpStat) JAXLCron::add(array($this, 'dumpStat'), $this->dumpStat);
if($this->logRotate) JAXLCron::add(array('JAXLog', 'logRotate'), $this->logRotate);
// include service discovery XEP-0030 and it's extensions, recommended for every XMPP entity
$this->requires(array(
'JAXL0030',
'JAXL0128'
));
}
/**
* Return Jaxl instance config param depending upon user choice and default values
*/
function getConfigByPriority($config, $constant, $default) {
return ($config === null) ? (@constant($constant) === null ? $default : constant($constant)) : $config;
}
/**
* Configures Jaxl instance to run across various platforms (*nix/windows)
*
* Configure method tunes connecting Jaxl instance for
* OS compatibility, SSL support and dependencies over PHP methods
*/
protected function configure() {
// register shutdown function
if(!JAXLUtil::isWin() && JAXLUtil::pcntlEnabled() && $this->sigh) {
pcntl_signal(SIGTERM, array($this, "shutdown"));
pcntl_signal(SIGINT, array($this, "shutdown"));
$this->log("[[JAXL]] Registering callbacks for CTRL+C and kill.");
}
else {
$this->log("[[JAXL]] No callbacks registered for CTRL+C and kill.");
}
// check Jaxl dependency on PHP extension in cli mode
if($this->mode == "cli") {
if(($this->openSSL = JAXLUtil::sslEnabled()))
$this->log("[[JAXL]] OpenSSL extension is loaded.");
else
$this->log("[[JAXL]] OpenSSL extension not loaded.");
if(!function_exists('fsockopen'))
throw new JAXLException("[[JAXL]] Requires fsockopen method");
if(@is_writable($this->pidPath))
file_put_contents($this->pidPath, $this->pid);
}
// check Jaxl dependency on PHP extension in cgi mode
if($this->mode == "cgi") {
if(!function_exists('curl_init'))
throw new JAXLException("[[JAXL]] Requires CURL PHP extension");
if(!function_exists('json_encode'))
throw new JAXLException("[[JAXL]] Requires JSON PHP extension.");
}
}
/**
* Dumps Jaxl instance usage statistics
*
* Jaxl instance periodically calls this methods every JAXL::$dumpStat seconds.
*/
function dumpStat() {
$stat = "[[JAXL]] Memory usage: ".round(memory_get_usage()/pow(1024,2), 2)." Mb";
if(function_exists('memory_get_peak_usage'))
$stat .= ", Peak usage: ".round(memory_get_peak_usage()/pow(1024,2), 2)." Mb";
$this->log($stat, 0);
}
/**
* Magic method for calling XEP's included by the JAXL instance
*
* Application <b>should never</b> call an XEP method directly using <code>JAXL0045::joinRoom()</code>
* instead use <code>$jaxl->JAXL0045('joinRoom', $param1, ..)</code> to call methods provided by included XEP's
*
* @param string $xep XMPP extension (XEP) class name e.g. JAXL0045 for XEP-0045 a.k.a. Multi-User chat extension
* @param array $param Array of parameters where $param[0]='methodName' is the method called inside JAXL0045 class
*
* @return mixed $return Return value of called XEP method
*/
function __call($xep, $param) {
$method = array_shift($param);
array_unshift($param, $this);
if(substr($xep, 0, 4) == 'JAXL') {
$xep = substr($xep, 4, 4);
if(is_numeric($xep)
&& class_exists('JAXL'.$xep)
) { return call_user_func_array(array('JAXL'.$xep, $method), $param); }
else { $this->log("[[JAXL]] JAXL$xep Doesn't exists in the environment"); }
}
}
/**
* Perform pre-choosen auth type for the Jaxl instance
*/
function doAuth($mechanism) {
return XMPPSend::startAuth($this);
}
/**
* Adds a node (if doesn't exists) for $jid inside local $roster cache
*/
function _addRosterNode($jid, $inRoster=true) {
if(!isset($this->roster[$jid]))
$this->roster[$jid] = array(
'groups'=>array(),
'name'=>'',
'subscription'=>'',
'presence'=>array(),
'inRoster'=>$inRoster
);
return;
}
/**
* Core method that accepts retrieved roster list and manage local cache
*/
function _handleRosterList($payload, $jaxl) {
if(is_array($payload['queryItemJid'])) {
foreach($payload['queryItemJid'] as $key=>$jid) {
$this->_addRosterNode($jid);
$this->roster[$jid]['groups'] = $payload['queryItemGrp'][$key];
$this->roster[$jid]['name'] = $payload['queryItemName'][$key];
$this->roster[$jid]['subscription'] = $payload['queryItemSub'][$key];
}
}
else {
$jid = $payload['queryItemJid'];
$this->_addRosterNode($jid);
$this->roster[$jid]['groups'] = $payload['queryItemGrp'];
$this->roster[$jid]['name'] = $payload['queryItemName'];
$this->roster[$jid]['subscription'] = $payload['queryItemSub'];
}
JAXLPlugin::execute('jaxl_post_roster_update', $payload, $this);
return $payload;
}
/**
* Tracks all incoming presence stanza's
*/
function _handlePresence($payloads, $jaxl) {
foreach($payloads as $payload) {
if($this->trackPresence) {
// update local $roster cache
$jid = JAXLUtil::getBareJid($payload['from']);
$this->_addRosterNode($jid, false);
if(!isset($this->roster[$jid]['presence'][$payload['from']])) $this->roster[$jid]['presence'][$payload['from']] = array();
$this->roster[$jid]['presence'][$payload['from']]['type'] = $payload['type'] == '' ? 'available' : $payload['type'];
$this->roster[$jid]['presence'][$payload['from']]['status'] = $payload['status'];
$this->roster[$jid]['presence'][$payload['from']]['show'] = $payload['show'];
$this->roster[$jid]['presence'][$payload['from']]['priority'] = $payload['priority'];
}
if($payload['type'] == 'subscribe'
&& $this->autoSubscribe
) {
$this->subscribed($payload['from']);
$this->subscribe($payload['from']);
JAXLPlugin::execute('jaxl_post_subscription_request', $payload, $this);
}
else if($payload['type'] == 'subscribed') {
JAXLPlugin::execute('jaxl_post_subscription_accept', $payload, $this);
}
}
return $payloads;
}
}
?>
diff --git a/core/jaxl.cron.php b/core/jaxl.cron.php
index 8ad06bc..1386227 100644
--- a/core/jaxl.cron.php
+++ b/core/jaxl.cron.php
@@ -1,93 +1,93 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl Cron Job
*
* Add periodic cron in your xmpp applications
*/
class JAXLCron {
private static $cron = array();
public static function init($jaxl) {
- JAXLPlugin::add('jaxl_get_xml', array('JAXLCron', 'ticker'));
+ $jaxl->addPlugin('jaxl_get_xml', array('JAXLCron', 'ticker'));
}
public static function ticker($payload, $jaxl) {
foreach(self::$cron as $interval => $jobs) {
foreach($jobs as $key => $job) {
if($jaxl->clock % $interval == 0 // if cron interval matches
|| $jaxl->clocked - $job['lastCall'] > $interval // if cron interval has already passed
) {
self::$cron[$interval][$key]['lastCall'] = $jaxl->clocked;
$arg = $job['arg'];
array_unshift($arg, $jaxl);
call_user_func_array($job['callback'], $arg);
}
}
}
return $payload;
}
public static function add(/* $callback, $interval, $param1, $param2, .. */) {
$arg = func_get_args();
$callback = array_shift($arg);
$interval = array_shift($arg);
self::$cron[$interval][self::generateCbSignature($callback)] = array('callback'=>$callback, 'arg'=>$arg, 'lastCall'=>time());
}
public static function delete($callback, $interval) {
$sig = self::generateCbSignature($callback);
if(isset(self::$cron[$interval][$sig]))
unset(self::$cron[$interval][$sig]);
}
protected static function generateCbSignature($callback) {
return is_array($callback) ? md5(json_encode($callback)) : md5($callback);
}
}
?>
diff --git a/core/jaxl.plugin.php b/core/jaxl.plugin.php
index 70959cf..27c844f 100644
--- a/core/jaxl.plugin.php
+++ b/core/jaxl.plugin.php
@@ -1,120 +1,121 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl Plugin Framework
*/
class JAXLPlugin {
/**
* Registry of all registered hooks
*/
public static $registry = array();
/**
* Register callback on hook
*
* @param string $hook
* @param string|array $callback A valid callback inside your application code
* @param integer $priority (>0) When more than one callbacks is attached on hook, they are called in priority order or which ever was registered first
* @param integer $uid random id $jaxl->uid of connected Jaxl instance, $uid=0 means callback registered for all connected instances
*/
public static function add($hook, $callback, $priority=10, $uid=0) {
if(!isset(self::$registry[$uid]))
self::$registry[$uid] = array();
if(!isset(self::$registry[$uid][$hook]))
self::$registry[$uid][$hook] = array();
if(!isset(self::$registry[$uid][$hook][$priority]))
self::$registry[$uid][$hook][$priority] = array();
array_push(self::$registry[$uid][$hook][$priority], $callback);
}
/**
* Removes a previously registered callback on hook
*
* @param string $hook
* @param string|array $callback
* @param integer $priority
* @param integer $uid random id $jaxl->uid of connected Jaxl instance, $uid=0 means callback registered for all connected instances
*/
public static function remove($hook, $callback, $priority=10, $uid=0) {
if(($key = array_search($callback, self::$registry[$uid][$hook][$priority])) !== FALSE)
unset(self::$registry[$uid][$hook][$priority][$key]);
if(count(self::$registry[$uid][$hook][$priority]) == 0)
unset(self::$registry[$uid][$hook][$priority]);
if(count(self::$registry[$uid][$hook]) == 0)
unset(self::$registry[$uid][$hook]);
}
/*
* Method calls previously registered callbacks on executing hook
*
* @param string $hook
* @param mixed $payload
* @param object $jaxl
* @param array $filter
*/
public static function execute($hook, $payload=null, $jaxl=false, $filter=false) {
$uids = array($jaxl->uid, 0);
foreach($uids as $uid) {
if(isset(self::$registry[$uid][$hook]) && count(self::$registry[$uid][$hook]) > 0) {
foreach(self::$registry[$uid][$hook] as $priority) {
foreach($priority as $callback) {
if($filter === false || (is_array($filter) && in_array($callback[0], $filter))) {
+ //$jaxl->log("[[JAXLPlugin]] Executing hook $hook for uid $uid", 5);
$payload = call_user_func($callback, $payload, $jaxl);
}
}
}
}
}
return $payload;
}
}
?>
diff --git a/xep/jaxl.0030.php b/xep/jaxl.0030.php
index 4393c52..c2743f3 100644
--- a/xep/jaxl.0030.php
+++ b/xep/jaxl.0030.php
@@ -1,109 +1,109 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP: 0030 Service Discovery
* Version: 2.4
* Url: http://xmpp.org/extensions/xep-0030.html
*/
class JAXL0030 {
public static $ns = array('info'=>'http://jabber.org/protocol/disco#info', 'items'=>'http://jabber.org/protocol/disco#items');
public static function init($jaxl) {
$jaxl->features[] = self::$ns['info'];
$jaxl->features[] = self::$ns['items'];
JAXLXml::addTag('iq', 'identityCategory', '//iq/query/identity/@category');
JAXLXml::addTag('iq', 'identityText', '//iq/query/identity/@text');
JAXLXml::addTag('iq', 'identityName', '//iq/query/identity/@name');
JAXLXml::addTag('iq', 'identityLang', '//iq/query/identity/@xml:lang');
JAXLXml::addTag('iq', 'featureVar', '//iq/query/feature/@var');
// register callbacks
- JAXLPlugin::add('jaxl_get_iq_get', array('JAXL0030', 'handleIq'));
+ $jaxl->addPlugin('jaxl_get_iq_get', array('JAXL0030', 'handleIq'));
}
public static function discoInfo($jaxl, $to, $from, $callback, $node=false) {
$payload = '<query xmlns="'.self::$ns['info'].'"';
if($node) $payload .= ' node="'.$node.'"/>';
else $payload .= '/>';
return XMPPSend::iq($jaxl, 'get', $payload, $to, $from, $callback);
}
public static function discoItems($jaxl, $to, $from, $callback, $node=false) {
$payload = '<query xmlns="'.self::$ns['items'].'"';
if($node) $payload .= ' node="'.$node.'"/>';
else $payload .= '/>';
return XMPPSend::iq($jaxl, 'get', $payload, $to, $from, $callback);
}
public static function handleIq($payload, $jaxl) {
if($payload['queryXmlns'] == self::$ns['info']) {
$xml = '<query xmlns="'.$payload['queryXmlns'].'"';
if(isset($payload['queryNode'])) $xml .= ' node="'.$payload['queryNode'].'"';
$xml .= '>';
$xml .= '<identity xml:lang="'.$jaxl->lang.'"';
$xml .= ' name="'.$jaxl->getName().'"';
$xml .= ' category="'.$jaxl->category.'"';
$xml .= ' type="'.$jaxl->type.'"/>';
foreach($jaxl->features as $feature)
$xml .= '<feature var="'.$feature.'"/>';
$xml .= '</query>';
XMPPSend::iq($jaxl, 'result', $xml, $payload['from'], $payload['to'], false, $payload['id']);
}
else if($payload['queryXmlns'] == self::$ns['items']) {
}
return $payload;
}
}
?>
diff --git a/xep/jaxl.0085.php b/xep/jaxl.0085.php
index 4fca728..d99d70e 100644
--- a/xep/jaxl.0085.php
+++ b/xep/jaxl.0085.php
@@ -1,84 +1,84 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0085: Chat State Notifications
*
* Adds 5 chat state a.k.a 'composing', 'paused', 'active', 'inactive', 'gone'
*/
class JAXL0085 {
public static $ns = 'http://jabber.org/protocol/chatstates';
public static $chatStates = array('composing', 'active', 'inactive', 'paused', 'gone');
public static function init($jaxl) {
$jaxl->features[] = self::$ns;
JAXLXml::addTag('message', 'composing', '//message/composing/@xmlns');
JAXLXml::addTag('message', 'active', '//message/active/@xmlns');
JAXLXml::addTag('message', 'inactive', '//message/inactive/@xmlns');
JAXLXml::addTag('message', 'paused', '//message/paused/@xmlns');
JAXLXml::addTag('message', 'gone', '//message/gone/@xmlns');
- JAXLPlugin::add('jaxl_get_message', array('JAXL0085', 'getMessage'));
+ $jaxl->addPlugin('jaxl_get_message', array('JAXL0085', 'getMessage'));
}
public static function getMessage($payloads, $jaxl) {
foreach($payloads as $key => $payload) {
$payload['chatState'] = false;
foreach(self::$chatStates as $state) {
if(isset($payload[$state]) && $payload[$state] == self::$ns) {
$payload['chatState'] = $state;
}
unset($payload[$state]);
}
$payloads[$key] = $payload;
}
return $payloads;
}
}
?>
diff --git a/xep/jaxl.0092.php b/xep/jaxl.0092.php
index 76a9b9f..6e62c0b 100644
--- a/xep/jaxl.0092.php
+++ b/xep/jaxl.0092.php
@@ -1,81 +1,81 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0092: Software Version
*/
class JAXL0092 {
public static $ns = 'jabber:iq:version';
public static function init($jaxl) {
$jaxl->features[] = self::$ns;
JAXLXml::addTag('iq', 'softwareName', '//iq/query[@xmlns="'.self::$ns.'"]/name');
JAXLXml::addTag('iq', 'softwareVersion', '//iq/query[@xmlns="'.self::$ns.'"]/version');
JAXLXml::addTag('iq', 'softwareOS', '//iq/query[@xmlns="'.self::$ns.'"]/os');
- JAXLPlugin::add('jaxl_get_iq_get', array('JAXL0092', 'getIq'));
+ $jaxl->addPlugin('jaxl_get_iq_get', array('JAXL0092', 'getIq'));
}
public static function getIq($arr, $jaxl) {
if($arr['queryXmlns'] == self::$ns) {
$payload = '<query xmlns="'.self::$ns.'">';
$payload .= '<name>'.$jaxl->getName().'</name>';
$payload .= '<version>'.$jaxl->getVersion().'</version>';
$payload .= '<os>'.PHP_OS.'</os>';
$payload .= '</query>';
return XMPPSend::iq($jaxl, 'result', $payload, $arr['from'], $arr['to'], false, $arr['id']);
}
return $arr;
}
public static function getVersion($jaxl, $fromJid, $toJid, $callback) {
$payload = '<query xmlns="'.self::$ns.'">';
return XMPPSend::iq($jaxl, 'get', $payload, $fromJid, $toJid, $callback);
}
}
?>
diff --git a/xep/jaxl.0114.php b/xep/jaxl.0114.php
index a2b4449..05c2231 100644
--- a/xep/jaxl.0114.php
+++ b/xep/jaxl.0114.php
@@ -1,86 +1,86 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0114: Jabber Component Protocol
*/
class JAXL0114 {
public static function init($jaxl) {
// initialize working parameter for this jaxl instance
$jaxl->comp = array(
'host' => false,
'pass' => false
);
// parse user options
$jaxl->comp['host'] = $jaxl->getConfigByPriority(@$jaxl->config['compHost'], "JAXL_COMPONENT_HOST", $jaxl->comp['host']);
$jaxl->pass['pass'] = $jaxl->getConfigByPriority(@$jaxl->config['compPass'], "JAXL_COMPONENT_PASS", $jaxl->comp['pass']);
// register required callbacks
- JAXLPlugin::add('jaxl_post_start', array('JAXL0114', 'handshake'));
- JAXLPlugin::add('jaxl_pre_handler', array('JAXL0114', 'preHandler'));
+ $jaxl->addPlugin('jaxl_post_start', array('JAXL0114', 'handshake'));
+ $jaxl->addPlugin('jaxl_pre_handler', array('JAXL0114', 'preHandler'));
}
public static function startStream($jaxl, $payload) {
$xml = '<stream:stream xmlns="jabber:component:accept" xmlns:stream="http://etherx.jabber.org/streams" to="'.$jaxl->comp['host'].'">';
$jaxl->sendXML($xml);
}
public static function handshake($id, $jaxl) {
$hash = strtolower(sha1($id.$jaxl->comp['pass']));
$xml = '<handshake>'.$hash.'</handshake>';
$jaxl->sendXML($xml);
}
public static function preHandler($xml, $jaxl) {
if($xml == '<handshake/>') {
$xml = '';
JAXLPlugin::execute('jaxl_post_handshake', false, $jaxl);
}
return $xml;
}
}
?>
diff --git a/xep/jaxl.0124.php b/xep/jaxl.0124.php
index 7b30929..6231de9 100644
--- a/xep/jaxl.0124.php
+++ b/xep/jaxl.0124.php
@@ -1,254 +1,254 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0124: Bosh Implementation
* Maintain various attributes like rid, sid across requests
*/
class JAXL0124 {
private static $buffer = array();
private static $sess = false;
public static function init($jaxl) {
// initialize working parameters for this jaxl instance
$jaxl->bosh = array(
'host' => 'localhost',
'port' => 5280,
'suffix'=> 'http-bind',
'out' => true,
'outheaders' => 'Content-type: application/json',
'cookie'=> array(
'ttl' => 3600,
'path' => '/',
'domain'=> false,
'https' => false,
'httponly' => true
),
'hold' => '1',
'wait' => '30',
'polling' => '0',
'version' => '1.6',
'xmppversion' => '1.0',
'secure'=> true,
'content' => 'text/xml; charset=utf-8',
'headers' => array('Accept-Encoding: gzip, deflate','Content-Type: text/xml; charset=utf-8'),
'xmlns' => 'http://jabber.org/protocol/httpbind',
'xmlnsxmpp' => 'urn:xmpp:xbosh',
'url' => 'http://localhost:5280/http-bind'
);
// parse user options
$jaxl->bosh['host'] = $jaxl->getConfigByPriority(@$jaxl->config['boshHost'], "JAXL_BOSH_HOST", $jaxl->bosh['host']);
$jaxl->bosh['port'] = $jaxl->getConfigByPriority(@$jaxl->config['boshPort'], "JAXL_BOSH_PORT", $jaxl->bosh['port']);
$jaxl->bosh['suffix'] = $jaxl->getConfigByPriority(@$jaxl->config['boshSuffix'], "JAXL_BOSH_SUFFIX", $jaxl->bosh['suffix']);
$jaxl->bosh['out'] = $jaxl->getConfigByPriority(@$jaxl->config['boshOut'], "JAXL_BOSH_OUT", $jaxl->bosh['out']);
$jaxl->bosh['url'] = "http://".$jaxl->bosh['host'].":".$jaxl->bosh['port']."/".$jaxl->bosh['suffix']."/";
// cookie params
$jaxl->bosh['cookie']['ttl'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieTTL'], "JAXL_BOSH_COOKIE_TTL", $jaxl->bosh['cookie']['ttl']);
$jaxl->bosh['cookie']['path'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookiePath'], "JAXL_BOSH_COOKIE_PATH", $jaxl->bosh['cookie']['path']);
$jaxl->bosh['cookie']['domain'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieDomain'], "JAXL_BOSH_COOKIE_DOMAIN", $jaxl->bosh['cookie']['domain']);
$jaxl->bosh['cookie']['https'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieHTTPS'], "JAXL_BOSH_COOKIE_HTTPS", $jaxl->bosh['cookie']['https']);
$jaxl->bosh['cookie']['httponly'] = $jaxl->getConfigByPriority(@$jaxl->config['boshCookieHTTPOnly'], "JAXL_BOSH_COOKIE_HTTP_ONLY", $jaxl->bosh['cookie']['httponly']);
session_set_cookie_params(
$jaxl->bosh['cookie']['ttl'],
$jaxl->bosh['cookie']['path'],
$jaxl->bosh['cookie']['domain'],
$jaxl->bosh['cookie']['https'],
$jaxl->bosh['cookie']['httponly']
);
session_start();
- JAXLPlugin::add('jaxl_post_bind', array('JAXL0124', 'postBind'));
- JAXLPlugin::add('jaxl_send_xml', array('JAXL0124', 'wrapBody'));
- JAXLPlugin::add('jaxl_pre_handler', array('JAXL0124', 'preHandler'));
- JAXLPlugin::add('jaxl_post_handler', array('JAXL0124', 'postHandler'));
- JAXLPlugin::add('jaxl_send_body', array('JAXL0124', 'sendBody'));
+ $jaxl->addPlugin('jaxl_post_bind', array('JAXL0124', 'postBind'));
+ $jaxl->addPlugin('jaxl_send_xml', array('JAXL0124', 'wrapBody'));
+ $jaxl->addPlugin('jaxl_pre_handler', array('JAXL0124', 'preHandler'));
+ $jaxl->addPlugin('jaxl_post_handler', array('JAXL0124', 'postHandler'));
+ $jaxl->addPlugin('jaxl_send_body', array('JAXL0124', 'sendBody'));
self::loadSession($jaxl);
}
public static function postHandler($payload, $jaxl) {
if(!$jaxl->bosh['out']) return $payload;
$payload = json_encode(self::$buffer);
$jaxl->log("[[BoshOut]]\n".$payload, 5);
header($jaxl->bosh['outheaders']);
echo $payload;
exit;
}
public static function postBind($payload, $jaxl) {
$jaxl->bosh['jid'] = $jaxl->jid;
$_SESSION['auth'] = true;
return;
}
public static function out($payload) {
self::$buffer[] = $payload;
}
public static function loadSession($jaxl) {
$jaxl->bosh['rid'] = isset($_SESSION['rid']) ? (string) $_SESSION['rid'] : rand(1000, 10000);
$jaxl->bosh['sid'] = isset($_SESSION['sid']) ? (string) $_SESSION['sid'] : false;
$jaxl->lastid = isset($_SESSION['id']) ? $_SESSION['id'] : $jaxl->lastid;
$jaxl->jid = isset($_SESSION['jid']) ? $_SESSION['jid'] : $jaxl->jid;
$jaxl->log("Loading session data\n".json_encode($_SESSION), 5);
}
public static function saveSession($xml, $jaxl) {
if($_SESSION['auth'] === true) {
$_SESSION['rid'] = isset($jaxl->bosh['rid']) ? $jaxl->bosh['rid'] : false;
$_SESSION['sid'] = isset($jaxl->bosh['sid']) ? $jaxl->bosh['sid'] : false;
$_SESSION['jid'] = $jaxl->jid;
$_SESSION['id'] = $jaxl->lastid;
if($jaxl->bosh['out'])
session_write_close();
if(self::$sess && $jaxl->bosh['out']) {
list($body, $xml) = self::unwrapBody($xml);
$jaxl->log("[[".$_REQUEST['jaxl']."]] Auth complete, sync now\n".json_encode($_SESSION), 5);
return self::out(array('jaxl'=>'jaxl', 'xml'=>urlencode($xml)));
}
else {
self::$sess = true;
$jaxl->log("[[".$_REQUEST['jaxl']."]] Auth complete, commiting session now\n".json_encode($_SESSION), 5);
}
}
else {
$jaxl->log("[[".$_REQUEST['jaxl']."]] Not authed yet, Not commiting session\n".json_encode($_SESSION), 5);
}
return $xml;
}
public static function wrapBody($xml, $jaxl) {
$body = trim($xml);
if(substr($body, 1, 4) != 'body') {
$body = '';
$body .= '<body rid="'.++$jaxl->bosh['rid'].'"';
$body .= ' sid="'.$jaxl->bosh['sid'].'"';
$body .= ' xmlns="http://jabber.org/protocol/httpbind">';
$body .= $xml;
$body .= "</body>";
$_SESSION['rid'] = $jaxl->bosh['rid'];
}
return $body;
}
public static function sendBody($xml, $jaxl) {
$xml = self::saveSession($xml, $jaxl);
if($xml != false) {
$jaxl->log("[[XMPPSend]] body\n".$xml, 4);
$payload = JAXLUtil::curl($jaxl->bosh['url'], 'POST', $jaxl->bosh['headers'], $xml);
// curl error handling
if($payload['errno'] != 0) {
$log = "[[JAXL0124]] Curl errno ".$payload['errno']." encountered";
switch($payload['errno']) {
case 7:
$log .= ". Failed to connect with ".$jaxl->bosh['url'];
break;
case 52:
$log .= ". Empty response rcvd from bosh endpoint";
break;
default:
break;
}
$jaxl->log($log);
}
$payload = $payload['content'];
$jaxl->handler($payload);
}
return $xml;
}
public static function unwrapBody($payload) {
if(substr($payload, -2, 2) == "/>") preg_match_all('/<body (.*?)\/>/smi', $payload, $m);
else preg_match_all('/<body (.*?)>(.*)<\/body>/smi', $payload, $m);
if(isset($m[1][0])) $body = "<body ".$m[1][0].">";
else $body = "<body>";
if(isset($m[2][0])) $payload = $m[2][0];
else $payload = '';
return array($body, $payload);
}
public static function preHandler($payload, $jaxl) {
if(substr($payload, 1, 4) == "body") {
list($body, $payload) = self::unwrapBody($payload);
if($payload == '') {
if($_SESSION['auth'] === 'disconnect') {
$_SESSION['auth'] = false;
JAXLPlugin::execute('jaxl_post_disconnect', $body, $jaxl);
}
else {
JAXLPlugin::execute('jaxl_get_empty_body', $body, $jaxl);
}
}
if($_SESSION['auth'] === 'connect') {
$arr = $jaxl->xml->xmlize($body);
if(isset($arr["body"]["@"]["sid"])) {
$_SESSION['auth'] = false;
$_SESSION['sid'] = $arr["body"]["@"]["sid"];
$jaxl->bosh['sid'] = $arr["body"]["@"]["sid"];
}
}
}
return $payload;
}
}
?>
diff --git a/xep/jaxl.0184.php b/xep/jaxl.0184.php
index 1a46e9d..ed792e6 100644
--- a/xep/jaxl.0184.php
+++ b/xep/jaxl.0184.php
@@ -1,79 +1,79 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0184 Message Receipts
*/
class JAXL0184 {
public static $ns = 'urn:xmpp:receipts';
public static function init($jaxl) {
$jaxl->features[] = self::$ns;
JAXLXml::addTag('message', 'request', '//message/request/@xmlns');
JAXLXml::addTag('message', 'received', '//message/received/@xmlns');
JAXLXml::addTag('message', 'receivedId', '//message/received/@id');
- JAXLPlugin::add('jaxl_get_message', array('JAXL0184', 'handleMessage'));
+ $jaxl->addPlugin('jaxl_get_message', array('JAXL0184', 'handleMessage'));
}
public static function requestReceipt() {
$payload = '<request xmlns="'.self::$ns.'"/>';
return $payload;
}
public static function handleMessage($payloads, $jaxl) {
foreach($payloads as $payload) {
if($payload['request'] == self::$ns) {
$child = array();
$child['payload'] = '<received xmlns="'.self::$ns.'" id="'.$payload['id'].'"/>';
XMPPSend::message($jaxl, $payload['from'], $payload['to'], $child, false, false);
}
}
return $payloads;
}
}
?>
diff --git a/xep/jaxl.0199.php b/xep/jaxl.0199.php
index b370b22..22850ba 100644
--- a/xep/jaxl.0199.php
+++ b/xep/jaxl.0199.php
@@ -1,86 +1,86 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0199: XMPP Ping
*/
class JAXL0199 {
public static $ns = 'urn:xmpp:ping';
public static function init($jaxl) {
$jaxl->features[] = self::$ns;
$jaxl->pingInterval = 0;
$jaxl->pingInterval = $jaxl->getConfigByPriority($jaxl->config['pingInterval'], "JAXL_PING_INTERVAL", $jaxl->pingInterval);
if($jaxl->pingInterval > 0)
JAXLCron::add(array('JAXL0199', 'ping'), $jaxl->pingInterval, $jaxl->domain, $jaxl->jid, array('JAXL0199', 'pinged'));
JAXLXml::addTag('iq', 'ping', '//iq/ping/@xmlns');
- JAXLPlugin::add('jaxl_get_iq_get', array('JAXL0199', 'handleIq'));
+ $jaxl->addPlugin('jaxl_get_iq_get', array('JAXL0199', 'handleIq'));
}
public static function handleIq($payload, $jaxl) {
if($payload['ping'] == self::$ns)
return XMPPSend::iq($jaxl, 'result', false, $payload['from'], $payload['to'], false, $payload['id']);
return $payload;
}
public static function ping($jaxl, $to, $from, $callback) {
if($jaxl->auth) {
$payload = "<ping xmlns='urn:xmpp:ping'/>";
return XMPPSend::iq($jaxl, 'get', $payload, $to, $from, $callback);
}
}
public static function pinged($payload, $jaxl) {
if($payload['type'] == 'error' && $payload['errorCode'] == 501 && $payload['errorCondition'] == 'feature-not-implemented') {
$jaxl->log("[[JAXL0199]] Server doesn't support ping feature, disabling cron tab for periodic ping...");
JAXLCron::delete(array('JAXL0199', 'ping'), $jaxl->pingInterval);
return $payload;
}
$jaxl->log("[[JAXL0199]] Rcvd ping response from the server...");
}
}
?>
diff --git a/xep/jaxl.0202.php b/xep/jaxl.0202.php
index 84d6d03..6e914b9 100644
--- a/xep/jaxl.0202.php
+++ b/xep/jaxl.0202.php
@@ -1,79 +1,79 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xep
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* XEP-0202 : Entity Time
*/
class JAXL0202 {
public static $ns = 'urn:xmpp:time';
public static function init($jaxl) {
$jaxl->features[] = self::$ns;
JAXLXml::addTag('iq', 'time', '//iq/time/@xmlns');
JAXLXml::addTag('iq', 'timeTZO', '//iq/time/tzo');
JAXLXml::addTag('iq', 'timeUTC', '//iq/time/utc');
- JAXLPlugin::add('jaxl_get_iq_get', array('JAXL0202', 'handleIq'));
+ $jaxl->addPlugin('jaxl_get_iq_get', array('JAXL0202', 'handleIq'));
}
public static function getEntityTime($jaxl, $to, $from, $callback) {
$payload = '<time xmlns="'.self::$ns.'"/>';
return XMPPSend::iq($jaxl, 'get', $payload, $to, $from, $callback);
}
public static function handleIq($payload, $jaxl) {
if($payload['time'] == self::$ns) {
$entityTime = '<time xmlns="'.self::$ns.'">';
$entityTime .= '<tzo>'.date('P').'</tzo>';
$entityTime .= '<utc>'.date('Y-m-d').'T'.date('H:i:s').'Z</utc>';
$entityTime .= '</time>';
return XMPPSend::iq($jaxl, 'result', $entityTime, $payload['from'], $payload['to'], false, $payload['id']);
}
return $payload;
}
}
?>
diff --git a/xmpp/xmpp.send.php b/xmpp/xmpp.send.php
index f79e68e..4922ed0 100644
--- a/xmpp/xmpp.send.php
+++ b/xmpp/xmpp.send.php
@@ -1,206 +1,206 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage xmpp
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
// include required classes
jaxl_require(array(
'JAXLPlugin',
'JAXLUtil',
'JAXLog'
));
/**
* XMPP Send Class
* Provide methods for sending all kind of xmpp stream and stanza's
*/
class XMPPSend {
public static function startStream($jaxl) {
$xml = '<stream:stream xmlns:stream="http://etherx.jabber.org/streams" version="1.0" xmlns="jabber:client" to="'.$jaxl->domain.'" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">';
return $jaxl->sendXML($xml);
}
public static function endStream($jaxl) {
$xml = '</stream:stream>';
return $jaxl->sendXML($xml, true);
}
public static function startTLS($jaxl) {
$xml = '<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>';
return $jaxl->sendXML($xml);
}
public static function startAuth($jaxl) {
$type = $jaxl->authType;
$xml = '<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="'.$type.'">';
switch($type) {
case 'DIGEST-MD5':
break;
case 'PLAIN':
$xml .= base64_encode("\x00".$jaxl->user."\x00".$jaxl->pass);
break;
case 'ANONYMOUS':
break;
case 'X-FACEBOOK-PLATFORM':
break;
case 'CRAM-MD5':
break;
case 'SCRAM-SHA-1':
$xml .= base64_encode("n,,n=".$jaxl->user.",r=".base64_encode(JAXLUtil::generateNonce()));
break;
default:
break;
}
$xml .= '</auth>';
$jaxl->log("[[XMPPSend]] Performing Auth type: ".$type);
return $jaxl->sendXML($xml);
}
public static function startSession($jaxl, $callback) {
$payload = '<session xmlns="urn:ietf:params:xml:ns:xmpp-session"/>';
return self::iq($jaxl, "set", $payload, $jaxl->domain, false, $callback);
}
public static function startBind($jaxl, $callback) {
$payload = '<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">';
$payload .= '<resource>'.$jaxl->resource.'</resource>';
$payload .= '</bind>';
return self::iq($jaxl, "set", $payload, false, false, $callback);
}
public static function message($jaxl, $to, $from=false, $child=false, $type='normal', $id=false, $ns='jabber:client') {
$xml = '';
if(is_array($to)) {
foreach($to as $key => $value) {
$xml .= self::prepareMessage($jaxl, $to[$key], $from[$key], $child[$key], $type[$key], $id[$key], $ns[$key]);
}
}
else {
$xml .= self::prepareMessage($jaxl, $to, $from, $child, $type, $id, $ns);
}
JAXLPlugin::execute('jaxl_send_message', $xml, $jaxl);
return $jaxl->sendXML($xml);
}
private static function prepareMessage($jaxl, $to, $from, $child, $type, $id, $ns) {
$xml = '<message';
if($from) $xml .= ' from="'.$from.'"';
$xml .= ' to="'.htmlspecialchars($to).'"';
if($type) $xml .= ' type="'.$type.'"';
if($id) $xml .= ' id="'.$id.'"';
$xml .= '>';
if($child) {
if(isset($child['subject'])) $xml .= '<subject>'.JAXLUtil::xmlentities($child['subject']).'</subject>';
if(isset($child['body'])) $xml .= '<body>'.JAXLUtil::xmlentities($child['body']).'</body>';
if(isset($child['thread'])) $xml .= '<thread>'.$child['thread'].'</thread>';
if(isset($child['payload'])) $xml .= $child['payload'];
}
$xml .= '</message>';
return $xml;
}
public static function presence($jaxl, $to=false, $from=false, $child=false, $type=false, $id=false, $ns='jabber:client') {
$xml = '';
if(is_array($to)) {
foreach($to as $key => $value) {
$xml .= self::preparePresence($jaxl, $to[$key], $from[$key], $child[$key], $type[$key], $id[$key], $ns[$key]);
}
}
else {
$xml .= self::preparePresence($jaxl, $to, $from, $child, $type, $id, $ns);
}
JAXLPlugin::execute('jaxl_send_presence', $xml, $jaxl);
return $jaxl->sendXML($xml);
}
private static function preparePresence($jaxl, $to, $from, $child, $type, $id, $ns) {
$xml = '<presence';
if($type) $xml .= ' type="'.$type.'"';
if($from) $xml .= ' from="'.$from.'"';
if($to) $xml .= ' to="'.htmlspecialchars($to).'"';
if($id) $xml .= ' id="'.$id.'"';
$xml .= '>';
if($child) {
if(isset($child['show'])) $xml .= '<show>'.$child['show'].'</show>';
if(isset($child['status'])) $xml .= '<status>'.JAXLUtil::xmlentities($child['status']).'</status>';
if(isset($child['priority'])) $xml .= '<priority>'.$child['priority'].'</priority>';
if(isset($child['payload'])) $xml .= $child['payload'];
}
$xml.= '</presence>';
return $xml;
}
public static function iq($jaxl, $type, $payload=false, $to=false, $from=false, $callback=false, $id=false, $ns='jabber:client') {
if($type == 'get' || $type == 'set') {
$id = $jaxl->getId();
- if($callback) JAXLPlugin::add('jaxl_get_iq_'.$id, $callback);
+ if($callback) $jaxl->addPlugin('jaxl_get_iq_'.$id, $callback);
}
$types = array('get','set','result','error');
$xml = '';
$xml .= '<iq';
$xml .= ' type="'.$type.'"';
$xml .= ' id="'.$id.'"';
if($to) $xml .= ' to="'.$to.'"';
if($from) $xml .= ' from="'.$from.'"';
$xml .= '>';
if($payload) $xml .= $payload;
$xml .= '</iq>';
$jaxl->sendXML($xml);
if($type == 'get' || $type == 'set') return $id;
else return true;
}
}
?>
|
jaxl/JAXL | 7440dbd6c6ee42a0bb816efe80a25fe6bd7b9056 | JAXLPlugin can now register a callback for a dedicated jaxl instance in a multi-instance jaxl application. Class functionality remains backward compatible. | diff --git a/core/jaxl.plugin.php b/core/jaxl.plugin.php
index 1de9d69..70959cf 100644
--- a/core/jaxl.plugin.php
+++ b/core/jaxl.plugin.php
@@ -1,112 +1,120 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl Plugin Framework
*/
class JAXLPlugin {
/**
* Registry of all registered hooks
*/
public static $registry = array();
/**
* Register callback on hook
*
* @param string $hook
* @param string|array $callback A valid callback inside your application code
* @param integer $priority (>0) When more than one callbacks is attached on hook, they are called in priority order or which ever was registered first
+ * @param integer $uid random id $jaxl->uid of connected Jaxl instance, $uid=0 means callback registered for all connected instances
*/
- public static function add($hook, $callback, $priority=10) {
- if(!isset(self::$registry[$hook]))
- self::$registry[$hook] = array();
+ public static function add($hook, $callback, $priority=10, $uid=0) {
+ if(!isset(self::$registry[$uid]))
+ self::$registry[$uid] = array();
+
+ if(!isset(self::$registry[$uid][$hook]))
+ self::$registry[$uid][$hook] = array();
- if(!isset(self::$registry[$hook][$priority]))
- self::$registry[$hook][$priority] = array();
+ if(!isset(self::$registry[$uid][$hook][$priority]))
+ self::$registry[$uid][$hook][$priority] = array();
- array_push(self::$registry[$hook][$priority], $callback);
+ array_push(self::$registry[$uid][$hook][$priority], $callback);
}
/**
* Removes a previously registered callback on hook
*
* @param string $hook
* @param string|array $callback
* @param integer $priority
+ * @param integer $uid random id $jaxl->uid of connected Jaxl instance, $uid=0 means callback registered for all connected instances
*/
- public static function remove($hook, $callback, $priority=10) {
- if(($key = array_search($callback, self::$registry[$hook][$priority])) !== FALSE)
- unset(self::$registry[$hook][$priority][$key]);
+ public static function remove($hook, $callback, $priority=10, $uid=0) {
+ if(($key = array_search($callback, self::$registry[$uid][$hook][$priority])) !== FALSE)
+ unset(self::$registry[$uid][$hook][$priority][$key]);
- if(count(self::$registry[$hook][$priority]) == 0)
- unset(self::$registry[$hook][$priority]);
+ if(count(self::$registry[$uid][$hook][$priority]) == 0)
+ unset(self::$registry[$uid][$hook][$priority]);
- if(count(self::$registry[$hook]) == 0)
- unset(self::$registry[$hook]);
+ if(count(self::$registry[$uid][$hook]) == 0)
+ unset(self::$registry[$uid][$hook]);
}
/*
* Method calls previously registered callbacks on executing hook
*
* @param string $hook
* @param mixed $payload
* @param object $jaxl
* @param array $filter
*/
public static function execute($hook, $payload=null, $jaxl=false, $filter=false) {
- if(isset(self::$registry[$hook]) && count(self::$registry[$hook]) > 0) {
- foreach(self::$registry[$hook] as $priority) {
- foreach($priority as $callback) {
- if($filter === false || (is_array($filter) && in_array($callback[0], $filter))) {
- $payload = call_user_func($callback, $payload, $jaxl);
+ $uids = array($jaxl->uid, 0);
+ foreach($uids as $uid) {
+ if(isset(self::$registry[$uid][$hook]) && count(self::$registry[$uid][$hook]) > 0) {
+ foreach(self::$registry[$uid][$hook] as $priority) {
+ foreach($priority as $callback) {
+ if($filter === false || (is_array($filter) && in_array($callback[0], $filter))) {
+ $payload = call_user_func($callback, $payload, $jaxl);
+ }
}
}
}
}
return $payload;
}
}
?>
|
jaxl/JAXL | f5d9653dd5eb388b91861b89c5dcb5c40cfca06d | JAXLPlugin can now register a callback for a dedicated jaxl instance in a multi-instance jaxl application. Class functionality remains backward compatible. | diff --git a/CHANGELOG b/CHANGELOG
index 6e42f7d..d064813 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,301 +1,303 @@
version 2.1.2
-------------
+- JAXLPlugin can now register a callback for a dedicated jaxl instance in a multi-instance jaxl application
+ Class functionality remains backward compatible.
- JAXLog class now also dump connect instance uid per log line
- XMPP instance iq id now defaults to a random value between 1 and 9
Also added jaxl_get_id event hook for apps to customize iq id for the connected Jaxl instance
Also as compared to default numeric iq id, Jaxl core now uses hex iq id's
- Every jaxl instance per php process id now generate it's own unique id JAXL::$uid
- Jaxl core doesn't go for a session if it's optional as indicated by the xmpp server
- Fixed boshChat postBind issues as reported by issue#26 (http://code.google.com/p/jaxl/issues/detail?id=26)
- Fixed jaxl constructor config read warning and XEP 0114 now make use of JAXL::getConfigByPriority method
- Removed warning while reading user config inside Jaxl constructor
Upgraded Jaxl Parser class which was malfunctioning on CentOS PHP 5.1.6 (cli)
- Added bosh error response handling and appropriate logging inside XMPP over Bosh core files
- Code cleanup inside jaxl logger class.
Fixed getConfigByPriority method which was malfunctioning in specific cases
- JAXLog class now using inbuild php function (error_log)
- Checking in first version of XEP-0016 (Privacy Lists), XEP-0055 (Jabber Search), XEP-0077 (In-Band Registration), XEP-0144 (Roster Item Exchange), XEP-0153 (vCard-Based Avatars), XEP-0237 (Roster Versioning)
- On auth faliure core doesn't throw exception since XMPP over Bosh apps are not held inside a try catch block (a better fix may be possible in future)
- XMPP over BOSH xep wasn't passing back Jaxl instance obj for jaxl_post_disconnect hook, fixed that for clean disconnect
- Jaxl core attempts to create log and pid files if doesn't already exists
Also instead of die() core throws relevant exception message wherever required
XMPP base classes throws relevant exception with message wherever required
- First commit of JAXLException class. JAXL core now uses JAXLException
- Jaxl constructor dies if logPath, pidPath and tmpPath doesn't exists on the system
- Core updates JAXL::resource after successful binding to match resource assigned by the connecting server
- Updated echobot sample example to make use of autoSubscribe core feature
Also registers callback for jaxl_post_subscription_request and jaxl_post_subscription_accept hooks
- Updated echobot and boshchat application to use in memory roster cache maintained by Jaxl core.
App files should register callback on hook jaxl_post_roster_update to get notified everytime local roster cache is updated
- Added provision for local roster cache management inside Jaxl core.
Retrived roster lists are cached in memory (see updated echobot.php sample example).
Also added provision for presence tracking (JAXL::trackPresence).
If enabled Jaxl core keep a track of jid availability and update local roster cache accordingly.
Also added provision for auto-accept subscription (JAXL::autoSubscribe).
- Removed XMPP::isConnected variable which used to tell status of connected socket stream.
This is equivalent to checking XMPP:stream variable for true/false
- Added a (kind of) buggy support for '/xml()' inside parser xpath
- If Jaxl instance has being configured for auto periodic ping (XEP-0199), pings are holded till auth completion.
Also if server responds 'feature-not-implemented' for first ping XEP-0199 automatically deleted periodic ping cron tab
- Corrected handling of error type iq stanza's (removed jaxl_get_iq_error hook)
- Added iq error code xpath inside JAXLXml class
- Completed missing JAXLCron::delete method for removing a previously registered cron tab
- Checking in first version of XEP-0049 (Private XML Storage) (not yet tested)
- Checking in first version of XEP-0191 (Simple Communication Blocking) (not yet tested)
- Added JAXL_PING_INTERVAL configuration option inside jaxl.ini
- XEP-0199 (XMPP Ping) can now automatically ping the connected server periodically for keeping connection alive on long running bots
(see echobot.php sample app for usage)
- Updated JAXLCron::add method to accept a number of arguments while adding bckgrnd jobs
These list of arguments is passed back to the application method
- Updated IQ handling inside XEP-0202 which wasn't returning iq stanza back resulting in no ping/pong
- Updated echobot to show usage of JAXL::discoItems and JAXL::discoInfo inside application code
- Added tagMap xpath for service identity and feature nodes in service discovery resultset
- JAXL core now auto includes XEP-0128 along with XEP-0030 on startup.
Also added two methods JAXL::discoItems and JAXL::discoInfo for service discovery
- Checking in first version of XEP-0128 (Service Discovery Extension)
- Fixed bug where message and presence stanza builder were not using passed id value as attribute
- Removed jaxl_pre_curl event hook which was only used internally by XEP-0124
- Jaxl now shutdown gracefully is encryption is required and openssl PHP module is not loaded in the environment
- For every registered callback on XMPP hooks, callback'd method will receive two params.
A payload and reference of Jaxl instance for whom XMPP event has occured.
Updated sample application code to use passed back Jaxl instance reference instead of global jaxl variable.
- As a library convention XEP's exposing user space configuration parameters via JAXL constructor SHOULD utilize JAXL::getConfigByPriority method
Added JAXL_TMP_PATH option inside jaxl.ini
- Jaxl::tmp is now Jaxl::tmpPath. Also added Jaxl config param to specify custom tmp path location
Jaxl client also self detect the IP of the host it is running upon (to be used by STUN/TURN utilities in Jingle negotitation)
- Removed JAXLUtil::includePath and JAXLUtil::getAppFilePath methods which are now redundant after removing jaxl.ini and jaxl.conf from lib core
- Removed global defines JAXL_BASE_PATH, JAXL_APP_BASE_PATH, JAXL_BOSH_APP_ABS_PATH from inside jaxl.ini (No more required by apps to specify these values)
- Removing env/jaxl.php and env/jaxl.conf (were required if you run your apps using `jaxl` command line utility)
Updated env/jaxl.ini so that projects can now directly include their app setting via jaxl.ini (before including core/jaxl.class.php)
- Added JAXL::bareJid public variable for usage inside applications.
XMPP base class now return bool on socket connect completion (used by PHPUnit test cases)
- Removing build.sh file from library for next release
Users should simply download, extract, include and write their app code without caring about the build script from 2.1.2 release
- As a library convention to include XEP's use JAXL::requires() method, while to include any core/ or xmpp/ base class use jaxl_require() method.
Updated library code and xep's to adhere to this convention.
Jaxl instance now provide a system specific /tmp folder location accessible by JAXL::tmp
- Removed JAXL_NAME and JAXL_VERSION constants.
Instead const variables are now defined per instance accessible by getName() and getVersion() methods.
Updated XEP-0030,0092,0115 to use the same
- Moved indivisual XEP's working parameter (0114,0124) from JAXL core class to XEP classes itself.
XEP's make use of JAXL::config array for parsing user options.
- Added JAXL_COMPONENT_PASS option inside jaxl.ini. Updated build.sh with new /app file paths.
Updated XEP-0114,0124,0206 to use array style configs as defined inside JAXL class
- Removed dependency upon jaxl.ini from all sample applications.
First checkin of sample sendMessage.php app.
- Config parameters for XEP's like 0114 and 0206 are now saved as an array inside JAXL class (later on they will be moved inside respective XEP's).
Added constructor config option to pre-choose an auth mechanism to be performed
if an auth mech is pre-chosen app files SHOULD not register callback for jaxl_get_auth_mech hook.
Bosh cookie settings can now be passed along with Jaxl constructor.
Added support for publishing vcard-temp:x:update node along with presence stanzas.
Jaxl instance can run in 3 modes a.k.a. stream,component and bosh mode
applications should use JAXL::startCore('mode') to configure instance for a specific mode.
- Removed redundant NS variable from inside XEP-0124
- Moved JAXLHTTPd setting defines inside the class (if gone missing CPU usage peaks to 100%)
- Added jaxl_httpd_pre_shutdown, jaxl_httpd_get_http_request, jaxl_httpd_get_sock_request event hooks inside JAXLHTTPd class
- Added JAXLS5B path (SOCKS5 implementation) inside jaxl_require method
- Removed all occurance of JAXL::$action variable from /core and /xep class files
- Updated boshChat and boshMUChat sample application which no longer user JAXL::$action variable inside application code
- Updated preFetchBOSH and preFetchXMPP sample example.
Application code don't need any JAXL::$action variable now
Neither application code need to define JAXL_BASE_PATH (optional from now on)
- JAXL core and XEP-0206 have no relation and dependency upon JAXL::$action variable now.
- Deprecated jaxl_get_body hook which was only for XEP-0124 working.
Also cleaned up XEP-0124 code by removing processBody method which is now handled inside preHandler itself.
- Defining JAXL_BASE_PATH inside application code made optional.
Developers can directly include /path/to/jaxl/core/jaxl.class.php and start writing applications.
Also added a JAXL::startCore() method (see usage in /app/preFetchXMPP.php).
Jaxl magic method for calling XEP methods now logs a warning inside jaxl.log if XEP doesn't exists in the environment
- Added tag map for XMPP message thread and subject child elements
- Fixed typo where in case of streamError proper description namespace was not parsed/displayed
- Disabled BOSH session close if application is running in boshOut=false mode
Suggested by MOVIM dev team who were experiencing loss of session data on end of script
- JAXL::log method 2nd parameter now defaults to logLevel=1 (passing 2nd param is now optional)
- Fixed XPath for iq stanza error condition and error NS extraction inside jaxl.parser.class
- First checkin of XEP-0184 Message Receipts
- Added support for usage of name() xpath function inside tag maps of JAXLXml class.
Also added some documentation for methods available inside JAXLXml class
- Fixed JAXLPlugin::remove method to properly remove and manage callback registry.
Also added some documentation for JAXLPlugin class methods
- Added JAXL contructor config option to disable BOSH module auto-output behaviour.
This is utilized inside app/preFetchBOSH.php sample example
- First checkin of sample application code pre-fetching XMPP/Jabber data for web page population using BOSH XEP
- Added a sample application file which can be used to pre-fetch XMPP/Jabber data for a webpage without using BOSH XEP or Ajax requests
As per the discussion on google groups (http://bit.ly/aKavZB) with MOVIM team
- JAXL library is now $jaxl independent, you can use anything like $var = new JAXL(); instance your applications now
JAXLUtil::encryptPassword now accepts username/password during SASL auth.
Previously it used to auto detect the same from JAXL instance, now core has to manually pass these param
- Added JAXL::startHTTPd method with appropriate docblock on how to convert Jaxl instance into a Jaxl socket (web) server.
Comments also explains how to still maintaining XMPP communication in the background
- Updated JAXLHTTPd class to use new constants inside jaxl.ini
- Added jaxl_get_stream_error event handler.
Registered callback methods also receive array form of received XMPP XML stanza
- Connecting Jaxl instance now fallback to default value 'localhost' for host,domain,boshHost,boshPort,boshSuffix
If these values are not configured either using jaxl.ini constants or constructor
- Provided a sendIQ method per JAXL instance.
Recommended that applications and XEP's should directly use this method for sending <iq/> type stanza
DONOT use XMPPSend methods inside your application code from here on
- Added configuration options for JAXL HTTPd server and JAXL Bosh Component Manager inside jaxl.ini
- Fixed type in XEP-0202 (Entity Time). XEP was not sending <iq/> id in response to get request
- Jaxl library is now phpdocs ready. Added extended documentation for JAXL core class, rest to be added
- All core classes inside core/, xmpp/ and xep/ folder now make use of jaxl->log method
JAXL Core constructor are now well prepared so that inclusion of jaxl.ini is now optional
Application code too should use jaxl->log instead of JAXLog::log method for logging purpose
- Reshuffled core instance paramaters between JAXL and XMPP class
Also Jaxl core now logs at level 1 instead of 0 (i.e. all logs goes inside jaxl.log and not on console)
- JAXL class now make use of endStream method inside XMPP base class while disconnecting.
Also XMPPSend::endStream now forces xmpp stanza delivery (escaping JAXL internal buffer)
http://code.google.com/p/jaxl/issues/detail?id=23
- Added endStream method inside XMPP base class and startSession,startBind methods inside XMPPSend class
XMPP::sendXML now accepts a $force parameter for escaping XMPP stanza's from JAXL internal buffer
- Updated the way Jaxl core calls XEP 0115 method (entity caps) to match documentation
XEP method's should accept jaxl instance as first paramater
- First checkin of PEP (Personal Eventing), User Location, User Mood, User Activity and User Tune XEP's
- Completed methods discoFeatures, discoNodes, discoNodeInfo, discoNodeMeta and discoNodeItems in PubSub XEP
- Hardcoded client category, type, lang and name. TODO: Make them configurable in future
- Cleaned up XEP 0030 (Service Discovery) and XEP 0115 (Entity Capabilities)
- Updated XMPP base class to use performance configuration parameters (now customizable with JAXL constructor)
- jaxl.conf will be removed from jaxl core in future, 1st step towards this goal
- Moved bulk of core configs from jaxl.conf
- Added more configuration options relating to client performance e.g. getPkts, getPktSize etc
- Fixed client mode by detecting sapi type instead of $_REQUEST['jaxl'] variable
- Now every implemented XEP should have an 'init' method which will accept only one parameter (jaxl instance itself)
- Jaxl core now converts transmitted stanza's into xmlentities (http://code.google.com/p/jaxl/issues/detail?id=22)
- Created a top level 'patch' folder which contains various patches sent by developers using 'git diff > patch' utility
- Fixed typo in namespace inside 0030 (thanks to Thomas Baquet for the patch)
- First checkin of PubSub XEP (untested)
- Indented build.sh and moved define's from top of JAXLHTTPd class to jaxl.ini
- Added JAXLHTTPd inside Jaxl core (a simple socket select server)
- Fixed sync of background iq and other stanza requests with browser ajax calls
- Updated left out methods in XMPP over BOSH xep to accept jaxl instance as first method
- All XEP methods available in application landspace, now accepts jaxl instance as first parameter. Updated core jaxl class magic method to handle the same.
If you are calling XEP methods as specified in the documentation, this change will not hurt your running applications
- Updated echobot sample application to utilize XEP 0054 (VCard Temp) and 0202 (Entity Time)
- First checkin of missing vcard-temp xep
- Added xmlentities JAXLUtil method
- Jaxl Parser now default parses xXmlns node for message stanzas
- Added PCRE_DOTALL and PCRE_MULTILINE pattern modifier for bosh unwrapBody method
- Added utility methods like urldecode, urlencode, htmlEntities, stripHTML and splitJid inside jaxl.js
- Updated sample application jaxl.ini to reflect changes in env/jaxl.ini
version 2.1.1
-------------
- Updated XMPPSend 'presence', 'message' and 'iq' methods to accept $jaxl instance as first parameter
if you are not calling these methods directly from your application code as mentioned in documentation
this change should not hurt you
- Added more comments to env/jaxl.ini and also added JAXL_LOG_ROTATE ini file option
- JAXL instance logs can be rotated every x seconds (logRotate config parameter) now
- Removed config param dumpTime, instead use dumpStat to specify stats dump period
- Base XMPP class now auto-flush output buffers filled because of library level rate limiter
- Added more options for JAXL constructor e.g.
boshHost, boshPort, boshSuffix, pidPath, logPath, logLevel, dumpStat, dumpTime
These param overwrites value specified inside jaxl.ini file
Also JAXL core will now periodically dump instance statistics
- Added an option in JAXL constructor to disable inbuild core rate limiter
- Added support when applications need to connect with external bosh endpoints
Bosh application code requires update for ->JAXL0206('startStream') method
- XMPPGet::handler replaces ->handler inside XEP-0124
- JAXLCron job now also passes connected instance to callback cron methods
- Updated base XMPP class now maintains a clock, updated sendXML method to respect library level rate limiting
- Base JAXL class now includes JAXLCron class for periodically dumping connected bot memory/usage stats
- First version of JAXLCron class for adding periodic jobs in the background
- XMPP payload handler moves from XMPPGet to base XMPP class, packets are then routed to XMPPGet class for further processing
- Updated xep-0124 to use instance bosh parameters instead of values defined inside jaxl.ini
- Provision to specify custom JAXL_BOSH_HOST inside jaxl.ini
- Instead of global logLevel and logPath, logger class now respects indivisual instance log settings
Helpful in multiple instance applications
- Updated base JAXL class to accept various other configuration parameters inside constructor
These param overwrites values defined inside jaxl.ini
- XMPPSend::xml method moves inside XMPP::sendXML (call using ->sendXML from within application code), as a part of library core cleanup
- Updated jaxl class to return back payload from called xep methods
- XMPP base method getXML can be instructed not to take a nap between stream reads
- Added jaxl_get_xml hook for taking control over incoming xml payload from xmpp stream
- Added support for disabling sig term registration, required by applications who already handle this in their core code
- Added capability of sending multiple message/presence stanza in one go inside jaxl base class
- Fixed typo in MUC Direct Invitation xep invite method
- getHandler should have accepted core instance by reference, fixed now. BOSH MUC Chat sample application header is now more appropriate
version 2.1.0
-------------
- First checkin of bosh MUC sample application
- Updated build file now packages bosh MUC chat sample application along with core classes
- Updated JAXLog class to accept instance inside log() method, application code should use ->log() to call JAXLog::log() method now
- Updated JAXLPlugin class to pass instance along with every XMPP event hook
- Updated jaxl_require method to call including XEP's init() method every time they are included using jaxl_require method
- Update jaxl.ini with some documentation/comments about JAXL_BOSH_COOKIE_DOMAIN parameter
- Updated echobot sample application code to pass instance while calling jaxl_require method
- Update XMPP SASL Auth class to accept instance while calculating SASL response.
Also passinginstance when jaxl_get_facebook_key hook is called
- Updated XMPP base class to accept component host name inside constructor.
Sending currentinstance with every XMPPSend, XMPPGet and JAXLog method calls
- Every XMPPGet method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Every XMPPSend method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Updated component bot sample application to show how to pass component host inside JAXL constructor.
Also updated jaxl_require call to accept current working instance
- Updated boshchat sample application to follow new rules of jaxl_require, also cleaned up the sample app code a bit
- Updated jaxl.ini of packaged sample applications to match /env/jaxl.ini
- Updated implemented XEP's init method to accept instance during initialization step
Send working instance with every XMPPSend method call
Almost every XEP's available method now accepts an additional instance so that XEP's can work independently for every instance inside a multiple jaxl instance application code
- Added magic method __call inside JAXL class
All application codes should now call a methods inside implemented XEP's like ->JAXLxxxx('method', , , ...)
Also added ->log method to be used by application codes
JAXLog::log() should not be called directly from application code
Updated XMPPSend methods to accept instance
Added ->requires() method that does a similar job as jaxl_require() which now also expects instance as one of the passed parameter.
version 2.0.4
-------------
- Updated XMPP base class and XMPP Get class to utilize new XMPPAuth class
- Updated jaxl_require method with new XMPPAuth class path
- Extracted XMPP SASL auth mechanism out of XMPP Get class, code cleanup
- unwrapBody method of XEP 0124 is now public
- Added #News block on top of README
- No more capital true, false, null inside Jaxl core to pass PHP_CodeSniffer tests
- :retab Jaxl library core to pass PHP_CodeSniffer tests
- Added Jabber Component Protocol example application bot
- Updated README with documentation link for Jabber component protocol
- Updated Entity Caps method to use list of passed feature list for verification code generation
- Updated MUC available methods doc link inside README
- Added experimental support for SCRAM-SHA-1, CRAM-MD5 and LOGIN auth mechanisms
version 2.0.3
-------------
- Updated Jaxl XML parsing class to handle multiple level nested child cases
- Updated README and bosh chat application with documentation link
- Fixed bosh application to run on localhost
- Added doc links inside echobot sample app
- Bosh sample application also use entity time XEP-0202 now
- Fix for sapi detection inside jaxl util
- jaxl.js updated to handle multiple ajax poll response payloads
- Bosh session manager now dumps ajax poll response on post handler callback
- Removed hardcoded ajax poll url inside boshchat application
- Updated component protocol XEP pre handshake event handling
version 2.0.2
-------------
- Packaged XEP 0202 (Entity Time)
- First checkin of Bosh related XEP 0124 and 0206
- Sample Bosh Chat example application
- Updated jaxl.class.php to save Bosh request action parameter
- jaxl.ini updated with Bosh related cookie options, default loglevel now set to 4
- jaxl.js checkin which should be used with bosh applications
- Updated base xmpp classes to provide integrated bosh support
- Outgoing presence and message stanza's too can include @id attribute now
version 2.0.1
-------------
- Typo fix in JAXLXml::$tagMap for errorCode
- Fix for handling overflooded roster list
- Packaged XEP 0115 (Entity capability) and XEP 0199 (XMPP Ping)
- Updated sample echobot to use XEP 0115 and XEP 0199
- Support for X-FACEBOOK-PLATFORM authentication
version 2.0.0
--------------
First checkin of:
- Restructed core library with event mechanism
- Packaged XEP 0004, 0030, 0045, 0050, 0085, 0092, 0114, 0133, 0249
- Sample echobot application
diff --git a/core/jaxl.cron.php b/core/jaxl.cron.php
index 11b748f..8ad06bc 100644
--- a/core/jaxl.cron.php
+++ b/core/jaxl.cron.php
@@ -1,93 +1,93 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl Cron Job
*
* Add periodic cron in your xmpp applications
*/
class JAXLCron {
private static $cron = array();
- public static function init() {
+ public static function init($jaxl) {
JAXLPlugin::add('jaxl_get_xml', array('JAXLCron', 'ticker'));
}
public static function ticker($payload, $jaxl) {
foreach(self::$cron as $interval => $jobs) {
foreach($jobs as $key => $job) {
if($jaxl->clock % $interval == 0 // if cron interval matches
|| $jaxl->clocked - $job['lastCall'] > $interval // if cron interval has already passed
) {
self::$cron[$interval][$key]['lastCall'] = $jaxl->clocked;
$arg = $job['arg'];
array_unshift($arg, $jaxl);
call_user_func_array($job['callback'], $arg);
}
}
}
return $payload;
}
public static function add(/* $callback, $interval, $param1, $param2, .. */) {
$arg = func_get_args();
$callback = array_shift($arg);
$interval = array_shift($arg);
self::$cron[$interval][self::generateCbSignature($callback)] = array('callback'=>$callback, 'arg'=>$arg, 'lastCall'=>time());
}
public static function delete($callback, $interval) {
$sig = self::generateCbSignature($callback);
if(isset(self::$cron[$interval][$sig]))
unset(self::$cron[$interval][$sig]);
}
protected static function generateCbSignature($callback) {
return is_array($callback) ? md5(json_encode($callback)) : md5($callback);
}
}
?>
|
jaxl/JAXL | 5e77c1985030b944da6db48e0979eb7d5336db90 | JAXLog class now also dump connect instance uid per log line | diff --git a/CHANGELOG b/CHANGELOG
index 97f9045..6e42f7d 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,300 +1,301 @@
version 2.1.2
-------------
+- JAXLog class now also dump connect instance uid per log line
- XMPP instance iq id now defaults to a random value between 1 and 9
Also added jaxl_get_id event hook for apps to customize iq id for the connected Jaxl instance
Also as compared to default numeric iq id, Jaxl core now uses hex iq id's
- Every jaxl instance per php process id now generate it's own unique id JAXL::$uid
- Jaxl core doesn't go for a session if it's optional as indicated by the xmpp server
- Fixed boshChat postBind issues as reported by issue#26 (http://code.google.com/p/jaxl/issues/detail?id=26)
- Fixed jaxl constructor config read warning and XEP 0114 now make use of JAXL::getConfigByPriority method
- Removed warning while reading user config inside Jaxl constructor
Upgraded Jaxl Parser class which was malfunctioning on CentOS PHP 5.1.6 (cli)
- Added bosh error response handling and appropriate logging inside XMPP over Bosh core files
- Code cleanup inside jaxl logger class.
Fixed getConfigByPriority method which was malfunctioning in specific cases
- JAXLog class now using inbuild php function (error_log)
- Checking in first version of XEP-0016 (Privacy Lists), XEP-0055 (Jabber Search), XEP-0077 (In-Band Registration), XEP-0144 (Roster Item Exchange), XEP-0153 (vCard-Based Avatars), XEP-0237 (Roster Versioning)
- On auth faliure core doesn't throw exception since XMPP over Bosh apps are not held inside a try catch block (a better fix may be possible in future)
- XMPP over BOSH xep wasn't passing back Jaxl instance obj for jaxl_post_disconnect hook, fixed that for clean disconnect
- Jaxl core attempts to create log and pid files if doesn't already exists
Also instead of die() core throws relevant exception message wherever required
XMPP base classes throws relevant exception with message wherever required
- First commit of JAXLException class. JAXL core now uses JAXLException
- Jaxl constructor dies if logPath, pidPath and tmpPath doesn't exists on the system
- Core updates JAXL::resource after successful binding to match resource assigned by the connecting server
- Updated echobot sample example to make use of autoSubscribe core feature
Also registers callback for jaxl_post_subscription_request and jaxl_post_subscription_accept hooks
- Updated echobot and boshchat application to use in memory roster cache maintained by Jaxl core.
App files should register callback on hook jaxl_post_roster_update to get notified everytime local roster cache is updated
- Added provision for local roster cache management inside Jaxl core.
Retrived roster lists are cached in memory (see updated echobot.php sample example).
Also added provision for presence tracking (JAXL::trackPresence).
If enabled Jaxl core keep a track of jid availability and update local roster cache accordingly.
Also added provision for auto-accept subscription (JAXL::autoSubscribe).
- Removed XMPP::isConnected variable which used to tell status of connected socket stream.
This is equivalent to checking XMPP:stream variable for true/false
- Added a (kind of) buggy support for '/xml()' inside parser xpath
- If Jaxl instance has being configured for auto periodic ping (XEP-0199), pings are holded till auth completion.
Also if server responds 'feature-not-implemented' for first ping XEP-0199 automatically deleted periodic ping cron tab
- Corrected handling of error type iq stanza's (removed jaxl_get_iq_error hook)
- Added iq error code xpath inside JAXLXml class
- Completed missing JAXLCron::delete method for removing a previously registered cron tab
- Checking in first version of XEP-0049 (Private XML Storage) (not yet tested)
- Checking in first version of XEP-0191 (Simple Communication Blocking) (not yet tested)
- Added JAXL_PING_INTERVAL configuration option inside jaxl.ini
- XEP-0199 (XMPP Ping) can now automatically ping the connected server periodically for keeping connection alive on long running bots
(see echobot.php sample app for usage)
- Updated JAXLCron::add method to accept a number of arguments while adding bckgrnd jobs
These list of arguments is passed back to the application method
- Updated IQ handling inside XEP-0202 which wasn't returning iq stanza back resulting in no ping/pong
- Updated echobot to show usage of JAXL::discoItems and JAXL::discoInfo inside application code
- Added tagMap xpath for service identity and feature nodes in service discovery resultset
- JAXL core now auto includes XEP-0128 along with XEP-0030 on startup.
Also added two methods JAXL::discoItems and JAXL::discoInfo for service discovery
- Checking in first version of XEP-0128 (Service Discovery Extension)
- Fixed bug where message and presence stanza builder were not using passed id value as attribute
- Removed jaxl_pre_curl event hook which was only used internally by XEP-0124
- Jaxl now shutdown gracefully is encryption is required and openssl PHP module is not loaded in the environment
- For every registered callback on XMPP hooks, callback'd method will receive two params.
A payload and reference of Jaxl instance for whom XMPP event has occured.
Updated sample application code to use passed back Jaxl instance reference instead of global jaxl variable.
- As a library convention XEP's exposing user space configuration parameters via JAXL constructor SHOULD utilize JAXL::getConfigByPriority method
Added JAXL_TMP_PATH option inside jaxl.ini
- Jaxl::tmp is now Jaxl::tmpPath. Also added Jaxl config param to specify custom tmp path location
Jaxl client also self detect the IP of the host it is running upon (to be used by STUN/TURN utilities in Jingle negotitation)
- Removed JAXLUtil::includePath and JAXLUtil::getAppFilePath methods which are now redundant after removing jaxl.ini and jaxl.conf from lib core
- Removed global defines JAXL_BASE_PATH, JAXL_APP_BASE_PATH, JAXL_BOSH_APP_ABS_PATH from inside jaxl.ini (No more required by apps to specify these values)
- Removing env/jaxl.php and env/jaxl.conf (were required if you run your apps using `jaxl` command line utility)
Updated env/jaxl.ini so that projects can now directly include their app setting via jaxl.ini (before including core/jaxl.class.php)
- Added JAXL::bareJid public variable for usage inside applications.
XMPP base class now return bool on socket connect completion (used by PHPUnit test cases)
- Removing build.sh file from library for next release
Users should simply download, extract, include and write their app code without caring about the build script from 2.1.2 release
- As a library convention to include XEP's use JAXL::requires() method, while to include any core/ or xmpp/ base class use jaxl_require() method.
Updated library code and xep's to adhere to this convention.
Jaxl instance now provide a system specific /tmp folder location accessible by JAXL::tmp
- Removed JAXL_NAME and JAXL_VERSION constants.
Instead const variables are now defined per instance accessible by getName() and getVersion() methods.
Updated XEP-0030,0092,0115 to use the same
- Moved indivisual XEP's working parameter (0114,0124) from JAXL core class to XEP classes itself.
XEP's make use of JAXL::config array for parsing user options.
- Added JAXL_COMPONENT_PASS option inside jaxl.ini. Updated build.sh with new /app file paths.
Updated XEP-0114,0124,0206 to use array style configs as defined inside JAXL class
- Removed dependency upon jaxl.ini from all sample applications.
First checkin of sample sendMessage.php app.
- Config parameters for XEP's like 0114 and 0206 are now saved as an array inside JAXL class (later on they will be moved inside respective XEP's).
Added constructor config option to pre-choose an auth mechanism to be performed
if an auth mech is pre-chosen app files SHOULD not register callback for jaxl_get_auth_mech hook.
Bosh cookie settings can now be passed along with Jaxl constructor.
Added support for publishing vcard-temp:x:update node along with presence stanzas.
Jaxl instance can run in 3 modes a.k.a. stream,component and bosh mode
applications should use JAXL::startCore('mode') to configure instance for a specific mode.
- Removed redundant NS variable from inside XEP-0124
- Moved JAXLHTTPd setting defines inside the class (if gone missing CPU usage peaks to 100%)
- Added jaxl_httpd_pre_shutdown, jaxl_httpd_get_http_request, jaxl_httpd_get_sock_request event hooks inside JAXLHTTPd class
- Added JAXLS5B path (SOCKS5 implementation) inside jaxl_require method
- Removed all occurance of JAXL::$action variable from /core and /xep class files
- Updated boshChat and boshMUChat sample application which no longer user JAXL::$action variable inside application code
- Updated preFetchBOSH and preFetchXMPP sample example.
Application code don't need any JAXL::$action variable now
Neither application code need to define JAXL_BASE_PATH (optional from now on)
- JAXL core and XEP-0206 have no relation and dependency upon JAXL::$action variable now.
- Deprecated jaxl_get_body hook which was only for XEP-0124 working.
Also cleaned up XEP-0124 code by removing processBody method which is now handled inside preHandler itself.
- Defining JAXL_BASE_PATH inside application code made optional.
Developers can directly include /path/to/jaxl/core/jaxl.class.php and start writing applications.
Also added a JAXL::startCore() method (see usage in /app/preFetchXMPP.php).
Jaxl magic method for calling XEP methods now logs a warning inside jaxl.log if XEP doesn't exists in the environment
- Added tag map for XMPP message thread and subject child elements
- Fixed typo where in case of streamError proper description namespace was not parsed/displayed
- Disabled BOSH session close if application is running in boshOut=false mode
Suggested by MOVIM dev team who were experiencing loss of session data on end of script
- JAXL::log method 2nd parameter now defaults to logLevel=1 (passing 2nd param is now optional)
- Fixed XPath for iq stanza error condition and error NS extraction inside jaxl.parser.class
- First checkin of XEP-0184 Message Receipts
- Added support for usage of name() xpath function inside tag maps of JAXLXml class.
Also added some documentation for methods available inside JAXLXml class
- Fixed JAXLPlugin::remove method to properly remove and manage callback registry.
Also added some documentation for JAXLPlugin class methods
- Added JAXL contructor config option to disable BOSH module auto-output behaviour.
This is utilized inside app/preFetchBOSH.php sample example
- First checkin of sample application code pre-fetching XMPP/Jabber data for web page population using BOSH XEP
- Added a sample application file which can be used to pre-fetch XMPP/Jabber data for a webpage without using BOSH XEP or Ajax requests
As per the discussion on google groups (http://bit.ly/aKavZB) with MOVIM team
- JAXL library is now $jaxl independent, you can use anything like $var = new JAXL(); instance your applications now
JAXLUtil::encryptPassword now accepts username/password during SASL auth.
Previously it used to auto detect the same from JAXL instance, now core has to manually pass these param
- Added JAXL::startHTTPd method with appropriate docblock on how to convert Jaxl instance into a Jaxl socket (web) server.
Comments also explains how to still maintaining XMPP communication in the background
- Updated JAXLHTTPd class to use new constants inside jaxl.ini
- Added jaxl_get_stream_error event handler.
Registered callback methods also receive array form of received XMPP XML stanza
- Connecting Jaxl instance now fallback to default value 'localhost' for host,domain,boshHost,boshPort,boshSuffix
If these values are not configured either using jaxl.ini constants or constructor
- Provided a sendIQ method per JAXL instance.
Recommended that applications and XEP's should directly use this method for sending <iq/> type stanza
DONOT use XMPPSend methods inside your application code from here on
- Added configuration options for JAXL HTTPd server and JAXL Bosh Component Manager inside jaxl.ini
- Fixed type in XEP-0202 (Entity Time). XEP was not sending <iq/> id in response to get request
- Jaxl library is now phpdocs ready. Added extended documentation for JAXL core class, rest to be added
- All core classes inside core/, xmpp/ and xep/ folder now make use of jaxl->log method
JAXL Core constructor are now well prepared so that inclusion of jaxl.ini is now optional
Application code too should use jaxl->log instead of JAXLog::log method for logging purpose
- Reshuffled core instance paramaters between JAXL and XMPP class
Also Jaxl core now logs at level 1 instead of 0 (i.e. all logs goes inside jaxl.log and not on console)
- JAXL class now make use of endStream method inside XMPP base class while disconnecting.
Also XMPPSend::endStream now forces xmpp stanza delivery (escaping JAXL internal buffer)
http://code.google.com/p/jaxl/issues/detail?id=23
- Added endStream method inside XMPP base class and startSession,startBind methods inside XMPPSend class
XMPP::sendXML now accepts a $force parameter for escaping XMPP stanza's from JAXL internal buffer
- Updated the way Jaxl core calls XEP 0115 method (entity caps) to match documentation
XEP method's should accept jaxl instance as first paramater
- First checkin of PEP (Personal Eventing), User Location, User Mood, User Activity and User Tune XEP's
- Completed methods discoFeatures, discoNodes, discoNodeInfo, discoNodeMeta and discoNodeItems in PubSub XEP
- Hardcoded client category, type, lang and name. TODO: Make them configurable in future
- Cleaned up XEP 0030 (Service Discovery) and XEP 0115 (Entity Capabilities)
- Updated XMPP base class to use performance configuration parameters (now customizable with JAXL constructor)
- jaxl.conf will be removed from jaxl core in future, 1st step towards this goal
- Moved bulk of core configs from jaxl.conf
- Added more configuration options relating to client performance e.g. getPkts, getPktSize etc
- Fixed client mode by detecting sapi type instead of $_REQUEST['jaxl'] variable
- Now every implemented XEP should have an 'init' method which will accept only one parameter (jaxl instance itself)
- Jaxl core now converts transmitted stanza's into xmlentities (http://code.google.com/p/jaxl/issues/detail?id=22)
- Created a top level 'patch' folder which contains various patches sent by developers using 'git diff > patch' utility
- Fixed typo in namespace inside 0030 (thanks to Thomas Baquet for the patch)
- First checkin of PubSub XEP (untested)
- Indented build.sh and moved define's from top of JAXLHTTPd class to jaxl.ini
- Added JAXLHTTPd inside Jaxl core (a simple socket select server)
- Fixed sync of background iq and other stanza requests with browser ajax calls
- Updated left out methods in XMPP over BOSH xep to accept jaxl instance as first method
- All XEP methods available in application landspace, now accepts jaxl instance as first parameter. Updated core jaxl class magic method to handle the same.
If you are calling XEP methods as specified in the documentation, this change will not hurt your running applications
- Updated echobot sample application to utilize XEP 0054 (VCard Temp) and 0202 (Entity Time)
- First checkin of missing vcard-temp xep
- Added xmlentities JAXLUtil method
- Jaxl Parser now default parses xXmlns node for message stanzas
- Added PCRE_DOTALL and PCRE_MULTILINE pattern modifier for bosh unwrapBody method
- Added utility methods like urldecode, urlencode, htmlEntities, stripHTML and splitJid inside jaxl.js
- Updated sample application jaxl.ini to reflect changes in env/jaxl.ini
version 2.1.1
-------------
- Updated XMPPSend 'presence', 'message' and 'iq' methods to accept $jaxl instance as first parameter
if you are not calling these methods directly from your application code as mentioned in documentation
this change should not hurt you
- Added more comments to env/jaxl.ini and also added JAXL_LOG_ROTATE ini file option
- JAXL instance logs can be rotated every x seconds (logRotate config parameter) now
- Removed config param dumpTime, instead use dumpStat to specify stats dump period
- Base XMPP class now auto-flush output buffers filled because of library level rate limiter
- Added more options for JAXL constructor e.g.
boshHost, boshPort, boshSuffix, pidPath, logPath, logLevel, dumpStat, dumpTime
These param overwrites value specified inside jaxl.ini file
Also JAXL core will now periodically dump instance statistics
- Added an option in JAXL constructor to disable inbuild core rate limiter
- Added support when applications need to connect with external bosh endpoints
Bosh application code requires update for ->JAXL0206('startStream') method
- XMPPGet::handler replaces ->handler inside XEP-0124
- JAXLCron job now also passes connected instance to callback cron methods
- Updated base XMPP class now maintains a clock, updated sendXML method to respect library level rate limiting
- Base JAXL class now includes JAXLCron class for periodically dumping connected bot memory/usage stats
- First version of JAXLCron class for adding periodic jobs in the background
- XMPP payload handler moves from XMPPGet to base XMPP class, packets are then routed to XMPPGet class for further processing
- Updated xep-0124 to use instance bosh parameters instead of values defined inside jaxl.ini
- Provision to specify custom JAXL_BOSH_HOST inside jaxl.ini
- Instead of global logLevel and logPath, logger class now respects indivisual instance log settings
Helpful in multiple instance applications
- Updated base JAXL class to accept various other configuration parameters inside constructor
These param overwrites values defined inside jaxl.ini
- XMPPSend::xml method moves inside XMPP::sendXML (call using ->sendXML from within application code), as a part of library core cleanup
- Updated jaxl class to return back payload from called xep methods
- XMPP base method getXML can be instructed not to take a nap between stream reads
- Added jaxl_get_xml hook for taking control over incoming xml payload from xmpp stream
- Added support for disabling sig term registration, required by applications who already handle this in their core code
- Added capability of sending multiple message/presence stanza in one go inside jaxl base class
- Fixed typo in MUC Direct Invitation xep invite method
- getHandler should have accepted core instance by reference, fixed now. BOSH MUC Chat sample application header is now more appropriate
version 2.1.0
-------------
- First checkin of bosh MUC sample application
- Updated build file now packages bosh MUC chat sample application along with core classes
- Updated JAXLog class to accept instance inside log() method, application code should use ->log() to call JAXLog::log() method now
- Updated JAXLPlugin class to pass instance along with every XMPP event hook
- Updated jaxl_require method to call including XEP's init() method every time they are included using jaxl_require method
- Update jaxl.ini with some documentation/comments about JAXL_BOSH_COOKIE_DOMAIN parameter
- Updated echobot sample application code to pass instance while calling jaxl_require method
- Update XMPP SASL Auth class to accept instance while calculating SASL response.
Also passinginstance when jaxl_get_facebook_key hook is called
- Updated XMPP base class to accept component host name inside constructor.
Sending currentinstance with every XMPPSend, XMPPGet and JAXLog method calls
- Every XMPPGet method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Every XMPPSend method now accepts instance.
Updated JAXLPlugin execute method call to accept instance and also passing current working instance to JAXLog method calls
- Updated component bot sample application to show how to pass component host inside JAXL constructor.
Also updated jaxl_require call to accept current working instance
- Updated boshchat sample application to follow new rules of jaxl_require, also cleaned up the sample app code a bit
- Updated jaxl.ini of packaged sample applications to match /env/jaxl.ini
- Updated implemented XEP's init method to accept instance during initialization step
Send working instance with every XMPPSend method call
Almost every XEP's available method now accepts an additional instance so that XEP's can work independently for every instance inside a multiple jaxl instance application code
- Added magic method __call inside JAXL class
All application codes should now call a methods inside implemented XEP's like ->JAXLxxxx('method', , , ...)
Also added ->log method to be used by application codes
JAXLog::log() should not be called directly from application code
Updated XMPPSend methods to accept instance
Added ->requires() method that does a similar job as jaxl_require() which now also expects instance as one of the passed parameter.
version 2.0.4
-------------
- Updated XMPP base class and XMPP Get class to utilize new XMPPAuth class
- Updated jaxl_require method with new XMPPAuth class path
- Extracted XMPP SASL auth mechanism out of XMPP Get class, code cleanup
- unwrapBody method of XEP 0124 is now public
- Added #News block on top of README
- No more capital true, false, null inside Jaxl core to pass PHP_CodeSniffer tests
- :retab Jaxl library core to pass PHP_CodeSniffer tests
- Added Jabber Component Protocol example application bot
- Updated README with documentation link for Jabber component protocol
- Updated Entity Caps method to use list of passed feature list for verification code generation
- Updated MUC available methods doc link inside README
- Added experimental support for SCRAM-SHA-1, CRAM-MD5 and LOGIN auth mechanisms
version 2.0.3
-------------
- Updated Jaxl XML parsing class to handle multiple level nested child cases
- Updated README and bosh chat application with documentation link
- Fixed bosh application to run on localhost
- Added doc links inside echobot sample app
- Bosh sample application also use entity time XEP-0202 now
- Fix for sapi detection inside jaxl util
- jaxl.js updated to handle multiple ajax poll response payloads
- Bosh session manager now dumps ajax poll response on post handler callback
- Removed hardcoded ajax poll url inside boshchat application
- Updated component protocol XEP pre handshake event handling
version 2.0.2
-------------
- Packaged XEP 0202 (Entity Time)
- First checkin of Bosh related XEP 0124 and 0206
- Sample Bosh Chat example application
- Updated jaxl.class.php to save Bosh request action parameter
- jaxl.ini updated with Bosh related cookie options, default loglevel now set to 4
- jaxl.js checkin which should be used with bosh applications
- Updated base xmpp classes to provide integrated bosh support
- Outgoing presence and message stanza's too can include @id attribute now
version 2.0.1
-------------
- Typo fix in JAXLXml::$tagMap for errorCode
- Fix for handling overflooded roster list
- Packaged XEP 0115 (Entity capability) and XEP 0199 (XMPP Ping)
- Updated sample echobot to use XEP 0115 and XEP 0199
- Support for X-FACEBOOK-PLATFORM authentication
version 2.0.0
--------------
First checkin of:
- Restructed core library with event mechanism
- Packaged XEP 0004, 0030, 0045, 0050, 0085, 0092, 0114, 0133, 0249
- Sample echobot application
diff --git a/core/jaxl.logger.php b/core/jaxl.logger.php
index f891ea5..a65237a 100644
--- a/core/jaxl.logger.php
+++ b/core/jaxl.logger.php
@@ -1,71 +1,71 @@
<?php
/**
* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package jaxl
* @subpackage core
* @author Abhinav Singh <[email protected]>
* @copyright Abhinav Singh
* @link http://code.google.com/p/jaxl
*/
/**
* Jaxl Logging Class
*/
class JAXLog {
public static function log($log, $level=1, $jaxl=false) {
- $log = '['.$jaxl->pid.'] '.date('Y-m-d H:i:s')." - ".$log;
+ $log = '['.$jaxl->pid.':'.$jaxl->uid.'] '.date('Y-m-d H:i:s')." - ".$log;
if($level <= $jaxl->logLevel
||($level == 0 && $jaxl->mode == "cli"))
error_log($log."\n\n", 3, $jaxl->logPath);
return true;
}
public static function logRotate($jaxl) {
if(copy($jaxl->logPath, $jaxl->logPath.'.'.date('Y-m-d-H-i-s')))
if($jaxl->mode == 'cli')
- print '['.$jaxl->pid.'] '.date('Y-m-d H:i:s')." - Successfully rotated log file...\n";
+ print '['.$jaxl->pid.':'.$jaxl->uid.'] '.date('Y-m-d H:i:s')." - Successfully rotated log file...\n";
$fh = fopen($jaxl->logPath, "r+");
ftruncate($fh, 1);
rewind($fh);
fclose($fh);
}
}
?>
|
dougwilson/perl5-www-wizards-gatherer | f85538d5cedad0727519323c2d14b16b4e55abc5 | Add copy of the license text | diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f4499a4
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,377 @@
+This software is copyright (c) 2010 by Douglas Christopher Wilson <[email protected]>.
+
+This is free software; you can redistribute it and/or modify it under
+the same terms as the Perl 5 programming language system itself.
+
+Terms of the Perl programming language system itself
+
+a) the GNU General Public License as published by the Free
+ Software Foundation; either version 1, or (at your option) any
+ later version, or
+b) the "Artistic License"
+
+--- The GNU General Public License, Version 1, February 1989 ---
+
+This software is Copyright (c) 2010 by Douglas Christopher Wilson <[email protected]>.
+
+This is free software, licensed under:
+
+ The GNU General Public License, Version 1, February 1989
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 1, February 1989
+
+ Copyright (C) 1989 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The license agreements of most software companies try to keep users
+at the mercy of those companies. By contrast, our General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. The
+General Public License applies to the Free Software Foundation's
+software and to any other program whose authors commit to using it.
+You can use it for your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Specifically, the General Public License is designed to make
+sure that you have the freedom to give away or sell copies of free
+software, that you receive source code or can get it if you want it,
+that you can change the software or use pieces of it in new free
+programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of a such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must tell them their rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any program or other work which
+contains a notice placed by the copyright holder saying it may be
+distributed under the terms of this General Public License. The
+"Program", below, refers to any such program or work, and a "work based
+on the Program" means either the Program or any work containing the
+Program or a portion of it, either verbatim or with modifications. Each
+licensee is addressed as "you".
+
+ 1. You may copy and distribute verbatim copies of the Program's source
+code as you receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice and
+disclaimer of warranty; keep intact all the notices that refer to this
+General Public License and to the absence of any warranty; and give any
+other recipients of the Program a copy of this General Public License
+along with the Program. You may charge a fee for the physical act of
+transferring a copy.
+
+ 2. You may modify your copy or copies of the Program or any portion of
+it, and copy and distribute such modifications under the terms of Paragraph
+1 above, provided that you also do the following:
+
+ a) cause the modified files to carry prominent notices stating that
+ you changed the files and the date of any change; and
+
+ b) cause the whole of any work that you distribute or publish, that
+ in whole or in part contains the Program or any part thereof, either
+ with or without modifications, to be licensed at no charge to all
+ third parties under the terms of this General Public License (except
+ that you may choose to grant warranty protection to some or all
+ third parties, at your option).
+
+ c) If the modified program normally reads commands interactively when
+ run, you must cause it, when started running for such interactive use
+ in the simplest and most usual way, to print or display an
+ announcement including an appropriate copyright notice and a notice
+ that there is no warranty (or else, saying that you provide a
+ warranty) and that users may redistribute the program under these
+ conditions, and telling the user how to view a copy of this General
+ Public License.
+
+ d) You may charge a fee for the physical act of transferring a
+ copy, and you may at your option offer warranty protection in
+ exchange for a fee.
+
+Mere aggregation of another independent work with the Program (or its
+derivative) on a volume of a storage or distribution medium does not bring
+the other work under the scope of these terms.
+
+ 3. You may copy and distribute the Program (or a portion or derivative of
+it, under Paragraph 2) in object code or executable form under the terms of
+Paragraphs 1 and 2 above provided that you also do one of the following:
+
+ a) accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of
+ Paragraphs 1 and 2 above; or,
+
+ b) accompany it with a written offer, valid for at least three
+ years, to give any third party free (except for a nominal charge
+ for the cost of distribution) a complete machine-readable copy of the
+ corresponding source code, to be distributed under the terms of
+ Paragraphs 1 and 2 above; or,
+
+ c) accompany it with the information you received as to where the
+ corresponding source code may be obtained. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form alone.)
+
+Source code for a work means the preferred form of the work for making
+modifications to it. For an executable file, complete source code means
+all the source code for all modules it contains; but, as a special
+exception, it need not include source code for modules which are standard
+libraries that accompany the operating system on which the executable
+file runs, or for standard header files or definitions files that
+accompany that operating system.
+
+ 4. You may not copy, modify, sublicense, distribute or transfer the
+Program except as expressly provided under this General Public License.
+Any attempt otherwise to copy, modify, sublicense, distribute or transfer
+the Program is void, and will automatically terminate your rights to use
+the Program under this License. However, parties who have received
+copies, or rights to use copies, from you under this General Public
+License will not have their licenses terminated so long as such parties
+remain in full compliance.
+
+ 5. By copying, distributing or modifying the Program (or any work based
+on the Program) you indicate your acceptance of this license to do so,
+and all its terms and conditions.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the original
+licensor to copy, distribute or modify the Program subject to these
+terms and conditions. You may not impose any further restrictions on the
+recipients' exercise of the rights granted herein.
+
+ 7. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of the license which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+the license, you may choose any version ever published by the Free Software
+Foundation.
+
+ 8. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ Appendix: How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to humanity, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these
+terms.
+
+ To do so, attach the following notices to the program. It is safest to
+attach them to the start of each source file to most effectively convey
+the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) 19yy <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 1, or (at your option)
+ any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software Foundation,
+ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) 19xx name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the
+appropriate parts of the General Public License. Of course, the
+commands you use may be called something other than `show w' and `show
+c'; they could even be mouse-clicks or menu items--whatever suits your
+program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ program `Gnomovision' (a program to direct compilers to make passes
+ at assemblers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+
+--- The Artistic License 1.0 ---
+
+This software is Copyright (c) 2010 by Douglas Christopher Wilson <[email protected]>.
+
+This is free software, licensed under:
+
+ The Artistic License 1.0
+
+The Artistic License
+
+Preamble
+
+The intent of this document is to state the conditions under which a Package
+may be copied, such that the Copyright Holder maintains some semblance of
+artistic control over the development of the package, while giving the users of
+the package the right to use and distribute the Package in a more-or-less
+customary fashion, plus the right to make reasonable modifications.
+
+Definitions:
+
+ - "Package" refers to the collection of files distributed by the Copyright
+ Holder, and derivatives of that collection of files created through
+ textual modification.
+ - "Standard Version" refers to such a Package if it has not been modified,
+ or has been modified in accordance with the wishes of the Copyright
+ Holder.
+ - "Copyright Holder" is whoever is named in the copyright or copyrights for
+ the package.
+ - "You" is you, if you're thinking about copying or distributing this Package.
+ - "Reasonable copying fee" is whatever you can justify on the basis of media
+ cost, duplication charges, time of people involved, and so on. (You will
+ not be required to justify it to the Copyright Holder, but only to the
+ computing community at large as a market that must bear the fee.)
+ - "Freely Available" means that no fee is charged for the item itself, though
+ there may be fees involved in handling the item. It also means that
+ recipients of the item may redistribute it under the same conditions they
+ received it.
+
+1. You may make and give away verbatim copies of the source form of the
+Standard Version of this Package without restriction, provided that you
+duplicate all of the original copyright notices and associated disclaimers.
+
+2. You may apply bug fixes, portability fixes and other modifications derived
+from the Public Domain or from the Copyright Holder. A Package modified in such
+a way shall still be considered the Standard Version.
+
+3. You may otherwise modify your copy of this Package in any way, provided that
+you insert a prominent notice in each changed file stating how and when you
+changed that file, and provided that you do at least ONE of the following:
+
+ a) place your modifications in the Public Domain or otherwise make them
+ Freely Available, such as by posting said modifications to Usenet or an
+ equivalent medium, or placing the modifications on a major archive site
+ such as ftp.uu.net, or by allowing the Copyright Holder to include your
+ modifications in the Standard Version of the Package.
+
+ b) use the modified Package only within your corporation or organization.
+
+ c) rename any non-standard executables so the names do not conflict with
+ standard executables, which must also be provided, and provide a separate
+ manual page for each non-standard executable that clearly documents how it
+ differs from the Standard Version.
+
+ d) make other distribution arrangements with the Copyright Holder.
+
+4. You may distribute the programs of this Package in object code or executable
+form, provided that you do at least ONE of the following:
+
+ a) distribute a Standard Version of the executables and library files,
+ together with instructions (in the manual page or equivalent) on where to
+ get the Standard Version.
+
+ b) accompany the distribution with the machine-readable source of the Package
+ with your modifications.
+
+ c) accompany any non-standard executables with their corresponding Standard
+ Version executables, giving the non-standard executables non-standard
+ names, and clearly documenting the differences in manual pages (or
+ equivalent), together with instructions on where to get the Standard
+ Version.
+
+ d) make other distribution arrangements with the Copyright Holder.
+
+5. You may charge a reasonable copying fee for any distribution of this
+Package. You may charge any fee you choose for support of this Package. You
+may not charge a fee for this Package itself. However, you may distribute this
+Package in aggregate with other (possibly commercial) programs as part of a
+larger (possibly commercial) software distribution provided that you do not
+advertise this Package as a product of your own.
+
+6. The scripts and library files supplied as input to or produced as output
+from the programs of this Package do not automatically fall under the copyright
+of this Package, but belong to whomever generated them, and may be sold
+commercially, and may be aggregated with this Package.
+
+7. C or perl subroutines supplied by you and linked into this Package shall not
+be considered part of this Package.
+
+8. The name of the Copyright Holder may not be used to endorse or promote
+products derived from this software without specific prior written permission.
+
+9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
+WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
+MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+
+The End
+
|
dougwilson/perl5-www-wizards-gatherer | cbf4c69895767049fbbbe14c725662f3466155bc | Add distribution metadata | diff --git a/META.yml b/META.yml
new file mode 100644
index 0000000..9bdfda3
--- /dev/null
+++ b/META.yml
@@ -0,0 +1,52 @@
+---
+abstract: 'Access to Magic the Gathering Gatherer'
+author:
+ - 'Douglas Christopher Wilson <[email protected]>'
+configure_requires:
+ Module::Build: 0.36
+generated_by: 'Module::Build version 0.3607'
+license: perl
+meta-spec:
+ url: http://module-build.sourceforge.net/META-spec-v1.4.html
+ version: 1.4
+name: WWW-Wizards-Gatherer
+no_index:
+ directory:
+ - inc
+ - t
+ - xt
+provides:
+ WWW::Wizards::Gatherer:
+ file: lib/WWW/Wizards/Gatherer.pm
+ version: 0.001
+ WWW::Wizards::Gatherer::Card:
+ file: lib/WWW/Wizards/Gatherer/Card.pm
+ version: 0.001
+ WWW::Wizards::Gatherer::Results:
+ file: lib/WWW/Wizards/Gatherer/Results.pm
+ version: 0.001
+ WWW::Wizards::Gatherer::Utils:
+ file: lib/WWW/Wizards/Gatherer/Utils.pm
+ version: 0.001
+requires:
+ Carp: 0
+ Data::Stream::Bulk::DoneFlag: 0.08
+ Encode: 0
+ HTML::HTML5::Parser: 0.101
+ List::MoreUtils: 0
+ Moose: 1.05
+ Moose::Util::TypeConstraints: 0
+ MooseX::StrictConstructor: 0.09
+ MooseX::Types::Common::String: 0
+ MooseX::Types::LWP::UserAgent: 0.02
+ MooseX::Types::Moose: 0
+ MooseX::Types::URI: 0
+ URI: 0
+ URI::QueryParam: 0
+ namespace::clean: 0.10
+ perl: 5.008003
+resources:
+ homepage: http://github.com/dougwilson/perl5-www-wizards-gatherer/
+ license: http://dev.perl.org/licenses/
+ repository: git://github.com/dougwilson/perl5-www-wizards-gatherer.git
+version: 0.001
|
dougwilson/perl5-www-wizards-gatherer | 6acc2adf78e9b1e178097cc36aca41c7c4d55846 | Add the MANIFEST file | diff --git a/MANIFEST b/MANIFEST
new file mode 100644
index 0000000..98d8916
--- /dev/null
+++ b/MANIFEST
@@ -0,0 +1,9 @@
+Build.PL
+lib/WWW/Wizards/Gatherer.pm
+lib/WWW/Wizards/Gatherer/Card.pm
+lib/WWW/Wizards/Gatherer/Results.pm
+lib/WWW/Wizards/Gatherer/Utils.pm
+MANIFEST This list of files
+README
+LICENSE
+META.yml
|
dougwilson/perl5-www-wizards-gatherer | f70d4d053947d3cb2e9f1f3e44f153aebabb344d | Initial functionality; missing tests and documentation | diff --git a/Build.PL b/Build.PL
new file mode 100644
index 0000000..a49976a
--- /dev/null
+++ b/Build.PL
@@ -0,0 +1,57 @@
+use 5.008003;
+use strict;
+use warnings 'all';
+
+use Module::Build 0.31;
+
+my $build = Module::Build->new(
+ module_name => 'WWW::Wizards::Gatherer',
+ license => 'perl',
+ dist_author => 'Douglas Christopher Wilson <[email protected]>',
+
+ meta_merge => {
+ resources => {
+ homepage => 'http://github.com/dougwilson/perl5-www-wizards-gatherer/',
+ repository => 'git://github.com/dougwilson/perl5-www-wizards-gatherer.git',
+ },
+ no_index => {
+ directory => [qw/inc t xt/],
+ },
+ },
+
+ # Module that are required for tests in t/
+ build_requires => {
+# 'Test::Exception' => '0.03',
+# 'Test::More' => 0,
+ },
+
+ # Module that are required
+ requires => {
+ 'perl' => '5.008003',
+ 'Carp' => 0,
+ 'Data::Stream::Bulk::DoneFlag' => '0.08',
+ 'Encode' => 0,
+ 'HTML::HTML5::Parser' => '0.101',
+ 'List::MoreUtils' => 0,
+ 'Moose' => '1.05',
+ 'Moose::Util::TypeConstraints' => 0,
+ 'MooseX::StrictConstructor' => '0.09',
+ 'MooseX::Types::Common::String' => 0,
+ 'MooseX::Types::LWP::UserAgent' => '0.02',
+ 'MooseX::Types::Moose' => 0,
+ 'MooseX::Types::URI' => 0,
+ 'URI' => 0,
+ 'URI::QueryParam' => 0,
+ 'namespace::clean' => '0.10',
+ },
+
+ # Enable tests to be in multi-level directories
+ recursive_test_files => 1,
+
+ # Create a LICENSE file
+ create_license => 1,
+
+ test_files => 't/*.t xt/*.t',
+);
+
+$build->create_build_script;
diff --git a/README b/README
new file mode 100644
index 0000000..9e05498
--- /dev/null
+++ b/README
@@ -0,0 +1,42 @@
+WWW-Wizards-Gatherer version 0.001
+==================================
+
+INSTALLATION
+------------
+
+To install this module, run the following commands:
+
+ perl Build.PL
+ ./Build
+ ./Build test
+ ./Build install
+
+SUPPORT AND DOCUMENTATION
+-------------------------
+
+After installing, you can find documentation for this module with the
+perldoc command.
+
+ perldoc WWW::Wizards::Gatherer
+
+You can also look for information at:
+
+* [RT, CPAN's request tracker](http://rt.cpan.org/NoAuth/Bugs.html?Dist=WWW-Wizards-Gatherer)
+
+* [AnnoCPAN, Annotated CPAN documentation](http://annocpan.org/dist/WWW-Wizards-Gatherer)
+
+* [CPAN Ratings](http://cpanratings.perl.org/d/WWW-Wizards-Gatherer)
+
+* [Search CPAN](http://search.cpan.org/dist/WWW-Wizards-Gatherer)
+
+COPYRIGHT AND LICENCE
+---------------------
+
+Copyright 2010 Douglas Christopher Wilson.
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of either:
+
+* the GNU General Public License as published by the Free Software Foundation;
+ either version 1, or (at your option) any later version, or
+* the Artistic License version 2.0.
diff --git a/lib/WWW/Wizards/Gatherer.pm b/lib/WWW/Wizards/Gatherer.pm
new file mode 100644
index 0000000..2c201cd
--- /dev/null
+++ b/lib/WWW/Wizards/Gatherer.pm
@@ -0,0 +1,125 @@
+package WWW::Wizards::Gatherer;
+
+use 5.008003;
+use strict;
+use warnings 'all';
+
+###########################################################################
+# METADATA
+our $AUTHORITY = 'cpan:DOUGDUDE';
+our $VERSION = '0.001';
+
+###########################################################################
+# MOOSE
+use Moose 1.05;
+use MooseX::StrictConstructor 0.09;
+
+###########################################################################
+# MOOSE TYPES
+use MooseX::Types::LWP::UserAgent 0.02 qw(UserAgent);
+use MooseX::Types::URI qw(Uri);
+
+###########################################################################
+# MODULES
+use URI::QueryParam ();
+use WWW::Wizards::Gatherer::Results ();
+use WWW::Wizards::Gatherer::Utils ();
+
+###########################################################################
+# ALL IMPORTS BEFORE THIS WILL BE ERASED
+use namespace::clean 0.10 -except => [qw(meta)];
+
+###########################################################################
+# ATTRIBUTES
+has card_details_page => (
+ is => 'ro',
+ isa => Uri,
+
+ coerce => 1,
+ default => 'http://gatherer.wizards.com/Pages/Card/Details.aspx',
+);
+has search_page => (
+ is => 'ro',
+ isa => Uri,
+
+ coerce => 1,
+ clearer => '_clear_search_page',
+ predicate => 'has_search_page',
+);
+has user_agent => (
+ is => 'ro',
+ isa => UserAgent,
+
+ coerce => 1,
+ default => sub { [] },
+);
+
+###########################################################################
+# METHODS
+sub get_random_card {
+ my ($self) = @_;
+
+ # Get the card details page address
+ my $random_card_url = $self->card_details_page->clone;
+
+ # To get a random card, just add action=random
+ $random_card_url->query_param(action => 'random');
+
+ # Get the card
+ my $card = WWW::Wizards::Gatherer::Utils::build_card_from_response(
+ $self->user_agent->get($random_card_url),
+ );
+
+ # Return the card
+ return $card;
+}
+sub search {
+ my ($self, %args) = @_;
+
+ # The arguments for the results object
+ my @results_args = (
+ user_agent => $self->user_agent->clone,
+ );
+
+ if ($self->has_search_page) {
+ # Add the search page
+ push @results_args, search_page => $self->search_page->clone;
+ }
+
+ # XXX: For testing
+ push @results_args, search => {
+ map { $_ => qq{+["$args{$_}"]} } keys %args
+ };
+
+ # Return a new results bulk data stream
+ return WWW::Wizards::Gatherer::Results->new(@results_args);
+}
+
+###########################################################################
+# MAKE MOOSE OBJECT IMMUTABLE
+__PACKAGE__->meta->make_immutable;
+
+1;
+
+__END__
+
+=head1 NAME
+
+WWW::Wizards::Gatherer - Access to Magic the Gathering Gatherer
+
+=head1 VERSION
+
+This documentation refers to version 0.001.
+
+=head1 SYNOPSIS
+
+ use WWW::Wizards::Gatherer ();
+
+ # Get the gatherer
+ my $gatherer = WWW::Wizards::Gatherer->new;
+
+ # Find a card by name and expansion
+ my $card = $gatherer->search(
+ name => 'Ad Nauseam',
+ set => 'Shards of Alara',
+ );
diff --git a/lib/WWW/Wizards/Gatherer/Card.pm b/lib/WWW/Wizards/Gatherer/Card.pm
new file mode 100644
index 0000000..a8e95e3
--- /dev/null
+++ b/lib/WWW/Wizards/Gatherer/Card.pm
@@ -0,0 +1,150 @@
+package WWW::Wizards::Gatherer::Card;
+
+use 5.008003;
+use strict;
+use warnings 'all';
+
+###########################################################################
+# METADATA
+our $AUTHORITY = 'cpan:DOUGDUDE';
+our $VERSION = '0.001';
+
+###########################################################################
+# MOOSE
+use Moose 1.05;
+use MooseX::StrictConstructor 0.09;
+
+###########################################################################
+# MOOSE TYPES
+use MooseX::Types::Common::String qw(NonEmptySimpleStr NonEmptyStr);
+use MooseX::Types::Moose qw(ArrayRef Str);
+
+###########################################################################
+# MODULES
+use Moose::Util::TypeConstraints;
+
+###########################################################################
+# ATTRIBUTES
+subtype PT =>
+ as Str =>
+ where { m{\A (?:\-?\d+ (?:[+-] \*)? | \*) \z}msx };
+
+has artist => (
+ is => 'ro',
+ isa => NonEmptySimpleStr,
+
+ required => 1,
+);
+has converted_mana_cost => (
+ is => 'ro',
+ isa => 'Int',
+
+ clearer => '_clear_converted_mana_cost',
+ predicate => 'has_converted_mana_cost',
+);
+has expansion => (
+ is => 'ro',
+ isa => NonEmptySimpleStr,
+
+ required => 1,
+);
+has flavor_text => (
+ is => 'ro',
+ isa => NonEmptyStr,
+
+ clearer => '_clear_flavor_text',
+ predicate => 'has_flavor_text',
+);
+has loyalty => (
+ is => 'ro',
+ isa => 'Int',
+
+ clearer => '_clear_loyalty',
+ predicate => 'has_loyalty',
+);
+has mana_cost => (
+ is => 'ro',
+ isa => NonEmptyStr, # XXX: Change this
+
+ clearer => '_clear_mana_cost',
+ predicate => 'has_mana_cost',
+);
+has multiverse_id => (
+ is => 'ro',
+ isa => 'Int',
+
+ required => 1,
+);
+has name => (
+ is => 'ro',
+ isa => NonEmptySimpleStr,
+
+ required => 1,
+);
+has number => (
+ is => 'ro',
+ isa => 'Int',
+
+ clearer => '_clear_number',
+ predicate => 'has_number',
+);
+has power => (
+ is => 'ro',
+ isa => 'PT',
+
+ clearer => '_clear_power',
+ predicate => 'has_power',
+);
+has rarity => (
+ is => 'ro',
+ isa => NonEmptySimpleStr,
+
+ required => 1,
+);
+has subtypes => (
+ is => 'ro',
+ isa => ArrayRef[NonEmptySimpleStr],
+
+ clearer => '_clear_subtypes',
+ predicate => 'has_subtypes',
+);
+has text_blocks => (
+ is => 'ro',
+ isa => ArrayRef[Str],
+
+ clearer => '_clear_text_blocks',
+ predicate => 'has_text_blocks',
+);
+has toughness => (
+ is => 'ro',
+ isa => 'PT',
+
+ clearer => '_clear_toughness',
+ predicate => 'has_toughness',
+);
+has types => (
+ is => 'ro',
+ isa => ArrayRef[NonEmptySimpleStr],
+
+ required => 1,
+);
+
+###########################################################################
+# ALL IMPORTS BEFORE THIS WILL BE ERASED
+use namespace::clean 0.10 -except => [qw(meta)];
+
+###########################################################################
+# MAKE MOOSE OBJECT IMMUTABLE
+__PACKAGE__->meta->make_immutable;
+
+1;
+
+__END__
+
+=head1 NAME
+
+WWW::Wizards::Gatherer::Card - Magic: The Gathering Card
+
+=head1 VERSION
+
+This documentation refers to version 0.001.
diff --git a/lib/WWW/Wizards/Gatherer/Results.pm b/lib/WWW/Wizards/Gatherer/Results.pm
new file mode 100644
index 0000000..97fec82
--- /dev/null
+++ b/lib/WWW/Wizards/Gatherer/Results.pm
@@ -0,0 +1,432 @@
+package WWW::Wizards::Gatherer::Results;
+
+use 5.008003;
+use strict;
+use warnings 'all';
+
+###########################################################################
+# METADATA
+our $AUTHORITY = 'cpan:DOUGDUDE';
+our $VERSION = '0.001';
+
+###########################################################################
+# MOOSE
+use Moose 1.05;
+use MooseX::StrictConstructor 0.09;
+
+###########################################################################
+# MOOSE ROLES
+with 'Data::Stream::Bulk::DoneFlag' => {-version => 0.08};
+
+###########################################################################
+# MOOSE TYPES
+use MooseX::Types::LWP::UserAgent 0.02 qw(UserAgent);
+use MooseX::Types::URI qw(Uri);
+
+###########################################################################
+# MODULES
+use Encode ();
+use HTML::HTML5::Parser 0.101 ();
+use URI ();
+use URI::QueryParam ();
+use WWW::Wizards::Gatherer::Utils ();
+
+###########################################################################
+# ALL IMPORTS BEFORE THIS WILL BE ERASED
+use namespace::clean 0.10 -except => [qw(meta)];
+
+###########################################################################
+# ATTRIBUTES
+has search => (
+ is => 'ro',
+ isa => 'HashRef',
+
+ required => 1,
+);
+has search_page => (
+ is => 'ro',
+ isa => Uri,
+
+ coerce => 1,
+ default => 'http://gatherer.wizards.com/Pages/Search/Default.aspx',
+);
+has user_agent => (
+ is => 'ro',
+ isa => UserAgent,
+
+ coerce => 1,
+ required => 1,
+);
+
+###########################################################################
+# PRIVATE ATTRIBUTES
+has _current_page => (
+ is => 'rw',
+ isa => 'Int',
+
+ clearer => '_clear_current_page',
+ init_arg => undef,
+ predicate => '_has_current_page',
+);
+has _last_page => (
+ is => 'rw',
+ isa => 'Int',
+
+ clearer => '_clear_last_page',
+ init_arg => undef,
+ predicate => '_has_last_page',
+);
+has _pending_card_urls => (
+ is => 'rw',
+ isa => 'ArrayRef[Str]',
+ traits => ['Array'],
+
+ default => sub { [] },
+ init_arg => undef,
+ handles => {
+ _add_pending_card_urls => 'push',
+ _get_next_pending_card_url => 'shift',
+ _has_pending_card_urls => 'count',
+ },
+);
+
+###########################################################################
+# METHODS
+sub get_more {
+ my ($self) = @_;
+
+ my $results;
+
+ if (!$self->_has_pending_card_urls && defined(my $next_page_address = $self->_next_page_address)) {
+ $self->_add_pending_card_urls(
+ $self->_parse_card_urls_from_search_page($next_page_address)
+ );
+ }
+
+ if ($self->_has_pending_card_urls) {
+ # There are pending card URLs to retrieve
+ $results = [WWW::Wizards::Gatherer::Utils::build_card_from_response(
+ $self->user_agent->get($self->_get_next_pending_card_url),
+ )];
+ }
+
+ return $results;
+}
+
+###########################################################################
+# PRIVATE METHODS
+sub _next_page {
+ my ($self) = @_;
+
+ # Get the next page
+ my $next_page = $self->_has_current_page ? $self->_current_page + 1 : 1;
+
+ if ($self->_has_last_page && $next_page > $self->_last_page) {
+ # No more pages
+ $next_page = undef;
+ }
+
+ return $next_page;
+}
+sub _next_page_address {
+ my ($self) = @_;
+
+ # Get the current search page address
+ my $page_address = $self->search_page->clone;
+
+ # Add the search terms to the URL
+ for my $key (keys %{$self->search}) {
+ # Get the value of the key
+ my $value = Encode::encode_utf8($self->search->{$key});
+
+ # Append the value to the query
+ $page_address->query_param_append($key => $value);
+ }
+
+ # Get the next page
+ if (defined(my $next_page = $self->_next_page)) {
+ # Add the page to the URL (but the site uses pages with 0-index)
+ $page_address->query_param(page => $next_page - 1);
+ }
+ else {
+ # No more pages
+ $page_address = undef;
+ }
+
+ return $page_address;
+}
+sub _parse_card_urls_from_search_page {
+ my ($self, $search_page_url) = @_;
+
+ # Get the page number of this page
+ my $current_page = $self->_next_page;
+
+ # Remember the previous value of max redirect
+ my $previous_max_redirect = $self->user_agent->max_redirect;
+
+ # Set to 0 to prevent all redirects
+ $self->user_agent->max_redirect(0);
+print {*STDERR} " => url $search_page_url\n";
+ # Get the page
+ my $response = $self->user_agent->get($search_page_url);
+
+ # Set the redirect value back
+ $self->user_agent->max_redirect($previous_max_redirect);
+
+ if (defined $response->header('Location')) {
+ # Only one result
+ my $card_result = URI->new_abs($response->header('Location'), $response->base);
+
+ # Set the max pages to 1
+ $self->_current_page(1);
+ $self->_last_page(1);
+
+ return ("$card_result");
+ }
+
+ # Create a new HTML parser
+ my $parser = HTML::HTML5::Parser->new;
+
+ # Prase the content
+ my $document = $parser->parse_string($response->decoded_content);
+
+ # XXX: This should probably be some other function
+ if (!$self->_has_last_page) {
+ # Get the last page number from this results page
+ my ($paging_div) = grep { _element_has_class($_, 'paging') }
+ $document->getElementsByTagName('div');
+
+ # We'll say the current page is the last page unless proven otherwise
+ my $last_page = $current_page;
+
+ for my $page_link ($paging_div->getChildrenByTagName('a')) {
+ if ($page_link->hasAttribute('href')
+ && $page_link->getAttribute('href') =~ m{\b page=(\d+)}msx) {
+ my $page_number = $1;
+
+ if ($page_number > $last_page) {
+ $last_page = $page_number;
+ }
+ }
+ }
+
+ # Set the last page
+ $self->_last_page($last_page);
+ }
+
+ # Get the card table from the page
+ my ($card_table) = grep { _element_has_class($_, 'cardItemTable') }
+ $document->getElementsByTagName('table');
+
+ if (!defined $card_table) {
+ # There are no results
+ return;
+ }
+
+ # Get the card tables
+ my @card_tables = $card_table->getChildrenByTagName('tbody')->shift
+ ->getChildrenByTagName('tr')->shift
+ ->getChildrenByTagName('td')->shift
+ ->getChildrenByTagName('table');
+
+ my @card_urls;
+
+ for my $table (@card_tables) {
+ # All the links point to the card, so just pick the first one
+ my ($card_link) = map { URI->new_abs($_->getAttribute('href'), $response->base) }
+ grep { $_->hasAttribute('href') }
+ $table->getElementsByTagName('a');
+
+ # Get the card
+ push @card_urls, "$card_link";
+ }
+
+ # Update current page
+ $self->_current_page($current_page);
+
+ return @card_urls;
+}
+
+###########################################################################
+# PRIVATE FUNCTIONS
+sub _element_has_class {
+ my ($element, $class_name) = @_;
+
+ # No if element has no classes at all
+ return !1 if !$element->hasAttribute('class');
+
+ # Get the class names
+ my @class = split m{\s+}msx, $element->getAttribute('class');
+
+ # Return if any of the class names match
+ return List::MoreUtils::any { $_ eq $class_name } @class;
+}
+
+###########################################################################
+# MAKE MOOSE OBJECT IMMUTABLE
+__PACKAGE__->meta->make_immutable;
+
+1;
+
+__END__
+
+=head1 NAME
+
+WWW::Wizards::Gatherer::Results - Search results
+
+=head1 VERSION
+
+This documentation refers to version 0.001.
+
+=head1 SYNOPSIS
+
+ my $results = ...; # This object
+
+ BLOCK:
+ while (defined(my $block = $results->next)) {
+ RESULT:
+ for my $result (@{$block}) {
+ # ... do something with the result
+ }
+ }
+
+=head1 DESCRIPTION
+
+This represents results from a search on Gatherer.
+
+=head1 ROLES
+
+This object is composed of these L<Moose|Moose> roles:
+
+=over
+
+=item * L<Data::Stream::Bulk|Data::Stream::Bulk> 0.08
+
+=item * L<Data::Stream::Bulk::DoneFlag|Data::Stream::Bulk::DoneFlag> 0.08
+
+=back
+
+=head1 CONSTRUCTOR
+
+This is fully object-oriented, and as such before any method can be used,
+the constructor needs to be called to create an object to work with.
+
+=head2 new
+
+This will construct a new object. During object construction, no requests
+are made.
+
+=over
+
+=item new(%attributes)
+
+C<%attributes> is a HASH where the keys are attributes (specified in the
+L</ATTRIBUTES> section).
+
+=item new($attributes)
+
+C<$attributes> is a HASHREF where the keys are attributes (specified in the
+L</ATTRIBUTES> section).
+
+=back
+
+=head1 ATTRIBUTES
+
+ # Get an attribute
+ my $value = $object->attribute_name;
+
+=head2 user_agent
+
+B<Required>.
+
+This is a user agent that will be used to make the page requests. This is a
+C<UserAgent> as defined by
+L<MooseX::Types::LWP::UserAgent|MooseX::Types::LWP::UserAgent>.
+
+=head1 METHODS
+
+=head2 next
+
+Returns the next block as an array reference or C<undef> when there is no
+data blocks left. See L<Data::Stream::Bulk|Data::Stream::Bulk> for the full
+documentation.
+
+The definition of a block in this module is the number of cards that can be
+retrieved in the least number of requests. This means if getting each card
+requires a request, then each block will probably only have one card. A
+waste of a double-loop, you say? It could change at any time in the future
+and this L<Data::Stream::Bulk|Data::Stream::Bulk> interface is the most
+flexable (and will fit in with your logic if you use L<KiokuDB|KiokuDB>.
+
+=head1 DEPENDENCIES
+
+=over
+
+=item * L<Data::Stream::Bulk::DoneFlag|Data::Stream::Bulk::DoneFlag> 0.08
+
+=item * L<Moose|Moose> 1.05
+
+=item * L<MooseX::StrictConstructor|MooseX::StrictConstructor> 0.09
+
+=item * L<namespace::clean|namespace::clean> 0.10
+
+=back
+
+=head1 AUTHOR
+
+Douglas Christopher Wilson, C<< <doug at somethingdoug.com> >>
+
+=head1 BUGS AND LIMITATIONS
+
+Please report any bugs or feature requests to C<bug-www-wizards-gatherer at rt.cpan.org>,
+or through the web interface at
+L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=WWW-Wizards-Gatherer>.
+I will be notified, and then you'll automatically be notified of progress on
+your bug as I make changes.
+
+I highly encourage the submission of bugs and enhancements to my modules.
+
+=head1 SUPPORT
+
+You can find documentation for this module with the perldoc command.
+
+ perldoc WWW::Wizards::Gatherer
+
+You can also look for information at:
+
+=over 4
+
+=item * RT: CPAN's request tracker
+
+L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=WWW-Wizards-Gatherer>
+
+=item * AnnoCPAN: Annotated CPAN documentation
+
+L<http://annocpan.org/dist/WWW-Wizards-Gatherer>
+
+=item * CPAN Ratings
+
+L<http://cpanratings.perl.org/d/WWW-Wizards-Gatherer>
+
+=item * Search CPAN
+
+L<http://search.cpan.org/dist/WWW-Wizards-Gatherer/>
+
+=back
+
+=head1 LICENSE AND COPYRIGHT
+
+Copyright 2010 Douglas Christopher Wilson.
+
+This program is free software; you can redistribute it and/or
+modify it under the terms of either:
+
+=over 4
+
+=item * the GNU General Public License as published by the Free
+Software Foundation; either version 1, or (at your option) any
+later version, or
+
+=item * the Artistic License version 2.0.
+
+=back
diff --git a/lib/WWW/Wizards/Gatherer/Utils.pm b/lib/WWW/Wizards/Gatherer/Utils.pm
new file mode 100644
index 0000000..2c4d5a9
--- /dev/null
+++ b/lib/WWW/Wizards/Gatherer/Utils.pm
@@ -0,0 +1,356 @@
+package WWW::Wizards::Gatherer::Utils;
+
+use 5.008003;
+use charnames ':full'; # Used in regexps as \N{}
+use strict;
+use utf8;
+use warnings 'all';
+
+###########################################################################
+# METADATA
+our $AUTHORITY = 'cpan:DOUGDUDE';
+our $VERSION = '0.001';
+
+###########################################################################
+# MODULES
+use Carp ();
+use List::MoreUtils ();
+use HTML::HTML5::Parser 0.101 ();
+use WWW::Wizards::Gatherer::Card ();
+
+###########################################################################
+# ALL IMPORTS BEFORE THIS WILL BE ERASED
+use namespace::clean 0.10 -except => [qw(meta)];
+
+###########################################################################
+# FUNCTIONS
+sub build_card_from_response {
+ my ($response) = @_;
+
+ # Create a new HTML parser
+ my $parser = HTML::HTML5::Parser->new;
+
+ # Prase the content
+ my $document = $parser->parse_string($response->decoded_content);
+
+ # Parse the data from the document
+ my %card_args = _parse_card_details_document($document);
+
+ # Build the card
+ my $card = WWW::Wizards::Gatherer::Card->new(%card_args);
+
+ return $card;
+}
+
+###########################################################################
+# PRIVATE VARIABLES
+my %card_details_value_transform = (
+ flavor_text => \&_card_details_value_transform_flavor_text,
+ mana_cost => \&_card_details_value_transform_mana_cost,
+ other_sets => sub { () }, # XXX: This is ignored for now
+ p_t => \&_card_details_value_transform_power_tough,
+ text => \&_card_details_value_transform_text,
+ types => \&_card_details_value_transform_types,
+);
+
+###########################################################################
+# PRIVATE FUNCTIONS
+sub _card_details_value_transform_flavor_text {
+ # Return the blocks joined with new lines
+ return join qq{\n}, _parse_card_text_boxes($_[0]);
+}
+sub _card_details_value_transform_mana_cost {
+ my ($element) = @_;
+
+ # Get the mana costs from the images
+ my @mana_costs = map { $_->getAttribute('alt') }
+ $element->getElementsByTagName('img');
+
+ # XXX: This should eventually be an object
+ return join q{}, map { "{$_}" } @mana_costs;
+}
+sub _card_details_value_transform_power_tough {
+ my ($element) = @_;
+
+ # Get the power and toughness
+ my ($power, $toughness) = $element->textContent =~ m{(\S+) \s* / \s* (\S+)}msx;
+
+ return (
+ power => $power,
+ toughness => $toughness,
+ );
+}
+sub _card_details_value_transform_types {
+ my ($element) = @_;
+
+ my %details;
+
+ # Get and trim the text content
+ my $value = $element->textContent;
+ $value =~ s{\A \s+}{}msx;
+ $value =~ s{\s+ \z}{}msx;
+
+ # Split the text content into type and subtypes
+ my ($types, $subtypes) = split m{\s* \N{EM DASH} \s*}msx, $value;
+
+ if (defined $types) {
+ # Split the types
+ my @type = split m{\s+}msx, $types;
+
+ # Store the type in the details
+ $details{types} = \@type;
+ }
+
+ if (defined $subtypes) {
+ # Split the subtypes
+ my @subtype = split m{\s+}msx, $subtypes;
+
+ # Store them in the details
+ $details{subtypes} = \@subtype;
+ }
+
+ return %details;
+}
+sub _card_details_value_transform_text {
+ # Change the name to text_blocks and return reference of blocks
+ return (text_blocks => [_parse_card_text_boxes($_[0])]);
+}
+sub _element_has_class {
+ my ($element, $class_name) = @_;
+
+ # No if element has no classes at all
+ return !1 if !$element->hasAttribute('class');
+
+ # Get the class names
+ my @class = split m{\s+}msx, $element->getAttribute('class');
+
+ # Return if any of the class names match
+ return List::MoreUtils::any { $_ eq $class_name } @class;
+}
+sub _label_transform {
+ my ($label) = @_;
+
+ # Lower case
+ $label = lc $label;
+
+ # Trim leading whitespace
+ $label =~ s{\A \s+}{}mosx;
+
+ # Trim following whitespace and colon
+ $label =~ s{:? \s* \z}{}mosx;
+
+ # Change octothorpe to number
+ $label =~ s{\#}{number}gmosx;
+
+ # Change spaces and other non-alphanumeric into an underscore
+ $label =~ s{\s+|\W}{_}gmosx;
+
+ if ('card_' eq substr $label, 0, 5) {
+ # Since this is a card, there is no need to have labels starting with card
+ $label = substr $label, 5;
+ }
+
+ return $label;
+}
+sub _nvp_transform {
+ my ($name, $value_element) = @_;
+
+ # Name-value pairs to return
+ my @nvp;
+
+ if (exists $card_details_value_transform{$name}) {
+ # Get the transform function
+ my $transform = $card_details_value_transform{$name};
+
+ # Get the value after being transformed
+ my @value = $transform->($value_element);
+
+ if (@value == 1) {
+ # The transform function simply returned the value
+ @nvp = ($name, $value[0]);
+ }
+ elsif (@value % 2 == 0) {
+ # The transform function returned name-value pair(s)
+ @nvp = @value;
+ }
+ else {
+ # Something went wrong
+ Carp::croak "Reading $name from the card details page failed";
+ }
+ }
+ else {
+ # Standard text transformation
+ my $value = $value_element->textContent;
+ $value =~ s{\A \s+}{}msx;
+ $value =~ s{\s+ \z}{}msx;
+
+ @nvp = ($name, $value);
+ }
+
+ return @nvp;
+}
+sub _parse_card_details_document {
+ my ($document) = @_;
+
+ # Get the card details tables
+ my @tables = grep { _element_has_class($_, 'cardDetails') }
+ $document->getElementsByTagName('table');
+
+ if (!@tables) {
+ Carp::croak 'No card details tables found in the document';
+ }
+
+ # For now, just use the first table
+ my $card_details_table = shift @tables;
+
+ # Get the right column
+ my ($right_column) = grep { _element_has_class($_, 'rightCol') }
+ map { $_->getChildrenByTagName('td') }
+ $card_details_table->getChildrenByTagName('tbody')
+ ->shift->getChildrenByTagName('tr');
+
+ my $pairs_div = $right_column->getChildrenByTagName('div')
+ ->get_node(2);
+
+ # Get the multiverse ID from the first a element to have it
+ my ($multiverse_id) = map { my ($id) = $_->getAttribute('href') =~ m{multiverseid=(\d+)}msx; defined $id ? $id : (); }
+ $right_column->getChildrenByTagName('div')->get_node(1)->getElementsByTagName('a');
+
+ # Start off the card arguments with the multiverse ID
+ my @card_args = (multiverse_id => $multiverse_id);
+
+ my @rows = grep { _element_has_class($_, 'row') }
+ $pairs_div->getChildrenByTagName('div');
+
+ for my $row (@rows) {
+ my @div = $row->getChildrenByTagName('div');
+ my $label = [grep { _element_has_class($_, 'label') } @div]->[0];
+ my $value = [grep { _element_has_class($_, 'value') } @div]->[0];
+
+ $label = _label_transform($label->textContent);
+
+ push @card_args, _nvp_transform($label, $value);
+ }
+
+ return @card_args;
+}
+sub _parse_card_text_boxes {
+ my ($element) = @_;
+
+ # Get the text blocks
+ my @text_blocks = grep { _element_has_class($_, 'cardtextbox') }
+ $element->getChildrenByTagName('div');
+
+ # Get the text of the blocks
+ @text_blocks = map { _process_card_text_block($_) } @text_blocks;
+
+ return @text_blocks;
+}
+sub _process_card_text_block {
+ my ($text_block) = @_;
+
+ my @text = map { $_->isa('XML::LibXML::Element') && $_->localname eq 'img' ? '{' . $_->getAttribute('alt') . '}' : $_->textContent } $text_block->childNodes;
+
+ return join q{}, @text;
+}
+
+1;
+
+__END__
+
+=head1 NAME
+
+WWW::Wizards::Gatherer::Utils - Utilities
+
+=head1 VERSION
+
+This documentation refers to version 0.001.
+
+=head1 SYNOPSIS
+
+ # TODO: Write this
+
+=head1 DESCRIPTION
+
+This provides common utility functions for WWW::Wizards::Gatherer.
+
+=head1 FUNCTIONS
+
+=head2 build_card_from_page
+
+This function takes a single argument which is a URL of a card and will
+parse the page and return a
+L<WWW::Wizards::Gatherer::Card|WWW::Wizards::Gatherer::Card> object.
+
+=head1 DEPENDENCIES
+
+=over
+
+=item * L<Carp|Carp>
+
+=item * L<HTML::HTML5::Parser|HTML::HTML5::Parser> 0.101
+
+=item * L<List::MoreUtils|List::MoreUtils>
+
+=item * L<namespace::clean|namespace::clean> 0.10
+
+=back
+
+=head1 AUTHOR
+
+Douglas Christopher Wilson, C<< <doug at somethingdoug.com> >>
+
+=head1 BUGS AND LIMITATIONS
+
+Please report any bugs or feature requests to C<bug-www-wizards-gatherer at rt.cpan.org>,
+or through the web interface at
+L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=WWW-Wizards-Gatherer>.
+I will be notified, and then you'll automatically be notified of progress on
+your bug as I make changes.
+
+I highly encourage the submission of bugs and enhancements to my modules.
+
+=head1 SUPPORT
+
+You can find documentation for this module with the perldoc command.
+
+ perldoc WWW::Wizards::Gatherer
+
+You can also look for information at:
+
+=over 4
+
+=item * RT: CPAN's request tracker
+
+L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=WWW-Wizards-Gatherer>
+
+=item * AnnoCPAN: Annotated CPAN documentation
+
+L<http://annocpan.org/dist/WWW-Wizards-Gatherer>
+
+=item * CPAN Ratings
+
+L<http://cpanratings.perl.org/d/WWW-Wizards-Gatherer>
+
+=item * Search CPAN
+
+L<http://search.cpan.org/dist/WWW-Wizards-Gatherer/>
+
+=back
+
+=head1 LICENSE AND COPYRIGHT
+
+Copyright 2010 Douglas Christopher Wilson.
+
+This program is free software; you can redistribute it and/or
+modify it under the terms of either:
+
+=over 4
+
+=item * the GNU General Public License as published by the Free
+Software Foundation; either version 1, or (at your option) any
+later version, or
+
+=item * the Artistic License version 2.0.
+
+=back
|
dougwilson/perl5-www-wizards-gatherer | bd0e80858dabbd2ce909defdcb9d26acb2ef1940 | Add files that list which files to ignore | diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..9789926
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,11 @@
+_build/
+blib/
+cover_db/
+Build
+Debian_CPANTS.txt
+Makefile
+Makefile.old
+MANIFEST.bak
+MYMETA.yml
+pm_to_blib
+
diff --git a/MANIFEST.SKIP b/MANIFEST.SKIP
new file mode 100644
index 0000000..a2f3787
--- /dev/null
+++ b/MANIFEST.SKIP
@@ -0,0 +1,12 @@
+\A.git/
+\Ablib/
+\A_build/
+\A.gitignore\z
+\ABuild\z
+\AMakefile(?:\.old|)?\z
+\AMANIFEST\.(?:bak|SKIP)\z
+\Apm_to_blib\z
+\ADebian_CPANTS.txt\z
+\AREADME\.mkdn\z
+\Acover_db/ # The Devel::Cover database
+^MYMETA.yml$
|
mikeknox/LogParse | 6b12acac8e8f741e8a1fa50c8f5901fd4dea0eb6 | Handle \# in regex's Handle ??? in field matches | diff --git a/logparse.pl b/logparse.pl
index d0792a0..45f6b05 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1297 +1,1268 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Long;
use Data::Dumper qw(Dumper);
use Storable;
# Globals
#
my $STARTTIME = time();
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my @CONFIGFILES;# = ("logparse.conf");
my %datahash;
#my %cfghash;
#my %reshash;
my $UNMATCHEDLINES = 1;
my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
my $MATCH; # Only lines matching this regex will be parsed
my $COLOR = 0;
my $INPUT; # Where to load %cfghash & %reshash
# If set, load data and then generate report
# config files have also been set, update %cfghash and then process ignored lines before generating report
my $OUTPUT; # Where to save %cfghash & %reshash
my $KEEPCONFIG = 0; # If > 0, loaded config data is not cleared when using config files
my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
"l|log=s" => \@LOGFILES,
"d|debug=i" => \$DEBUG,
"m|match=s" => \$MATCH,
"o|outpur=s" => \$OUTPUT,
"i|inpur=s" => \$INPUT,
"k|keeponfig=i" => \$KEEPCONFIG,
"color" => \$COLOR
);
unless ($result) {
warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>] [--color] [-m|--match <strinbg>] [-o|--output <file>] [-i|--input <file>] [-k|keepconfig <0|1>] \nInvalid config options passed");
}
if ($COLOR) {
use Term::ANSIColor qw(:constants);
}
@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
@LOGFILES = split(/,/,join(',',@LOGFILES));
if ($MATCH) {
$MATCH =~ s/\^\"//;
$MATCH =~ s/\"$//;
logmsg (2, 3, "Skipping lines which match $MATCH");
}
if ($INPUT) {
logmsg (1, 2, "Loading data from $INPUT");
%datahash = %{ retrieve ($INPUT) } or die "Unable to load data from $INPUT";
}
my $cfghash = \%{$datahash{cfg}};
logmsg (3, 3, "There are ".($#CONFIGFILES+1)." config files specified ...");
if ($#CONFIGFILES >= 0 ) {
if ($INPUT) {
$cfghash = {} unless $KEEPCONFIG > 0;
logmsg (3, 4, "As config files have been specified, empty loaded config");
logmsg (9, 4, "config is now:", $cfghash);
}
loadcfg ($cfghash, \@CONFIGFILES);
}
logmsg(7, 3, "cfghash:", $cfghash);
my $reshash = \%{$datahash{res}};
if ($INPUT) {
processdatafile($cfghash, $reshash);
} else {
processlogfile($cfghash, $reshash, \@LOGFILES);
}
if ($OUTPUT) {
logmsg (1, 2, "Saving data in $OUTPUT");
store (\%datahash, $OUTPUT ) or die "Can't output data to $OUTPUT";
}
logmsg (9, 0, "reshash ..\n", $reshash);
report($cfghash, $reshash);
logmsg (9, 0, "reshash ..\n", $reshash);
logmsg (9, 0, "cfghash ..\n", $cfghash);
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text does not contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ", \@tmp);
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
logmsg (6, 4, "line results now ...", $linehashref);
}
sub processdatafile {
my $cfghashref = shift;
my $reshashref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
if (exists ($$reshashref{nomatch}) ) {
my @nomatch = @{ $$reshashref{nomatch} };
@{ $$reshashref{nomatch} } = ();
#foreach my $line (@{@$reshashref{nomatch}}) {
foreach my $dataline (@nomatch) {
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $dataline;
#$line{line} =~ s/\s+?$//;
chomp $line{line};
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
processline ($cfghashref, $reshashref, \%line, $format, \%lastline);
}
}
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Processing logfiles: ", $logfileref);
foreach my $logfile (@$logfileref) {
logmsg(1, 0, "processing $logfile using format $format...");
open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
$line{line} =~ s/\s+?$//;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
#logmsg(5, 1, "skipping as line doesn't match the match regex") and
processline ($cfghashref, $reshashref, \%line, $format, \%lastline);
}
close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub processline {
my $cfghashref = shift;
my $reshashref = shift;
my $lineref = shift;
my $format = shift;
my $lastlineref = shift;
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $$lineref{line}, $lineref);
logmsg(9, 1, "Checking line: $$lineref{line}");
if (not $MATCH or $$lineref{line} =~ /$MATCH/) {
my %rules = matchrules(\%{ $$cfghashref{RULE} }, $lineref );
logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
if (keys %rules >= 0) {
logmsg (5, 2, "matched ".keys(%rules)." rules from line $$lineref{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
$execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, $lineref);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
logmsg (9, 3, "#rules in list .., ".keys(%rules) );
logmsg (9, 3, "\%rules ..", \%rules);
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $$lineref{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
if (exists( $$lastlineref{ $$lineref{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($$lastlineref{ $$lineref{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$$lastlineref{ $$lineref{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %{ $lineref};
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
} else {
logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
}
logmsg(9 ,1, "Results hash ...", \%$reshashref );
logmsg (5, 1, "finished processing line");
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
- $line =~ s/#.*$//; # strip anything after #
- #$line =~ s/{.*?$//; # strip trail {, it was required in old format
+ $line =~ s/(?<!\\)#.*$//; # strip anything after #, unless it is precceded by \
+ logmsg(9, 4, "line after removing training comments: $line");
@A = $line =~ /(\/.+\/|\{.+?\}|".+?"|\d+=".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
-=depricate
-sub parsecfgline {
-=head6 parsecfgline($line)
-Depricated, use getparameter()
-takes line as arg, and returns array of cmd and value (arg)
-#=cut
- my $line = shift;
-
- logmsg (5, 3, " and I was called by ... ".&whowasi);
- my $cmd = "";
- my $arg = "";
- chomp $line;
-
- logmsg(5, 3, " and I was called by ... ".&whowasi);
- logmsg (6, 4, "line: ${line}");
-
- if ($line =~ /^#|^\s+#/ ) {
- logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
- } elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
- logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
- } else {
- $line = $1 if $line =~ /^\s+(.*)/;
- ($cmd, $arg) = split (/\s+/, $line, 2);
- $arg = "" unless $arg;
- $cmd = "" unless $cmd;
- }
-
- logmsg (6, 3, "returning cmd: $cmd arg: $arg");
- return ($cmd, $arg);
-}
-=cut
-
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
# $$actionref[$actionindex]{regex} =~ s/\//\/\//g;
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
$$reportref[$reportindex]{regex} =~ s/^"//;
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line\n";
}
}
if ($COLOR) {
print RED "\n\nSummaries:\n", RESET;
} else {
print "\n\nSummaries:\n";
}
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
logmsg (4, 1, "Processing report# $rptid for rule: $rule ...");
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (5, 2, "\%ruleresults rule ($rule) report ID ($rptid) ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
if ($COLOR) {
print BLUE "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n", RESET;
} else {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
}
} else {
logmsg (4, 2, "Report has no title for rule: $rule\[$rptid\]");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
if ($COLOR) {
print GREEN rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key), RESET;
} else {
print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
}
} else {
if ($COLOR) {
print GREEN "\t$$reshashref{$rule}{$key}: $key\n", RESET;
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
logmsg (9, 5, "cfghashref ...", $cfghashref);
logmsg (9, 5, "reshashref ...", $reshashref);
for my $actionid (keys( %$reshashref ) ) {
logmsg (5, 5, "Processing actionid: $actionid ...");
for my $key (keys %{ $$reshashref{$actionid} } ) {
logmsg (5, 6, "Processing key: $key for actionid: $actionid");
(my @values) = split (/:/, $key);
logmsg (9, 7, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
logmsg (5, 7, "Processing report ID: $rptid with key: $key for actionid: $actionid");
if (exists($$cfghashref{reports}[$rptid]{field})) {
logmsg (9, 8, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 7, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
# Compare max fieldid to number of entries in $key, skip if maxid > $key
my $targetmaxfield = array_max(\@targetfieldids);
if ($targetmaxfield > ($#values + 1) ) {
#warning ("w", "There is a field id in the report line that is greater than the number of items in this line's data set, skipping.");
logmsg (2, 5, "There is a field id ($targetmaxfield) in the target key greater than the number of fields ($#values) in the key, skipping");
next;
}
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 8, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} elsif ($fieldid == $$cfghashref{reports}[$rptid]{field} ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid is used report matching, so adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 9, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
logmsg (9, 8, "targetkeymatch is now: $targetkeymatch");
}
$targetkeymatch =~ s/^://;
$targetkeymatch =~ s/\[/\\\[/g;
$targetkeymatch =~ s/\]/\\\]/g;
$targetkeymatch =~ s/\(/\\\(/g;
$targetkeymatch =~ s/\)/\\\)/g;
+ $targetkeymatch =~ s/(?<!\.\*)\?/\\\?/g;
logmsg (9, 7, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$targetkeymatch =~ s/\\\(/\(/g;
$targetkeymatch =~ s/\\\)/\)/g;
$targetkeymatch =~ s/\\\[/\[/g;
$targetkeymatch =~ s/\\\]/\]/g;
+ $targetkeymatch =~ s/\\\?/\?/g;
+
logmsg (9, 8, "$key does matched $targetkeymatch, so I'm doing the necssary calcs ...");
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Incremented count for report\[$rptid\]\[$targetkeymatch\] by $$reshashref{$actionid}{$key}{count} so it's now $$reshashref{$actionid}{$key}{count}");
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
logmsg (9, 9, "Added $$reshashref{$actionid}{$key}{total} to total for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{total}");
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Avg for report\[$rptid\]\[$targetkeymatch\] is now $results{$rptid}{$targetkeymatch}{avg}");
if ($results{$rptid}{$targetkeymatch}{max} < $$reshashref{$actionid}{$key}{max} ) {
$results{$rptid}{$targetkeymatch}{max} = $$reshashref{$actionid}{$key}{max};
logmsg (9, 9, "Setting $$reshashref{$actionid}{$key}{max} to max for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{max}");
}
if ($results{$rptid}{$targetkeymatch}{min} > $$reshashref{$actionid}{$key}{min} ) {
$results{$rptid}{$targetkeymatch}{min} = $$reshashref{$actionid}{$key}{min};
logmsg (9, 9, "Setting $$reshashref{$actionid}{$key}{max} to max for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{max}");
}
} else {
logmsg (9, 8, "$key does not match $targetkeymatch<eol>");
logmsg (9, 8, " key $key<eol>");
logmsg (9, 8, "targetkey $targetkeymatch<eol>");
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
logmsg (9, 5, "Returning ... results", \%results);
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ", $cfghashref);
logmsg (7, 3, "reshash ... ", $reshashref);
my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/MAX/i) {
$line =~ s/\{x\}/$$reshashref{$key}{max}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{max} (max)");
} elsif (/MIN/i) {
$line =~ s/\{x\}/$$reshashref{$key}{min}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{min} (min)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "Settting \$fields[$field] ($fields[$field]) = \$fields[$i] ($fields[$i])");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
$line.="\n";
#if (exists($$cfghashref{field})) {
#logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
#if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
#logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
#$line = "";
#}
#}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
logmsg (9, 5, "Matchlist ... $matchlist");
logmsg (9, 5, "Matchlist has morphed in \@matrix with elements ... ", \@matrix);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
logmsg (9, 6, "\$matchlist didn't have a \",\", so we shoved it onto \@matrix. Which is now ... ", \@matrix);
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
logmsg (9, 7, "\$i: $i");
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
logmsg (9, 8, "element $i ($matrix[$i]) was an integer so we pushed it onto the matrix");
} else {
logmsg (9, 8, "element $i ($matrix[$i]) wasn't an integer so we ignored it");
}
}
if ($numericonly) {
logmsg (9, 5, "Returning numeric only results ... ", \@tmpmatrix);
return @tmpmatrix;
} else {
logmsg (9, 5, "Returning full results ... ", \@matrix);
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid using matches $$cfghashref{matches}");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0; # 0 - nomatch 1 - match
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
} else {
logmsg(8, 6, "line didn't match negative regex");
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
} else {
logmsg(8, 5, "Using regex /$$cfghashref{regex}/ on field content: $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
} else {
logmsg(8, 6, "line didn't match regex");
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
logmsg (8, 4, "Regex for action has been applied, processing results now ...");
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count|sum|max|min/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
if ($$reshashref{$rule}{$actionid}{$matchid}{max} < $resmatrix[ $$cfghashref{sourcefield} ] ) {
$$reshashref{$rule}{$actionid}{$matchid}{max} = $resmatrix[ $$cfghashref{sourcefield} ];
}
if ($$reshashref{$rule}{$actionid}{$matchid}{min} > $resmatrix[ $$cfghashref{sourcefield} ] ) {
$$reshashref{$rule}{$actionid}{$matchid}{min} = $resmatrix[ $$cfghashref{sourcefield} ];
}
#} elsif (/sum/i) {
#$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
#$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
#
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
} else {
logmsg(5, 5, "retval ($retval) was not set so we haven't processed the results");
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..", \@matrix);
logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
logmsg (9, 4, "cfghashref:", $cfghashref);
for my $rule (keys %{ $cfghashref } ) {
logmsg (9, 4, "Checking to see if $rule applies ...");
if (matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref)) {
$rules{$rule} = $rule ;
logmsg (9, 5, "it matches");
} else {
logmsg (9, 5, "it doesn't match");
}
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1; # 1 = match, 0 = fail
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
logmsg (9, 5, "cfghashref:", $cfghashref);
if (exists ( $$cfghashref{fields} ) ) {
logmsg (9, 5, "cfghashref{fields}:", \%{ $$cfghashref{fields} });
}
logmsg (9, 5, "linehashref:", $linehashref);
foreach my $field (keys (%{ $cfghashref } ) ) {
logmsg(9, 6, "checking field: $field with value: $$cfghashref{$field}");
logmsg (9, 7, "Does field ($field) with value: $$linehashref{ $field } match the following regex ...");
if ($$cfghashref{$field} =~ /^!/) {
my $exp = $$cfghashref{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
logmsg (9, 8, "neg regexp compar /$$linehashref{ $field }/ !~ /$exp/, ret=$ret");
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{$field}/);
logmsg (9, 8, "regexp compar /$$linehashref{$field}/ =~ /$$cfghashref{$field}/, ret=$ret");
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
my $dumpvar = shift;
my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
# TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
if ($COLOR) {
print STDERR GREEN whowasi."(): d=${time}s:", RESET;
} else {
print STDERR whowasi."(): d=${time}s:";
}
print STDERR " $msg";
if ($dumpvar) {
if ($COLOR) {
print STDERR BLUE Dumper($dumpvar), RESET;
} else {
print STDERR Dumper($dumpvar);
}
}
print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
if ($COLOR >= 1) {
print RED, "WARNING: $msg\n", RESET;
} else {
print "WARNING: $msg\n";
}
} elsif (/e|error/i) {
if ($COLOR >= 1) {
print RED, "ERROR: $msg\n", RESET;
} else {
print "ERROR: $msg\n";
}
} elsif (/c|critical/i) {
if ($COLOR >= 1) {
print RED, "CRITICAL error, aborted ... $msg\n", RESET;
} else {
print "CRITICAL error, aborted ... $msg\n";
}
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
sub array_max {
my $arrayref = shift; # ref to array
my $highestvalue = $$arrayref[0];
for my $i (0 .. @$arrayref ) {
$highestvalue = $$arrayref[$i] if $$arrayref[$i] > $highestvalue;
}
return $highestvalue;
}
sub loaddata {
my $datafile = shift;
my $datahashref = shift;
%{$$datahashref} = retrive($datafile);
}
sub savedata {
my $datafile = shift;
my $datahashref = shift;
store ($datahashref, $datafile) or die "Can't output data to $datafile";
}
|
mikeknox/LogParse | 6e1841badd0f998a601f20563303b49007c2d044 | Handle \# in regex's and ??? in match fields | diff --git a/testcases/20/Description b/testcases/20/Description
new file mode 100644
index 0000000..1d9ac1b
--- /dev/null
+++ b/testcases/20/Description
@@ -0,0 +1 @@
+Test for matches which contain ?
diff --git a/testcases/20/expected.output b/testcases/20/expected.output
new file mode 100644
index 0000000..aaa2f90
--- /dev/null
+++ b/testcases/20/expected.output
@@ -0,0 +1,12 @@
+
+
+No match for lines:
+ May 24 07:38:08 hosta ipop3d[29316]: Login user=user.a host=someotherhost.someisp.net [192.168.23.10] nmsgs=57/57
+ May 24 07:38:14 hosta imapd[29329]: imaps SSL service init from 192.168.23.103
+
+
+Summaries:
+IMAP disconnects
+ 2 unexpected disconnect(s) for user.b on hosta
+ 1 unexpected disconnect(s) for ??? on hosta
+
diff --git a/testcases/20/logparse.conf b/testcases/20/logparse.conf
new file mode 100644
index 0000000..2a07ba7
--- /dev/null
+++ b/testcases/20/logparse.conf
@@ -0,0 +1,42 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 APP
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+
+RULE imap-unexp-discon {
+ APP imapd
+ ACTION MSG /Unexpected client disconnect, while reading line user=(.*) host=(.*)/ {HOST, 1, 2}
+ REPORT "IMAP disconnects" "{x} unexpected disconnect(s) for {2} on {1}"
+}
+
+#######################
+#2
diff --git a/testcases/20/test.log b/testcases/20/test.log
new file mode 100644
index 0000000..8e6a056
--- /dev/null
+++ b/testcases/20/test.log
@@ -0,0 +1,5 @@
+May 24 07:38:04 hosta imapd[29288]: Unexpected client disconnect, while reading line user=user.b host=somehost.myisp.com [10.1.1.123]
+May 24 07:38:05 hosta imapd[29307]: Unexpected client disconnect, while reading line user=user.b host=somehost.myisp.com [10.1.1.123]
+May 24 07:38:08 hosta ipop3d[29316]: Login user=user.a host=someotherhost.someisp.net [192.168.23.10] nmsgs=57/57
+May 24 07:38:14 hosta imapd[29329]: imaps SSL service init from 192.168.23.103
+May 24 07:38:14 hosta imapd[29329]: Unexpected client disconnect, while reading line user=??? host=host=somehost.myisp.com [10.1.1.123]
|
mikeknox/LogParse | f2b333c725d7a130e184857bf347366bd63177da | Clear config when data is loaded, unless -k (keep config) is set | diff --git a/logparse.pl b/logparse.pl
index aacb87b..d0792a0 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,768 +1,780 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Long;
use Data::Dumper qw(Dumper);
use Storable;
# Globals
#
my $STARTTIME = time();
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my @CONFIGFILES;# = ("logparse.conf");
my %datahash;
#my %cfghash;
#my %reshash;
my $UNMATCHEDLINES = 1;
my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
my $MATCH; # Only lines matching this regex will be parsed
my $COLOR = 0;
my $INPUT; # Where to load %cfghash & %reshash
# If set, load data and then generate report
# config files have also been set, update %cfghash and then process ignored lines before generating report
my $OUTPUT; # Where to save %cfghash & %reshash
+my $KEEPCONFIG = 0; # If > 0, loaded config data is not cleared when using config files
my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
"l|log=s" => \@LOGFILES,
"d|debug=i" => \$DEBUG,
"m|match=s" => \$MATCH,
"o|outpur=s" => \$OUTPUT,
"i|inpur=s" => \$INPUT,
+ "k|keeponfig=i" => \$KEEPCONFIG,
"color" => \$COLOR
);
unless ($result) {
- warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>] [--color] [-m|--match] [-o|--output] [-i|--input]\nInvalid config options passed");
+ warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>] [--color] [-m|--match <strinbg>] [-o|--output <file>] [-i|--input <file>] [-k|keepconfig <0|1>] \nInvalid config options passed");
}
if ($COLOR) {
use Term::ANSIColor qw(:constants);
}
@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
@LOGFILES = split(/,/,join(',',@LOGFILES));
if ($MATCH) {
$MATCH =~ s/\^\"//;
$MATCH =~ s/\"$//;
logmsg (2, 3, "Skipping lines which match $MATCH");
}
if ($INPUT) {
logmsg (1, 2, "Loading data from $INPUT");
%datahash = %{ retrieve ($INPUT) } or die "Unable to load data from $INPUT";
}
my $cfghash = \%{$datahash{cfg}};
-loadcfg ($cfghash, \@CONFIGFILES);
+logmsg (3, 3, "There are ".($#CONFIGFILES+1)." config files specified ...");
+if ($#CONFIGFILES >= 0 ) {
+ if ($INPUT) {
+ $cfghash = {} unless $KEEPCONFIG > 0;
+ logmsg (3, 4, "As config files have been specified, empty loaded config");
+ logmsg (9, 4, "config is now:", $cfghash);
+ }
+ loadcfg ($cfghash, \@CONFIGFILES);
+}
+
logmsg(7, 3, "cfghash:", $cfghash);
my $reshash = \%{$datahash{res}};
if ($INPUT) {
processdatafile($cfghash, $reshash);
} else {
processlogfile($cfghash, $reshash, \@LOGFILES);
}
if ($OUTPUT) {
logmsg (1, 2, "Saving data in $OUTPUT");
store (\%datahash, $OUTPUT ) or die "Can't output data to $OUTPUT";
}
logmsg (9, 0, "reshash ..\n", $reshash);
report($cfghash, $reshash);
logmsg (9, 0, "reshash ..\n", $reshash);
logmsg (9, 0, "cfghash ..\n", $cfghash);
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text does not contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ", \@tmp);
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
logmsg (6, 4, "line results now ...", $linehashref);
}
sub processdatafile {
my $cfghashref = shift;
my $reshashref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
if (exists ($$reshashref{nomatch}) ) {
my @nomatch = @{ $$reshashref{nomatch} };
@{ $$reshashref{nomatch} } = ();
#foreach my $line (@{@$reshashref{nomatch}}) {
foreach my $dataline (@nomatch) {
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $dataline;
- $line{line} =~ s/\s+?$//;
+ #$line{line} =~ s/\s+?$//;
+ chomp $line{line};
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
processline ($cfghashref, $reshashref, \%line, $format, \%lastline);
}
}
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Processing logfiles: ", $logfileref);
foreach my $logfile (@$logfileref) {
logmsg(1, 0, "processing $logfile using format $format...");
open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
$line{line} =~ s/\s+?$//;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
#logmsg(5, 1, "skipping as line doesn't match the match regex") and
processline ($cfghashref, $reshashref, \%line, $format, \%lastline);
}
close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub processline {
my $cfghashref = shift;
my $reshashref = shift;
my $lineref = shift;
my $format = shift;
my $lastlineref = shift;
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $$lineref{line}, $lineref);
logmsg(9, 1, "Checking line: $$lineref{line}");
if (not $MATCH or $$lineref{line} =~ /$MATCH/) {
my %rules = matchrules(\%{ $$cfghashref{RULE} }, $lineref );
logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
if (keys %rules >= 0) {
logmsg (5, 2, "matched ".keys(%rules)." rules from line $$lineref{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
$execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, $lineref);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
logmsg (9, 3, "#rules in list .., ".keys(%rules) );
logmsg (9, 3, "\%rules ..", \%rules);
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $$lineref{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
if (exists( $$lastlineref{ $$lineref{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($$lastlineref{ $$lineref{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$$lastlineref{ $$lineref{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %{ $lineref};
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
} else {
logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
}
logmsg(9 ,1, "Results hash ...", \%$reshashref );
logmsg (5, 1, "finished processing line");
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+\/|\{.+?\}|".+?"|\d+=".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
# $$actionref[$actionindex]{regex} =~ s/\//\/\//g;
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
$$reportref[$reportindex]{regex} =~ s/^"//;
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line\n";
}
}
if ($COLOR) {
print RED "\n\nSummaries:\n", RESET;
} else {
print "\n\nSummaries:\n";
}
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
logmsg (4, 1, "Processing report# $rptid for rule: $rule ...");
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (5, 2, "\%ruleresults rule ($rule) report ID ($rptid) ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
if ($COLOR) {
print BLUE "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n", RESET;
} else {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
}
} else {
logmsg (4, 2, "Report has no title for rule: $rule\[$rptid\]");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
if ($COLOR) {
print GREEN rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key), RESET;
} else {
print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
}
} else {
if ($COLOR) {
print GREEN "\t$$reshashref{$rule}{$key}: $key\n", RESET;
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
logmsg (9, 5, "cfghashref ...", $cfghashref);
logmsg (9, 5, "reshashref ...", $reshashref);
for my $actionid (keys( %$reshashref ) ) {
logmsg (5, 5, "Processing actionid: $actionid ...");
for my $key (keys %{ $$reshashref{$actionid} } ) {
logmsg (5, 6, "Processing key: $key for actionid: $actionid");
(my @values) = split (/:/, $key);
logmsg (9, 7, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
logmsg (5, 7, "Processing report ID: $rptid with key: $key for actionid: $actionid");
if (exists($$cfghashref{reports}[$rptid]{field})) {
logmsg (9, 8, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 7, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
# Compare max fieldid to number of entries in $key, skip if maxid > $key
my $targetmaxfield = array_max(\@targetfieldids);
diff --git a/testcases/17/expected.output b/testcases/17/expected.output
index 39aa064..dfea140 100644
--- a/testcases/17/expected.output
+++ b/testcases/17/expected.output
@@ -1,22 +1,22 @@
No match for lines:
Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
Oct 2 15:01:35 hosta sudo: userb : (command continued) /var/log/syslog.1.gz /var/log/syslog.2.gz /var/log/syslog.3.gz /var/log/syslog.4.gz /var/log/syslog.5.gz /var/log/syslog.6.gz /var/log/udev /var/log/user.log /var/log/wtmp /var/log/wtmp.1
Summaries:
Sudo usage by cmd/user/host
userb ran /usr/bin/tail /var/log/auth.log as root on hosta: 2 times
- usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
userb ran /bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
userb ran /bin/grep -i ssh /var/log/messages as root on hosta: 1 times
- usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
usera ran /bin/chown usera auth.log as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
userb ran /usr/bin/head /var/log/auth.log as root on hosta: 1 times
Sudo usage by user/host
usera ran 4 sudo cmds on hosta
userb ran 5 sudo cmds on hosta
diff --git a/testcases/18/expected.output b/testcases/18/expected.output
index e2b8580..da7fc01 100644
--- a/testcases/18/expected.output
+++ b/testcases/18/expected.output
@@ -1,21 +1,21 @@
No match for lines:
Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
Summaries:
Sudo usage by cmd/user/host
userb ran /usr/bin/tail /var/log/auth.log as root on hosta: 2 times
- usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
userb ran /bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
userb ran /bin/grep -i ssh /var/log/messages as root on hosta: 1 times
- usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
usera ran /bin/chown usera auth.log as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
userb ran /usr/bin/head /var/log/auth.log as root on hosta: 1 times
Sudo usage by user/host
usera ran 4 sudo cmds on hosta
userb ran 5 sudo cmds on hosta
diff --git a/testcases/19/Description b/testcases/19/Description
new file mode 100644
index 0000000..99c5cbb
--- /dev/null
+++ b/testcases/19/Description
@@ -0,0 +1,5 @@
+Load datafile from TC#16
+and process using updated config files
+Keep previously loaded confgi data
+
+Based on TC#7
diff --git a/testcases/19/args b/testcases/19/args
new file mode 100755
index 0000000..b19a3cc
--- /dev/null
+++ b/testcases/19/args
@@ -0,0 +1,2 @@
+${LOGPARSE} -c ./logparse.conf.1 -c ./logparse.conf.2 -i ../16/datafile -k 1 -d 0
+
diff --git a/testcases/19/expected.output b/testcases/19/expected.output
new file mode 100644
index 0000000..b503d0c
--- /dev/null
+++ b/testcases/19/expected.output
@@ -0,0 +1,34 @@
+
+
+No match for lines:
+ Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+ Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+
+
+Summaries:
+Sudo usage by cmd/user/host
+ userb ran /usr/bin/tail /var/log/auth.log as root on hosta: 2 times
+ userb ran /bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
+ userb ran /bin/grep -i ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/chown usera auth.log as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
+ userb ran /usr/bin/head /var/log/auth.log as root on hosta: 1 times
+
+Sudo usage by user/host
+ usera ran 4 sudo cmds on hosta
+ userb ran 5 sudo cmds on hosta
+
+Sudo usage by cmd/user/host
+ userb ran /usr/bin/tail /var/log/auth.log as root on hosta: 2 times
+ userb ran /bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
+ userb ran /bin/grep -i ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/chown usera auth.log as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
+ userb ran /usr/bin/head /var/log/auth.log as root on hosta: 1 times
+
+Sudo usage by user/host
+ usera ran 4 sudo cmds on hosta
+ userb ran 5 sudo cmds on hosta
+
diff --git a/testcases/19/logparse.conf.1 b/testcases/19/logparse.conf.1
new file mode 100644
index 0000000..4da2a88
--- /dev/null
+++ b/testcases/19/logparse.conf.1
@@ -0,0 +1,26 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 APP
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+#######################
diff --git a/testcases/19/logparse.conf.2 b/testcases/19/logparse.conf.2
new file mode 100644
index 0000000..b9393ad
--- /dev/null
+++ b/testcases/19/logparse.conf.2
@@ -0,0 +1,25 @@
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE sudo {
+ APP sudo
+ MSG /.* : .* ; PWD=/
+ ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
+ ACTION MSG /(.*): \(command continued\) / IGNORE
+ REPORT "Sudo usage by cmd/user/host" "{2} ran {4} as {3} on {1}: {x} times" count
+ REPORT "Sudo usage by user/host" "{2} ran {x} sudo cmds on {1}" count
+ # by default {x} is total
+}
+
+RULE sudo-ignore {
+ APP sudo
+ MSG /\(command continued\)/
+ ACTION MSG /.* : \(command continued\)/ IGNORE
+}
+#######################
+#2
|
mikeknox/LogParse | fc35deedda9ac55b9fcdd5487bbbd8fa0fd2c1ca | Added input & output data file capablity Also able to reprocess unmatched lines when loading data. | diff --git a/logparse.pl b/logparse.pl
index e706a4f..aacb87b 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1207 +1,1285 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Long;
use Data::Dumper qw(Dumper);
+use Storable;
# Globals
#
my $STARTTIME = time();
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my @CONFIGFILES;# = ("logparse.conf");
-my %cfghash;
-my %reshash;
+my %datahash;
+
+#my %cfghash;
+#my %reshash;
my $UNMATCHEDLINES = 1;
my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
my $MATCH; # Only lines matching this regex will be parsed
my $COLOR = 0;
+my $INPUT; # Where to load %cfghash & %reshash
+# If set, load data and then generate report
+# config files have also been set, update %cfghash and then process ignored lines before generating report
+my $OUTPUT; # Where to save %cfghash & %reshash
my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
"l|log=s" => \@LOGFILES,
"d|debug=i" => \$DEBUG,
"m|match=s" => \$MATCH,
+ "o|outpur=s" => \$OUTPUT,
+ "i|inpur=s" => \$INPUT,
"color" => \$COLOR
);
unless ($result) {
- warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>] [--color]\nInvalid config options passed");
+ warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>] [--color] [-m|--match] [-o|--output] [-i|--input]\nInvalid config options passed");
}
if ($COLOR) {
use Term::ANSIColor qw(:constants);
}
@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
@LOGFILES = split(/,/,join(',',@LOGFILES));
if ($MATCH) {
$MATCH =~ s/\^\"//;
$MATCH =~ s/\"$//;
logmsg (2, 3, "Skipping lines which match $MATCH");
}
-loadcfg (\%cfghash, \@CONFIGFILES);
-logmsg(7, 3, "cfghash:", \%cfghash);
-processlogfile(\%cfghash, \%reshash, \@LOGFILES);
-logmsg (9, 0, "reshash ..\n", %reshash);
-report(\%cfghash, \%reshash);
+if ($INPUT) {
+ logmsg (1, 2, "Loading data from $INPUT");
+ %datahash = %{ retrieve ($INPUT) } or die "Unable to load data from $INPUT";
+}
+
+my $cfghash = \%{$datahash{cfg}};
+loadcfg ($cfghash, \@CONFIGFILES);
+logmsg(7, 3, "cfghash:", $cfghash);
+my $reshash = \%{$datahash{res}};
+
+if ($INPUT) {
+ processdatafile($cfghash, $reshash);
+} else {
+ processlogfile($cfghash, $reshash, \@LOGFILES);
+}
+
+if ($OUTPUT) {
+ logmsg (1, 2, "Saving data in $OUTPUT");
+ store (\%datahash, $OUTPUT ) or die "Can't output data to $OUTPUT";
+}
+
+logmsg (9, 0, "reshash ..\n", $reshash);
+report($cfghash, $reshash);
-logmsg (9, 0, "reshash ..\n", %reshash);
-logmsg (9, 0, "cfghash ..\n", %cfghash);
+logmsg (9, 0, "reshash ..\n", $reshash);
+logmsg (9, 0, "cfghash ..\n", $cfghash);
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text does not contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ", \@tmp);
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
logmsg (6, 4, "line results now ...", $linehashref);
}
+sub processdatafile {
+ my $cfghashref = shift;
+ my $reshashref = shift;
+
+ my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
+ my %lastline;
+
+ logmsg(5, 1, " and I was called by ... ".&whowasi);
+
+ if (exists ($$reshashref{nomatch}) ) {
+ my @nomatch = @{ $$reshashref{nomatch} };
+ @{ $$reshashref{nomatch} } = ();
+ #foreach my $line (@{@$reshashref{nomatch}}) {
+ foreach my $dataline (@nomatch) {
+ my %line;
+ # Placing line and line componenents into a hash to be passed to actrule, components can then be refered
+ # to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
+ $line{line} = $dataline;
+ $line{line} =~ s/\s+?$//;
+
+ logmsg(5, 1, "Processing next line");
+ logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
+ logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
+
+ processline ($cfghashref, $reshashref, \%line, $format, \%lastline);
+ }
+ }
+}
+
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Processing logfiles: ", $logfileref);
foreach my $logfile (@$logfileref) {
logmsg(1, 0, "processing $logfile using format $format...");
open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
$line{line} =~ s/\s+?$//;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
#logmsg(5, 1, "skipping as line doesn't match the match regex") and
- parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
+ processline ($cfghashref, $reshashref, \%line, $format, \%lastline);
+ }
+ close LOGFILE;
+ logmsg (1, 0, "Finished processing $logfile.");
+ } # loop through logfiles
+}
+
+sub processline {
+ my $cfghashref = shift;
+ my $reshashref = shift;
+ my $lineref = shift;
+ my $format = shift;
+ my $lastlineref = shift;
+
+ parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $$lineref{line}, $lineref);
- logmsg(9, 1, "Checking line: $line{line}");
- #logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
+ logmsg(9, 1, "Checking line: $$lineref{line}");
- if (not $MATCH or $line{line} =~ /$MATCH/) {
- my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
- logmsg(9, 2, keys (%rules)." matches so far");
-
- #TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
- #UP to here
- # FORMAT stanza contains a substanza which describes repeat for the given format
- # format{repeat}{cmd} - normally regex, not sure what other solutions would apply
- # format{repeat}{regex} - array of regex's hashes
- # format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
+ if (not $MATCH or $$lineref{line} =~ /$MATCH/) {
+ my %rules = matchrules(\%{ $$cfghashref{RULE} }, $lineref );
+ logmsg(9, 2, keys (%rules)." matches so far");
+
+ #TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
+ #UP to here
+ # FORMAT stanza contains a substanza which describes repeat for the given format
+ # format{repeat}{cmd} - normally regex, not sure what other solutions would apply
+ # format{repeat}{regex} - array of regex's hashes
+ # format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
- #TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
- # Detect and count repeats
- if (keys %rules >= 0) {
- logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
-
- # loop through matching rules and collect data as defined in the ACTIONS section of %config
- my $actrule = 0;
- my %tmprules = %rules;
- for my $rule (keys %tmprules) {
- logmsg (9, 3, "checking rule: $rule");
- my $execruleret = 0;
- if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
- $execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
- } else {
- logmsg (2, 3, "No actions defined for rule; $rule");
- }
- logmsg (9, 4, "execrule returning $execruleret");
- delete $rules{$rule} unless $execruleret;
+ #TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
+ # Detect and count repeats
+ if (keys %rules >= 0) {
+ logmsg (5, 2, "matched ".keys(%rules)." rules from line $$lineref{line}");
+
+ # loop through matching rules and collect data as defined in the ACTIONS section of %config
+ my $actrule = 0;
+ my %tmprules = %rules;
+ for my $rule (keys %tmprules) {
+ logmsg (9, 3, "checking rule: $rule");
+ my $execruleret = 0;
+ if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
+ $execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, $lineref);
+ } else {
+ logmsg (2, 3, "No actions defined for rule; $rule");
+ }
+ logmsg (9, 4, "execrule returning $execruleret");
+ delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
- }
- logmsg (9, 3, "#rules in list .., ".keys(%rules) );
- logmsg (9, 3, "\%rules ..", \%rules);
- $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
- # lastline & repeat
- } # rules > 0
- if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
- delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
- }
- $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
-
- if ( keys(%rules) == 0) {
- # Add new unmatched linescode
- }
- } else {
- logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
+ }
+ logmsg (9, 3, "#rules in list .., ".keys(%rules) );
+ logmsg (9, 3, "\%rules ..", \%rules);
+ $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $$lineref{line} if keys(%rules) == 0;
+ # lastline & repeat
+ } # rules > 0
+ if (exists( $$lastlineref{ $$lineref{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
+ delete ($$lastlineref{ $$lineref{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
- logmsg(9 ,1, "Results hash ...", \%$reshashref );
- logmsg (5, 1, "finished processing line");
+ $$lastlineref{ $$lineref{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %{ $lineref};
+
+ if ( keys(%rules) == 0) {
+ # Add new unmatched linescode
}
- close LOGFILE;
- logmsg (1, 0, "Finished processing $logfile.");
- } # loop through logfiles
+ } else {
+ logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
+ }
+ logmsg(9 ,1, "Results hash ...", \%$reshashref );
+ logmsg (5, 1, "finished processing line");
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+\/|\{.+?\}|".+?"|\d+=".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
# $$actionref[$actionindex]{regex} =~ s/\//\/\//g;
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
$$reportref[$reportindex]{regex} =~ s/^"//;
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line\n";
}
}
if ($COLOR) {
print RED "\n\nSummaries:\n", RESET;
} else {
print "\n\nSummaries:\n";
}
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
logmsg (4, 1, "Processing report# $rptid for rule: $rule ...");
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (5, 2, "\%ruleresults rule ($rule) report ID ($rptid) ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
if ($COLOR) {
print BLUE "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n", RESET;
} else {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
}
} else {
logmsg (4, 2, "Report has no title for rule: $rule\[$rptid\]");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
if ($COLOR) {
print GREEN rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key), RESET;
} else {
print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
}
} else {
if ($COLOR) {
print GREEN "\t$$reshashref{$rule}{$key}: $key\n", RESET;
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
logmsg (9, 5, "cfghashref ...", $cfghashref);
logmsg (9, 5, "reshashref ...", $reshashref);
for my $actionid (keys( %$reshashref ) ) {
logmsg (5, 5, "Processing actionid: $actionid ...");
for my $key (keys %{ $$reshashref{$actionid} } ) {
logmsg (5, 6, "Processing key: $key for actionid: $actionid");
(my @values) = split (/:/, $key);
logmsg (9, 7, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
logmsg (5, 7, "Processing report ID: $rptid with key: $key for actionid: $actionid");
if (exists($$cfghashref{reports}[$rptid]{field})) {
logmsg (9, 8, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 7, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
# Compare max fieldid to number of entries in $key, skip if maxid > $key
my $targetmaxfield = array_max(\@targetfieldids);
if ($targetmaxfield > ($#values + 1) ) {
#warning ("w", "There is a field id in the report line that is greater than the number of items in this line's data set, skipping.");
logmsg (2, 5, "There is a field id ($targetmaxfield) in the target key greater than the number of fields ($#values) in the key, skipping");
next;
}
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 8, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} elsif ($fieldid == $$cfghashref{reports}[$rptid]{field} ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid is used report matching, so adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 9, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
logmsg (9, 8, "targetkeymatch is now: $targetkeymatch");
}
$targetkeymatch =~ s/^://;
$targetkeymatch =~ s/\[/\\\[/g;
$targetkeymatch =~ s/\]/\\\]/g;
$targetkeymatch =~ s/\(/\\\(/g;
$targetkeymatch =~ s/\)/\\\)/g;
logmsg (9, 7, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$targetkeymatch =~ s/\\\(/\(/g;
$targetkeymatch =~ s/\\\)/\)/g;
$targetkeymatch =~ s/\\\[/\[/g;
$targetkeymatch =~ s/\\\]/\]/g;
logmsg (9, 8, "$key does matched $targetkeymatch, so I'm doing the necssary calcs ...");
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Incremented count for report\[$rptid\]\[$targetkeymatch\] by $$reshashref{$actionid}{$key}{count} so it's now $$reshashref{$actionid}{$key}{count}");
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
logmsg (9, 9, "Added $$reshashref{$actionid}{$key}{total} to total for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{total}");
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Avg for report\[$rptid\]\[$targetkeymatch\] is now $results{$rptid}{$targetkeymatch}{avg}");
if ($results{$rptid}{$targetkeymatch}{max} < $$reshashref{$actionid}{$key}{max} ) {
$results{$rptid}{$targetkeymatch}{max} = $$reshashref{$actionid}{$key}{max};
logmsg (9, 9, "Setting $$reshashref{$actionid}{$key}{max} to max for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{max}");
}
if ($results{$rptid}{$targetkeymatch}{min} > $$reshashref{$actionid}{$key}{min} ) {
$results{$rptid}{$targetkeymatch}{min} = $$reshashref{$actionid}{$key}{min};
logmsg (9, 9, "Setting $$reshashref{$actionid}{$key}{max} to max for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{max}");
}
} else {
logmsg (9, 8, "$key does not match $targetkeymatch<eol>");
logmsg (9, 8, " key $key<eol>");
logmsg (9, 8, "targetkey $targetkeymatch<eol>");
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
logmsg (9, 5, "Returning ... results", \%results);
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ", $cfghashref);
logmsg (7, 3, "reshash ... ", $reshashref);
my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/MAX/i) {
$line =~ s/\{x\}/$$reshashref{$key}{max}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{max} (max)");
} elsif (/MIN/i) {
$line =~ s/\{x\}/$$reshashref{$key}{min}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{min} (min)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "Settting \$fields[$field] ($fields[$field]) = \$fields[$i] ($fields[$i])");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
$line.="\n";
#if (exists($$cfghashref{field})) {
#logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
#if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
#logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
#$line = "";
#}
#}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
logmsg (9, 5, "Matchlist ... $matchlist");
logmsg (9, 5, "Matchlist has morphed in \@matrix with elements ... ", \@matrix);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
logmsg (9, 6, "\$matchlist didn't have a \",\", so we shoved it onto \@matrix. Which is now ... ", \@matrix);
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
logmsg (9, 7, "\$i: $i");
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
logmsg (9, 8, "element $i ($matrix[$i]) was an integer so we pushed it onto the matrix");
} else {
logmsg (9, 8, "element $i ($matrix[$i]) wasn't an integer so we ignored it");
}
}
if ($numericonly) {
logmsg (9, 5, "Returning numeric only results ... ", \@tmpmatrix);
return @tmpmatrix;
} else {
logmsg (9, 5, "Returning full results ... ", \@matrix);
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid using matches $$cfghashref{matches}");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0; # 0 - nomatch 1 - match
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
} else {
logmsg(8, 6, "line didn't match negative regex");
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
} else {
logmsg(8, 5, "Using regex /$$cfghashref{regex}/ on field content: $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
} else {
logmsg(8, 6, "line didn't match regex");
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
logmsg (8, 4, "Regex for action has been applied, processing results now ...");
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count|sum|max|min/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
if ($$reshashref{$rule}{$actionid}{$matchid}{max} < $resmatrix[ $$cfghashref{sourcefield} ] ) {
$$reshashref{$rule}{$actionid}{$matchid}{max} = $resmatrix[ $$cfghashref{sourcefield} ];
}
if ($$reshashref{$rule}{$actionid}{$matchid}{min} > $resmatrix[ $$cfghashref{sourcefield} ] ) {
$$reshashref{$rule}{$actionid}{$matchid}{min} = $resmatrix[ $$cfghashref{sourcefield} ];
}
#} elsif (/sum/i) {
#$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
#$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
#
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
} else {
logmsg(5, 5, "retval ($retval) was not set so we haven't processed the results");
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..", \@matrix);
logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
logmsg (9, 4, "cfghashref:", $cfghashref);
for my $rule (keys %{ $cfghashref } ) {
logmsg (9, 4, "Checking to see if $rule applies ...");
if (matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref)) {
$rules{$rule} = $rule ;
logmsg (9, 5, "it matches");
} else {
logmsg (9, 5, "it doesn't match");
}
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1; # 1 = match, 0 = fail
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
logmsg (9, 5, "cfghashref:", $cfghashref);
if (exists ( $$cfghashref{fields} ) ) {
logmsg (9, 5, "cfghashref{fields}:", \%{ $$cfghashref{fields} });
}
logmsg (9, 5, "linehashref:", $linehashref);
foreach my $field (keys (%{ $cfghashref } ) ) {
logmsg(9, 6, "checking field: $field with value: $$cfghashref{$field}");
logmsg (9, 7, "Does field ($field) with value: $$linehashref{ $field } match the following regex ...");
if ($$cfghashref{$field} =~ /^!/) {
my $exp = $$cfghashref{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
logmsg (9, 8, "neg regexp compar /$$linehashref{ $field }/ !~ /$exp/, ret=$ret");
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{$field}/);
logmsg (9, 8, "regexp compar /$$linehashref{$field}/ =~ /$$cfghashref{$field}/, ret=$ret");
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
my $dumpvar = shift;
my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
# TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
if ($COLOR) {
print STDERR GREEN whowasi."(): d=${time}s:", RESET;
} else {
print STDERR whowasi."(): d=${time}s:";
}
print STDERR " $msg";
if ($dumpvar) {
if ($COLOR) {
print STDERR BLUE Dumper($dumpvar), RESET;
} else {
print STDERR Dumper($dumpvar);
}
}
print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
if ($COLOR >= 1) {
print RED, "WARNING: $msg\n", RESET;
} else {
print "WARNING: $msg\n";
}
} elsif (/e|error/i) {
if ($COLOR >= 1) {
print RED, "ERROR: $msg\n", RESET;
} else {
print "ERROR: $msg\n";
}
} elsif (/c|critical/i) {
if ($COLOR >= 1) {
print RED, "CRITICAL error, aborted ... $msg\n", RESET;
} else {
print "CRITICAL error, aborted ... $msg\n";
}
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
sub array_max {
my $arrayref = shift; # ref to array
my $highestvalue = $$arrayref[0];
for my $i (0 .. @$arrayref ) {
$highestvalue = $$arrayref[$i] if $$arrayref[$i] > $highestvalue;
}
return $highestvalue;
}
+sub loaddata {
+ my $datafile = shift;
+ my $datahashref = shift;
+
+ %{$$datahashref} = retrive($datafile);
+}
+
+sub savedata {
+ my $datafile = shift;
+ my $datahashref = shift;
+
+ store ($datahashref, $datafile) or die "Can't output data to $datafile";
+}
diff --git a/testcases/15/datafile b/testcases/15/datafile
new file mode 100644
index 0000000..165b7d7
Binary files /dev/null and b/testcases/15/datafile differ
diff --git a/testcases/16/Description b/testcases/16/Description
new file mode 100644
index 0000000..3ea7a8a
--- /dev/null
+++ b/testcases/16/Description
@@ -0,0 +1,4 @@
+Save data file
+TC#17 will then load datafile
+
+Based on TC#7
diff --git a/testcases/16/args b/testcases/16/args
new file mode 100755
index 0000000..593b658
--- /dev/null
+++ b/testcases/16/args
@@ -0,0 +1 @@
+${LOGPARSE} -l ./test.log.1 -l ./test.log.2 -c ./logparse.conf.1 -c ./logparse.conf.2 -d 0 -o ./datafile
diff --git a/testcases/16/expected.output b/testcases/16/expected.output
new file mode 100644
index 0000000..39aa064
--- /dev/null
+++ b/testcases/16/expected.output
@@ -0,0 +1,22 @@
+
+
+No match for lines:
+ Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+ Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+ Oct 2 15:01:35 hosta sudo: userb : (command continued) /var/log/syslog.1.gz /var/log/syslog.2.gz /var/log/syslog.3.gz /var/log/syslog.4.gz /var/log/syslog.5.gz /var/log/syslog.6.gz /var/log/udev /var/log/user.log /var/log/wtmp /var/log/wtmp.1
+
+
+Summaries:
+Sudo usage by cmd/user/host
+ userb ran /usr/bin/tail /var/log/auth.log as root on hosta: 2 times
+ usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
+ userb ran /bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog as root on hosta: 1 times
+ userb ran /bin/grep -i ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/chown usera auth.log as root on hosta: 1 times
+ userb ran /usr/bin/head /var/log/auth.log as root on hosta: 1 times
+
+Sudo usage by user/host
+ usera ran 4 sudo cmds on hosta
+ userb ran 5 sudo cmds on hosta
+
diff --git a/testcases/16/logparse.conf.1 b/testcases/16/logparse.conf.1
new file mode 100644
index 0000000..4da2a88
--- /dev/null
+++ b/testcases/16/logparse.conf.1
@@ -0,0 +1,26 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 APP
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+#######################
diff --git a/testcases/16/logparse.conf.2 b/testcases/16/logparse.conf.2
new file mode 100644
index 0000000..e346fe4
--- /dev/null
+++ b/testcases/16/logparse.conf.2
@@ -0,0 +1,19 @@
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE sudo {
+ APP sudo
+ MSG /.* : .* ; PWD=/
+ ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
+ ACTION MSG /(.*): \(command continued\) / IGNORE
+ REPORT "Sudo usage by cmd/user/host" "{2} ran {4} as {3} on {1}: {x} times" count
+ REPORT "Sudo usage by user/host" "{2} ran {x} sudo cmds on {1}" count
+ # by default {x} is total
+}
+#######################
+#2
diff --git a/testcases/16/test.log.1 b/testcases/16/test.log.1
new file mode 100644
index 0000000..8120f96
--- /dev/null
+++ b/testcases/16/test.log.1
@@ -0,0 +1,6 @@
+Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+Oct 2 15:01:19 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/syslog
+Oct 2 15:01:22 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/syslog
+Oct 2 15:01:25 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/messages
+Oct 2 15:01:31 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep -i ssh /var/log/messages
diff --git a/testcases/16/test.log.2 b/testcases/16/test.log.2
new file mode 100644
index 0000000..8a3df2e
--- /dev/null
+++ b/testcases/16/test.log.2
@@ -0,0 +1,6 @@
+Oct 2 15:01:35 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog
+Oct 2 15:01:35 hosta sudo: userb : (command continued) /var/log/syslog.1.gz /var/log/syslog.2.gz /var/log/syslog.3.gz /var/log/syslog.4.gz /var/log/syslog.5.gz /var/log/syslog.6.gz /var/log/udev /var/log/user.log /var/log/wtmp /var/log/wtmp.1
+Oct 2 15:02:17 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/head /var/log/auth.log
+Oct 2 15:02:22 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/chown usera auth.log
+Oct 2 15:02:55 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/tail /var/log/auth.log
+Oct 2 15:03:50 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/tail /var/log/auth.log
diff --git a/testcases/17/Description b/testcases/17/Description
new file mode 100644
index 0000000..37f4d95
--- /dev/null
+++ b/testcases/17/Description
@@ -0,0 +1,3 @@
+Load datafile from TC#16, but no updata config files
+
+Based on TC#7
diff --git a/testcases/17/args b/testcases/17/args
new file mode 100755
index 0000000..6589f58
--- /dev/null
+++ b/testcases/17/args
@@ -0,0 +1 @@
+${LOGPARSE} -d 0 -i ../16/datafile
diff --git a/testcases/17/expected.output b/testcases/17/expected.output
new file mode 100644
index 0000000..39aa064
--- /dev/null
+++ b/testcases/17/expected.output
@@ -0,0 +1,22 @@
+
+
+No match for lines:
+ Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+ Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+ Oct 2 15:01:35 hosta sudo: userb : (command continued) /var/log/syslog.1.gz /var/log/syslog.2.gz /var/log/syslog.3.gz /var/log/syslog.4.gz /var/log/syslog.5.gz /var/log/syslog.6.gz /var/log/udev /var/log/user.log /var/log/wtmp /var/log/wtmp.1
+
+
+Summaries:
+Sudo usage by cmd/user/host
+ userb ran /usr/bin/tail /var/log/auth.log as root on hosta: 2 times
+ usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
+ userb ran /bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog as root on hosta: 1 times
+ userb ran /bin/grep -i ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/chown usera auth.log as root on hosta: 1 times
+ userb ran /usr/bin/head /var/log/auth.log as root on hosta: 1 times
+
+Sudo usage by user/host
+ usera ran 4 sudo cmds on hosta
+ userb ran 5 sudo cmds on hosta
+
diff --git a/testcases/17/logparse.conf.1 b/testcases/17/logparse.conf.1
new file mode 100644
index 0000000..4da2a88
--- /dev/null
+++ b/testcases/17/logparse.conf.1
@@ -0,0 +1,26 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 APP
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+#######################
diff --git a/testcases/17/logparse.conf.2 b/testcases/17/logparse.conf.2
new file mode 100644
index 0000000..e346fe4
--- /dev/null
+++ b/testcases/17/logparse.conf.2
@@ -0,0 +1,19 @@
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE sudo {
+ APP sudo
+ MSG /.* : .* ; PWD=/
+ ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
+ ACTION MSG /(.*): \(command continued\) / IGNORE
+ REPORT "Sudo usage by cmd/user/host" "{2} ran {4} as {3} on {1}: {x} times" count
+ REPORT "Sudo usage by user/host" "{2} ran {x} sudo cmds on {1}" count
+ # by default {x} is total
+}
+#######################
+#2
diff --git a/testcases/18/Description b/testcases/18/Description
new file mode 100644
index 0000000..07b1e36
--- /dev/null
+++ b/testcases/18/Description
@@ -0,0 +1,4 @@
+Load datafile from TC#16
+and process using updated config files
+
+Based on TC#7
diff --git a/testcases/18/args b/testcases/18/args
new file mode 100755
index 0000000..be0b44b
--- /dev/null
+++ b/testcases/18/args
@@ -0,0 +1 @@
+${LOGPARSE} -c ./logparse.conf.1 -c ./logparse.conf.2 -d 0 -i ../16/datafile
diff --git a/testcases/18/expected.output b/testcases/18/expected.output
new file mode 100644
index 0000000..e2b8580
--- /dev/null
+++ b/testcases/18/expected.output
@@ -0,0 +1,21 @@
+
+
+No match for lines:
+ Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+ Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+
+
+Summaries:
+Sudo usage by cmd/user/host
+ userb ran /usr/bin/tail /var/log/auth.log as root on hosta: 2 times
+ usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
+ userb ran /bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog as root on hosta: 1 times
+ userb ran /bin/grep -i ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/chown usera auth.log as root on hosta: 1 times
+ userb ran /usr/bin/head /var/log/auth.log as root on hosta: 1 times
+
+Sudo usage by user/host
+ usera ran 4 sudo cmds on hosta
+ userb ran 5 sudo cmds on hosta
+
diff --git a/testcases/18/logparse.conf.1 b/testcases/18/logparse.conf.1
new file mode 100644
index 0000000..4da2a88
--- /dev/null
+++ b/testcases/18/logparse.conf.1
@@ -0,0 +1,26 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 APP
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+#######################
diff --git a/testcases/18/logparse.conf.2 b/testcases/18/logparse.conf.2
new file mode 100644
index 0000000..b9393ad
--- /dev/null
+++ b/testcases/18/logparse.conf.2
@@ -0,0 +1,25 @@
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE sudo {
+ APP sudo
+ MSG /.* : .* ; PWD=/
+ ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
+ ACTION MSG /(.*): \(command continued\) / IGNORE
+ REPORT "Sudo usage by cmd/user/host" "{2} ran {4} as {3} on {1}: {x} times" count
+ REPORT "Sudo usage by user/host" "{2} ran {x} sudo cmds on {1}" count
+ # by default {x} is total
+}
+
+RULE sudo-ignore {
+ APP sudo
+ MSG /\(command continued\)/
+ ACTION MSG /.* : \(command continued\)/ IGNORE
+}
+#######################
+#2
|
mikeknox/LogParse | 440e16135961b4003c4ec6c195afff7ca876703f | Fixed reportoptions for total & avg Added min & max Also test case for min, max, total (sum) and avg in addition to count options | diff --git a/logparse.pl b/logparse.pl
index 5d85fc9..e706a4f 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -234,951 +234,974 @@ sub processlogfile {
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
#logmsg(5, 1, "skipping as line doesn't match the match regex") and
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
logmsg(9, 1, "Checking line: $line{line}");
#logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
if (not $MATCH or $line{line} =~ /$MATCH/) {
my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
if (keys %rules >= 0) {
logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
$execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
logmsg (9, 3, "#rules in list .., ".keys(%rules) );
logmsg (9, 3, "\%rules ..", \%rules);
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
} else {
logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
}
logmsg(9 ,1, "Results hash ...", \%$reshashref );
logmsg (5, 1, "finished processing line");
}
close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+\/|\{.+?\}|".+?"|\d+=".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
# $$actionref[$actionindex]{regex} =~ s/\//\/\//g;
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
$$reportref[$reportindex]{regex} =~ s/^"//;
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line\n";
}
}
if ($COLOR) {
print RED "\n\nSummaries:\n", RESET;
} else {
print "\n\nSummaries:\n";
}
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
logmsg (4, 1, "Processing report# $rptid for rule: $rule ...");
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (5, 2, "\%ruleresults rule ($rule) report ID ($rptid) ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
if ($COLOR) {
print BLUE "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n", RESET;
} else {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
}
} else {
logmsg (4, 2, "Report has no title for rule: $rule\[$rptid\]");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
if ($COLOR) {
print GREEN rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key), RESET;
} else {
print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
}
} else {
if ($COLOR) {
print GREEN "\t$$reshashref{$rule}{$key}: $key\n", RESET;
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
logmsg (9, 5, "cfghashref ...", $cfghashref);
logmsg (9, 5, "reshashref ...", $reshashref);
for my $actionid (keys( %$reshashref ) ) {
logmsg (5, 5, "Processing actionid: $actionid ...");
for my $key (keys %{ $$reshashref{$actionid} } ) {
logmsg (5, 6, "Processing key: $key for actionid: $actionid");
(my @values) = split (/:/, $key);
logmsg (9, 7, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
logmsg (5, 7, "Processing report ID: $rptid with key: $key for actionid: $actionid");
if (exists($$cfghashref{reports}[$rptid]{field})) {
logmsg (9, 8, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 7, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
# Compare max fieldid to number of entries in $key, skip if maxid > $key
my $targetmaxfield = array_max(\@targetfieldids);
if ($targetmaxfield > ($#values + 1) ) {
#warning ("w", "There is a field id in the report line that is greater than the number of items in this line's data set, skipping.");
logmsg (2, 5, "There is a field id ($targetmaxfield) in the target key greater than the number of fields ($#values) in the key, skipping");
next;
}
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 8, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} elsif ($fieldid == $$cfghashref{reports}[$rptid]{field} ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid is used report matching, so adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 9, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
logmsg (9, 8, "targetkeymatch is now: $targetkeymatch");
}
$targetkeymatch =~ s/^://;
$targetkeymatch =~ s/\[/\\\[/g;
$targetkeymatch =~ s/\]/\\\]/g;
$targetkeymatch =~ s/\(/\\\(/g;
$targetkeymatch =~ s/\)/\\\)/g;
logmsg (9, 7, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$targetkeymatch =~ s/\\\(/\(/g;
$targetkeymatch =~ s/\\\)/\)/g;
$targetkeymatch =~ s/\\\[/\[/g;
$targetkeymatch =~ s/\\\]/\]/g;
logmsg (9, 8, "$key does matched $targetkeymatch, so I'm doing the necssary calcs ...");
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Incremented count for report\[$rptid\]\[$targetkeymatch\] by $$reshashref{$actionid}{$key}{count} so it's now $$reshashref{$actionid}{$key}{count}");
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
- logmsg (9, 9, "Added $$reshashref{$actionid}{$key}{total} to total for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{count}");
+ logmsg (9, 9, "Added $$reshashref{$actionid}{$key}{total} to total for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{total}");
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Avg for report\[$rptid\]\[$targetkeymatch\] is now $results{$rptid}{$targetkeymatch}{avg}");
+
+ if ($results{$rptid}{$targetkeymatch}{max} < $$reshashref{$actionid}{$key}{max} ) {
+ $results{$rptid}{$targetkeymatch}{max} = $$reshashref{$actionid}{$key}{max};
+ logmsg (9, 9, "Setting $$reshashref{$actionid}{$key}{max} to max for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{max}");
+ }
+
+ if ($results{$rptid}{$targetkeymatch}{min} > $$reshashref{$actionid}{$key}{min} ) {
+ $results{$rptid}{$targetkeymatch}{min} = $$reshashref{$actionid}{$key}{min};
+ logmsg (9, 9, "Setting $$reshashref{$actionid}{$key}{max} to max for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{max}");
+ }
} else {
logmsg (9, 8, "$key does not match $targetkeymatch<eol>");
logmsg (9, 8, " key $key<eol>");
logmsg (9, 8, "targetkey $targetkeymatch<eol>");
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
logmsg (9, 5, "Returning ... results", \%results);
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ", $cfghashref);
logmsg (7, 3, "reshash ... ", $reshashref);
my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
+ } elsif (/MAX/i) {
+ $line =~ s/\{x\}/$$reshashref{$key}{max}/;
+ logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{max} (max)");
+ } elsif (/MIN/i) {
+ $line =~ s/\{x\}/$$reshashref{$key}{min}/;
+ logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{min} (min)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "Settting \$fields[$field] ($fields[$field]) = \$fields[$i] ($fields[$i])");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
$line.="\n";
#if (exists($$cfghashref{field})) {
#logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
#if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
#logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
#$line = "";
#}
#}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
logmsg (9, 5, "Matchlist ... $matchlist");
logmsg (9, 5, "Matchlist has morphed in \@matrix with elements ... ", \@matrix);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
logmsg (9, 6, "\$matchlist didn't have a \",\", so we shoved it onto \@matrix. Which is now ... ", \@matrix);
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
logmsg (9, 7, "\$i: $i");
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
logmsg (9, 8, "element $i ($matrix[$i]) was an integer so we pushed it onto the matrix");
} else {
logmsg (9, 8, "element $i ($matrix[$i]) wasn't an integer so we ignored it");
}
}
if ($numericonly) {
logmsg (9, 5, "Returning numeric only results ... ", \@tmpmatrix);
return @tmpmatrix;
} else {
logmsg (9, 5, "Returning full results ... ", \@matrix);
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid using matches $$cfghashref{matches}");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0; # 0 - nomatch 1 - match
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
} else {
logmsg(8, 6, "line didn't match negative regex");
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
} else {
logmsg(8, 5, "Using regex /$$cfghashref{regex}/ on field content: $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
} else {
logmsg(8, 6, "line didn't match regex");
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
logmsg (8, 4, "Regex for action has been applied, processing results now ...");
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
- if (/count/i) {
- $$reshashref{$rule}{$actionid}{$matchid}{count}++;
- } elsif (/sum/i) {
+ if (/count|sum|max|min/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
+ if ($$reshashref{$rule}{$actionid}{$matchid}{max} < $resmatrix[ $$cfghashref{sourcefield} ] ) {
+ $$reshashref{$rule}{$actionid}{$matchid}{max} = $resmatrix[ $$cfghashref{sourcefield} ];
+ }
+ if ($$reshashref{$rule}{$actionid}{$matchid}{min} > $resmatrix[ $$cfghashref{sourcefield} ] ) {
+ $$reshashref{$rule}{$actionid}{$matchid}{min} = $resmatrix[ $$cfghashref{sourcefield} ];
+ }
+ #} elsif (/sum/i) {
+ #$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
+ #$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
-
+ #
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
} else {
logmsg(5, 5, "retval ($retval) was not set so we haven't processed the results");
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..", \@matrix);
logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
logmsg (9, 4, "cfghashref:", $cfghashref);
for my $rule (keys %{ $cfghashref } ) {
logmsg (9, 4, "Checking to see if $rule applies ...");
if (matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref)) {
$rules{$rule} = $rule ;
logmsg (9, 5, "it matches");
} else {
logmsg (9, 5, "it doesn't match");
}
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1; # 1 = match, 0 = fail
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
logmsg (9, 5, "cfghashref:", $cfghashref);
if (exists ( $$cfghashref{fields} ) ) {
logmsg (9, 5, "cfghashref{fields}:", \%{ $$cfghashref{fields} });
}
logmsg (9, 5, "linehashref:", $linehashref);
foreach my $field (keys (%{ $cfghashref } ) ) {
logmsg(9, 6, "checking field: $field with value: $$cfghashref{$field}");
logmsg (9, 7, "Does field ($field) with value: $$linehashref{ $field } match the following regex ...");
if ($$cfghashref{$field} =~ /^!/) {
my $exp = $$cfghashref{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
logmsg (9, 8, "neg regexp compar /$$linehashref{ $field }/ !~ /$exp/, ret=$ret");
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{$field}/);
logmsg (9, 8, "regexp compar /$$linehashref{$field}/ =~ /$$cfghashref{$field}/, ret=$ret");
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
my $dumpvar = shift;
my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
# TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
if ($COLOR) {
print STDERR GREEN whowasi."(): d=${time}s:", RESET;
} else {
print STDERR whowasi."(): d=${time}s:";
}
print STDERR " $msg";
if ($dumpvar) {
if ($COLOR) {
print STDERR BLUE Dumper($dumpvar), RESET;
} else {
print STDERR Dumper($dumpvar);
}
}
print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
if ($COLOR >= 1) {
print RED, "WARNING: $msg\n", RESET;
} else {
print "WARNING: $msg\n";
}
} elsif (/e|error/i) {
if ($COLOR >= 1) {
print RED, "ERROR: $msg\n", RESET;
} else {
print "ERROR: $msg\n";
}
} elsif (/c|critical/i) {
if ($COLOR >= 1) {
print RED, "CRITICAL error, aborted ... $msg\n", RESET;
} else {
print "CRITICAL error, aborted ... $msg\n";
}
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
sub array_max {
my $arrayref = shift; # ref to array
my $highestvalue = $$arrayref[0];
for my $i (0 .. @$arrayref ) {
$highestvalue = $$arrayref[$i] if $$arrayref[$i] > $highestvalue;
}
return $highestvalue;
}
diff --git a/testcases/15/Description b/testcases/15/Description
new file mode 100644
index 0000000..34596a4
--- /dev/null
+++ b/testcases/15/Description
@@ -0,0 +1 @@
+Additional summarisation tests
diff --git a/testcases/15/expected.output b/testcases/15/expected.output
new file mode 100644
index 0000000..5676f67
--- /dev/null
+++ b/testcases/15/expected.output
@@ -0,0 +1,21 @@
+
+
+No match for lines:
+
+
+Summaries:
+xntpd resets
+ 6 xntpd reset's on hostA
+
+xntpd total time reset
+ total resets on hostA is: 1.741271s
+
+xntpd max reset time
+ max reset on hostA is: 0.530498s
+
+xntpd min reset time
+ min reset on hostA is: -0.288730s
+
+xntpd average reset time
+ avergae reset on hostA is: 0.290s
+
diff --git a/testcases/15/logparse.conf b/testcases/15/logparse.conf
new file mode 100644
index 0000000..2e185f5
--- /dev/null
+++ b/testcases/15/logparse.conf
@@ -0,0 +1,46 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 8 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 APP
+ FIELD 6 TAG
+ FIELD 7 FACLEV
+ FIELDS 7-2 "\.+"
+ FIELD 7-1 FACILITY
+ FIELD 7-2 LEVEL
+ FIELD 8 MSG
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE xntpd-reset {
+ APP xntpd
+ ACTION MSG /time reset \(step\) (.*) s/ {HOST, 1}
+ REPORT "xntpd resets" "{x} xntpd reset's on {1}" count
+ REPORT "xntpd total time reset " "total resets on {1} is: {x}s" sum
+ REPORT "xntpd max reset time" "max reset on {1} is: {x}s" max
+ REPORT "xntpd min reset time" "min reset on {1} is: {x}s" MIN
+ REPORT "xntpd average reset time" "avergae reset on {1} is: {x}s" AVG
+}
+
+#######################
diff --git a/testcases/15/test.log b/testcases/15/test.log
new file mode 100644
index 0000000..f149397
--- /dev/null
+++ b/testcases/15/test.log
@@ -0,0 +1,6 @@
+May 18 00:21:20 hostA xntpd 1d [daemon.notice] xntpd[260]: [ID 774427 daemon.notice] time reset (step) 0.402684 s
+May 18 21:10:18 hostA xntpd 1d [daemon.notice] xntpd[260]: [ID 774427 daemon.notice] time reset (step) 0.400225 s
+May 18 21:34:49 hostA xntpd 1d [daemon.notice] xntpd[260]: [ID 774427 daemon.notice] time reset (step) 0.425891 s
+May 18 22:07:22 hostA xntpd 1d [daemon.notice] xntpd[260]: [ID 774427 daemon.notice] time reset (step) -0.288730 s
+May 18 23:22:51 hostA xntpd 1d [daemon.notice] xntpd[260]: [ID 774427 daemon.notice] time reset (step) 0.530498 s
+May 18 23:42:37 hostA xntpd 1d [daemon.notice] xntpd[260]: [ID 774427 daemon.notice] time reset (step) 0.270703 s
|
mikeknox/LogParse | 19c48b0535a27310c872fb7fa402bf9b8fbd3568 | Fixed test case 13 - Allows multi word report regex's | diff --git a/logparse.pl b/logparse.pl
index b28a98a..5d85fc9 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1179 +1,1184 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Long;
use Data::Dumper qw(Dumper);
# Globals
#
my $STARTTIME = time();
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my @CONFIGFILES;# = ("logparse.conf");
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
my $MATCH; # Only lines matching this regex will be parsed
my $COLOR = 0;
my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
"l|log=s" => \@LOGFILES,
"d|debug=i" => \$DEBUG,
"m|match=s" => \$MATCH,
"color" => \$COLOR
);
unless ($result) {
warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>] [--color]\nInvalid config options passed");
}
if ($COLOR) {
use Term::ANSIColor qw(:constants);
}
@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
@LOGFILES = split(/,/,join(',',@LOGFILES));
if ($MATCH) {
$MATCH =~ s/\^\"//;
$MATCH =~ s/\"$//;
logmsg (2, 3, "Skipping lines which match $MATCH");
}
loadcfg (\%cfghash, \@CONFIGFILES);
logmsg(7, 3, "cfghash:", \%cfghash);
processlogfile(\%cfghash, \%reshash, \@LOGFILES);
logmsg (9, 0, "reshash ..\n", %reshash);
report(\%cfghash, \%reshash);
logmsg (9, 0, "reshash ..\n", %reshash);
logmsg (9, 0, "cfghash ..\n", %cfghash);
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text does not contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ", \@tmp);
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
logmsg (6, 4, "line results now ...", $linehashref);
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Processing logfiles: ", $logfileref);
foreach my $logfile (@$logfileref) {
logmsg(1, 0, "processing $logfile using format $format...");
open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
$line{line} =~ s/\s+?$//;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
#logmsg(5, 1, "skipping as line doesn't match the match regex") and
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
logmsg(9, 1, "Checking line: $line{line}");
#logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
if (not $MATCH or $line{line} =~ /$MATCH/) {
my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
if (keys %rules >= 0) {
logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
$execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
logmsg (9, 3, "#rules in list .., ".keys(%rules) );
logmsg (9, 3, "\%rules ..", \%rules);
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
} else {
logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
}
logmsg(9 ,1, "Results hash ...", \%$reshashref );
logmsg (5, 1, "finished processing line");
}
close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
- @A = $line =~ /(\/.+\/|\{.+?\}|".+?"|\S+)/g;
-# Bug
-# Chops field at /, this is normally correct, except when a string value has a / such as a file path
-# Ignore any escaping of \, i.e \/
-
+ @A = $line =~ /(\/.+\/|\{.+?\}|".+?"|\d+=".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
+# $$actionref[$actionindex]{regex} =~ s/\//\/\//g;
+
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
+ $$reportref[$reportindex]{regex} =~ s/^"//;
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line\n";
}
}
if ($COLOR) {
print RED "\n\nSummaries:\n", RESET;
} else {
print "\n\nSummaries:\n";
}
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
logmsg (4, 1, "Processing report# $rptid for rule: $rule ...");
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (5, 2, "\%ruleresults rule ($rule) report ID ($rptid) ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
if ($COLOR) {
print BLUE "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n", RESET;
} else {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
}
} else {
logmsg (4, 2, "Report has no title for rule: $rule\[$rptid\]");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
if ($COLOR) {
print GREEN rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key), RESET;
} else {
print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
}
} else {
if ($COLOR) {
print GREEN "\t$$reshashref{$rule}{$key}: $key\n", RESET;
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
logmsg (9, 5, "cfghashref ...", $cfghashref);
logmsg (9, 5, "reshashref ...", $reshashref);
for my $actionid (keys( %$reshashref ) ) {
logmsg (5, 5, "Processing actionid: $actionid ...");
for my $key (keys %{ $$reshashref{$actionid} } ) {
logmsg (5, 6, "Processing key: $key for actionid: $actionid");
(my @values) = split (/:/, $key);
logmsg (9, 7, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
logmsg (5, 7, "Processing report ID: $rptid with key: $key for actionid: $actionid");
if (exists($$cfghashref{reports}[$rptid]{field})) {
logmsg (9, 8, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 7, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
# Compare max fieldid to number of entries in $key, skip if maxid > $key
my $targetmaxfield = array_max(\@targetfieldids);
if ($targetmaxfield > ($#values + 1) ) {
#warning ("w", "There is a field id in the report line that is greater than the number of items in this line's data set, skipping.");
logmsg (2, 5, "There is a field id ($targetmaxfield) in the target key greater than the number of fields ($#values) in the key, skipping");
next;
}
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 8, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} elsif ($fieldid == $$cfghashref{reports}[$rptid]{field} ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid is used report matching, so adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 9, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
logmsg (9, 8, "targetkeymatch is now: $targetkeymatch");
}
$targetkeymatch =~ s/^://;
+ $targetkeymatch =~ s/\[/\\\[/g;
+ $targetkeymatch =~ s/\]/\\\]/g;
$targetkeymatch =~ s/\(/\\\(/g;
$targetkeymatch =~ s/\)/\\\)/g;
logmsg (9, 7, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$targetkeymatch =~ s/\\\(/\(/g;
$targetkeymatch =~ s/\\\)/\)/g;
+ $targetkeymatch =~ s/\\\[/\[/g;
+ $targetkeymatch =~ s/\\\]/\]/g;
logmsg (9, 8, "$key does matched $targetkeymatch, so I'm doing the necssary calcs ...");
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Incremented count for report\[$rptid\]\[$targetkeymatch\] by $$reshashref{$actionid}{$key}{count} so it's now $$reshashref{$actionid}{$key}{count}");
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
logmsg (9, 9, "Added $$reshashref{$actionid}{$key}{total} to total for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{count}");
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Avg for report\[$rptid\]\[$targetkeymatch\] is now $results{$rptid}{$targetkeymatch}{avg}");
} else {
logmsg (9, 8, "$key does not match $targetkeymatch<eol>");
logmsg (9, 8, " key $key<eol>");
logmsg (9, 8, "targetkey $targetkeymatch<eol>");
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
logmsg (9, 5, "Returning ... results", \%results);
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ", $cfghashref);
logmsg (7, 3, "reshash ... ", $reshashref);
my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "Settting \$fields[$field] ($fields[$field]) = \$fields[$i] ($fields[$i])");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
$line.="\n";
#if (exists($$cfghashref{field})) {
#logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
#if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
#logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
#$line = "";
#}
#}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
logmsg (9, 5, "Matchlist ... $matchlist");
logmsg (9, 5, "Matchlist has morphed in \@matrix with elements ... ", \@matrix);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
logmsg (9, 6, "\$matchlist didn't have a \",\", so we shoved it onto \@matrix. Which is now ... ", \@matrix);
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
logmsg (9, 7, "\$i: $i");
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
logmsg (9, 8, "element $i ($matrix[$i]) was an integer so we pushed it onto the matrix");
} else {
logmsg (9, 8, "element $i ($matrix[$i]) wasn't an integer so we ignored it");
}
}
if ($numericonly) {
logmsg (9, 5, "Returning numeric only results ... ", \@tmpmatrix);
return @tmpmatrix;
} else {
logmsg (9, 5, "Returning full results ... ", \@matrix);
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid using matches $$cfghashref{matches}");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0; # 0 - nomatch 1 - match
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
} else {
logmsg(8, 6, "line didn't match negative regex");
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
} else {
- logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
+ logmsg(8, 5, "Using regex /$$cfghashref{regex}/ on field content: $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
} else {
logmsg(8, 6, "line didn't match regex");
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
logmsg (8, 4, "Regex for action has been applied, processing results now ...");
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count/i) {
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/sum/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
- }
+ } else {
+ logmsg(5, 5, "retval ($retval) was not set so we haven't processed the results");
+ }
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..", \@matrix);
logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
logmsg (9, 4, "cfghashref:", $cfghashref);
for my $rule (keys %{ $cfghashref } ) {
logmsg (9, 4, "Checking to see if $rule applies ...");
if (matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref)) {
$rules{$rule} = $rule ;
logmsg (9, 5, "it matches");
} else {
logmsg (9, 5, "it doesn't match");
}
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1; # 1 = match, 0 = fail
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
logmsg (9, 5, "cfghashref:", $cfghashref);
if (exists ( $$cfghashref{fields} ) ) {
logmsg (9, 5, "cfghashref{fields}:", \%{ $$cfghashref{fields} });
}
logmsg (9, 5, "linehashref:", $linehashref);
foreach my $field (keys (%{ $cfghashref } ) ) {
logmsg(9, 6, "checking field: $field with value: $$cfghashref{$field}");
logmsg (9, 7, "Does field ($field) with value: $$linehashref{ $field } match the following regex ...");
if ($$cfghashref{$field} =~ /^!/) {
my $exp = $$cfghashref{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
logmsg (9, 8, "neg regexp compar /$$linehashref{ $field }/ !~ /$exp/, ret=$ret");
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{$field}/);
logmsg (9, 8, "regexp compar /$$linehashref{$field}/ =~ /$$cfghashref{$field}/, ret=$ret");
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
my $dumpvar = shift;
my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
# TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
if ($COLOR) {
print STDERR GREEN whowasi."(): d=${time}s:", RESET;
} else {
print STDERR whowasi."(): d=${time}s:";
}
print STDERR " $msg";
if ($dumpvar) {
if ($COLOR) {
print STDERR BLUE Dumper($dumpvar), RESET;
} else {
print STDERR Dumper($dumpvar);
}
}
print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
if ($COLOR >= 1) {
print RED, "WARNING: $msg\n", RESET;
} else {
print "WARNING: $msg\n";
}
} elsif (/e|error/i) {
if ($COLOR >= 1) {
print RED, "ERROR: $msg\n", RESET;
} else {
print "ERROR: $msg\n";
}
} elsif (/c|critical/i) {
if ($COLOR >= 1) {
print RED, "CRITICAL error, aborted ... $msg\n", RESET;
} else {
print "CRITICAL error, aborted ... $msg\n";
}
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
sub array_max {
my $arrayref = shift; # ref to array
my $highestvalue = $$arrayref[0];
for my $i (0 .. @$arrayref ) {
$highestvalue = $$arrayref[$i] if $$arrayref[$i] > $highestvalue;
}
return $highestvalue;
}
diff --git a/testcases/13/expected.output b/testcases/13/expected.output
index ee6c522..59fbb24 100644
--- a/testcases/13/expected.output
+++ b/testcases/13/expected.output
@@ -1,15 +1,11 @@
No match for lines:
May 13 09:42:13 hostA syslog-ng[10704]: Termination requested via signal, terminating;
Summaries:
Syslog-ng started up:
- Syslog-ng has been started 1 times on HostA
- Syslog-ng has been started 1 times on HostB
-
-Syslog-ng versions:
- 1 of '2.0.9'
- 1 of '2.0.9
+ Syslog-ng has been started 1 times on hostA
+ Syslog-ng has been started 1 times on hostB
diff --git a/testcases/13/logparse.conf b/testcases/13/logparse.conf
index af3537f..a606bdc 100644
--- a/testcases/13/logparse.conf
+++ b/testcases/13/logparse.conf
@@ -1,47 +1,45 @@
#########
FORMAT syslog {
# FIELDS <field count> <delimiter>
# FIELDS <field count> <delimiter> [<parent field>]
# FIELD <field id #> <label>
# FIELD <parent field id#>-<child field id#> <label>
FIELDS 6 "\s+"
FIELD 1 MONTH
FIELD 2 DAY
FIELD 3 TIME
FIELD 4 HOST
FIELD 5 FULLAPP
FIELDS 5-2 /\[/
FIELD 5-1 APP default
FIELD 5-2 APPPID
FIELD 6 FULLMSG
FIELDS 6-2 /\]\s+/
FIELD 6-1 FACILITY
FIELD 6-2 MSG default
LASTLINEINDEX HOST
# LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
# default format to be used for log file analysis
DEFAULT
}
RULE {
MSG /^message repeated (.*) times/ OR /^message repeated$/
ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
# Apply {1} as {x} in the previously applied rule for HOST
ACTION MSG /^message repeated$/ count append LASTLINE
}
RULE syslog-ng {
APP syslog-ng
ACTION MSG /^Log statistics;/ IGNORE
- ACTION MSG /syslog-ng (.*); version=\'(.*)/ {HOST, 2, 3}
- #ACTION MSG /syslog-ng (.*); version=\'(.*)/ {HOST, 2, 3}
+ ACTION MSG /syslog-ng (.*?); version=\'(.*)/ {HOST, 1, 2}
REPORT "Syslog-ng started up:" "Syslog-ng has been started {x} times on {1}" 2="starting up"
- REPORT "Syslog-ng versions:" "{x} of {3}"
}
#######################
|
mikeknox/LogParse | 8036098d5eea612ee586189a6460da01c6f37433 | Added logging and tidying whitespace | diff --git a/logparse.pl b/logparse.pl
index a08eb05..b28a98a 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1173 +1,1179 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Long;
use Data::Dumper qw(Dumper);
# Globals
#
my $STARTTIME = time();
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my @CONFIGFILES;# = ("logparse.conf");
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
my $MATCH; # Only lines matching this regex will be parsed
my $COLOR = 0;
my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
"l|log=s" => \@LOGFILES,
"d|debug=i" => \$DEBUG,
"m|match=s" => \$MATCH,
"color" => \$COLOR
);
unless ($result) {
warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>] [--color]\nInvalid config options passed");
}
if ($COLOR) {
use Term::ANSIColor qw(:constants);
}
@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
@LOGFILES = split(/,/,join(',',@LOGFILES));
if ($MATCH) {
$MATCH =~ s/\^\"//;
$MATCH =~ s/\"$//;
logmsg (2, 3, "Skipping lines which match $MATCH");
}
loadcfg (\%cfghash, \@CONFIGFILES);
logmsg(7, 3, "cfghash:", \%cfghash);
processlogfile(\%cfghash, \%reshash, \@LOGFILES);
logmsg (9, 0, "reshash ..\n", %reshash);
report(\%cfghash, \%reshash);
logmsg (9, 0, "reshash ..\n", %reshash);
logmsg (9, 0, "cfghash ..\n", %cfghash);
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text does not contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ", \@tmp);
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
- logmsg (9, 4, "line results now ...", $linehashref);
+ logmsg (6, 4, "line results now ...", $linehashref);
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Processing logfiles: ", $logfileref);
foreach my $logfile (@$logfileref) {
logmsg(1, 0, "processing $logfile using format $format...");
open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
$line{line} =~ s/\s+?$//;
- logmsg(5, 1, "Processing next line");
- logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
- logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
+ logmsg(5, 1, "Processing next line");
+ logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
+ logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
#logmsg(5, 1, "skipping as line doesn't match the match regex") and
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
logmsg(9, 1, "Checking line: $line{line}");
#logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
if (not $MATCH or $line{line} =~ /$MATCH/) {
my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
if (keys %rules >= 0) {
logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
$execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
logmsg (9, 3, "#rules in list .., ".keys(%rules) );
logmsg (9, 3, "\%rules ..", \%rules);
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
- if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
- delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
- }
- $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
+ if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
+ delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
+ }
+ $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
- if ( keys(%rules) == 0) {
- # Add new unmatched linescode
- }
- } else {
- logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
+ if ( keys(%rules) == 0) {
+ # Add new unmatched linescode
}
- logmsg(9 ,1, "Results hash ...", \%$reshashref );
+ } else {
+ logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
+ }
+ logmsg(9 ,1, "Results hash ...", \%$reshashref );
logmsg (5, 1, "finished processing line");
}
close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+\/|\{.+?\}|".+?"|\S+)/g;
# Bug
# Chops field at /, this is normally correct, except when a string value has a / such as a file path
# Ignore any escaping of \, i.e \/
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line\n";
}
}
if ($COLOR) {
print RED "\n\nSummaries:\n", RESET;
} else {
print "\n\nSummaries:\n";
}
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
logmsg (4, 1, "Processing report# $rptid for rule: $rule ...");
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (5, 2, "\%ruleresults rule ($rule) report ID ($rptid) ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
if ($COLOR) {
print BLUE "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n", RESET;
} else {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
}
} else {
logmsg (4, 2, "Report has no title for rule: $rule\[$rptid\]");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
if ($COLOR) {
print GREEN rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key), RESET;
} else {
print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
}
} else {
if ($COLOR) {
print GREEN "\t$$reshashref{$rule}{$key}: $key\n", RESET;
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
logmsg (9, 5, "cfghashref ...", $cfghashref);
logmsg (9, 5, "reshashref ...", $reshashref);
for my $actionid (keys( %$reshashref ) ) {
- logmsg (5, 5, "Processing actionid: $actionid ...");
+ logmsg (5, 5, "Processing actionid: $actionid ...");
for my $key (keys %{ $$reshashref{$actionid} } ) {
logmsg (5, 6, "Processing key: $key for actionid: $actionid");
(my @values) = split (/:/, $key);
- logmsg (9, 7, "values from key($key) ... @values");
+ logmsg (9, 7, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
logmsg (5, 7, "Processing report ID: $rptid with key: $key for actionid: $actionid");
if (exists($$cfghashref{reports}[$rptid]{field})) {
logmsg (9, 8, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 7, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
# Compare max fieldid to number of entries in $key, skip if maxid > $key
my $targetmaxfield = array_max(\@targetfieldids);
if ($targetmaxfield > ($#values + 1) ) {
+ #warning ("w", "There is a field id in the report line that is greater than the number of items in this line's data set, skipping.");
logmsg (2, 5, "There is a field id ($targetmaxfield) in the target key greater than the number of fields ($#values) in the key, skipping");
next;
}
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 8, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} elsif ($fieldid == $$cfghashref{reports}[$rptid]{field} ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid is used report matching, so adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 9, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
logmsg (9, 8, "targetkeymatch is now: $targetkeymatch");
}
$targetkeymatch =~ s/^://;
$targetkeymatch =~ s/\(/\\\(/g;
$targetkeymatch =~ s/\)/\\\)/g;
logmsg (9, 7, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$targetkeymatch =~ s/\\\(/\(/g;
$targetkeymatch =~ s/\\\)/\)/g;
logmsg (9, 8, "$key does matched $targetkeymatch, so I'm doing the necssary calcs ...");
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Incremented count for report\[$rptid\]\[$targetkeymatch\] by $$reshashref{$actionid}{$key}{count} so it's now $$reshashref{$actionid}{$key}{count}");
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
logmsg (9, 9, "Added $$reshashref{$actionid}{$key}{total} to total for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{count}");
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Avg for report\[$rptid\]\[$targetkeymatch\] is now $results{$rptid}{$targetkeymatch}{avg}");
} else {
logmsg (9, 8, "$key does not match $targetkeymatch<eol>");
logmsg (9, 8, " key $key<eol>");
logmsg (9, 8, "targetkey $targetkeymatch<eol>");
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
logmsg (9, 5, "Returning ... results", \%results);
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ", $cfghashref);
logmsg (7, 3, "reshash ... ", $reshashref);
my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "Settting \$fields[$field] ($fields[$field]) = \$fields[$i] ($fields[$i])");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
$line.="\n";
#if (exists($$cfghashref{field})) {
#logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
#if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
#logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
#$line = "";
#}
#}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
logmsg (9, 5, "Matchlist ... $matchlist");
logmsg (9, 5, "Matchlist has morphed in \@matrix with elements ... ", \@matrix);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
logmsg (9, 6, "\$matchlist didn't have a \",\", so we shoved it onto \@matrix. Which is now ... ", \@matrix);
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
logmsg (9, 7, "\$i: $i");
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
logmsg (9, 8, "element $i ($matrix[$i]) was an integer so we pushed it onto the matrix");
} else {
logmsg (9, 8, "element $i ($matrix[$i]) wasn't an integer so we ignored it");
}
}
if ($numericonly) {
logmsg (9, 5, "Returning numeric only results ... ", \@tmpmatrix);
return @tmpmatrix;
} else {
logmsg (9, 5, "Returning full results ... ", \@matrix);
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid using matches $$cfghashref{matches}");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ", $cfghashref);
- my $retval = 0;
+ my $retval = 0; # 0 - nomatch 1 - match
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
- }
+ } else {
+ logmsg(8, 6, "line didn't match negative regex");
+ }
+ logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
} else {
logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
- }
+ } else {
+ logmsg(8, 6, "line didn't match regex");
+ }
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
+ logmsg (8, 4, "Regex for action has been applied, processing results now ...");
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
- for ($$cfghashref{cmd}) {
- logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
- if (/count/i) {
- $$reshashref{$rule}{$actionid}{$matchid}{count}++;
- } elsif (/sum/i) {
- $$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
- $$reshashref{$rule}{$actionid}{$matchid}{count}++;
- } elsif (/append/i) {
-
- } elsif (/ignore/i) {
- } else {
- warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
- logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
- }
- }
+ for ($$cfghashref{cmd}) {
+ logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
+ if (/count/i) {
+ $$reshashref{$rule}{$actionid}{$matchid}{count}++;
+ } elsif (/sum/i) {
+ $$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
+ $$reshashref{$rule}{$actionid}{$matchid}{count}++;
+ } elsif (/append/i) {
+
+ } elsif (/ignore/i) {
+ } else {
+ warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
+ logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
+ }
+ }
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
- $retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
- } else {
- logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
- }
-
+ $retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
+ } else {
+ logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
+ }
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..", \@matrix);
logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
logmsg (9, 4, "cfghashref:", $cfghashref);
for my $rule (keys %{ $cfghashref } ) {
logmsg (9, 4, "Checking to see if $rule applies ...");
if (matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref)) {
$rules{$rule} = $rule ;
logmsg (9, 5, "it matches");
} else {
logmsg (9, 5, "it doesn't match");
}
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1; # 1 = match, 0 = fail
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
logmsg (9, 5, "cfghashref:", $cfghashref);
if (exists ( $$cfghashref{fields} ) ) {
logmsg (9, 5, "cfghashref{fields}:", \%{ $$cfghashref{fields} });
}
logmsg (9, 5, "linehashref:", $linehashref);
foreach my $field (keys (%{ $cfghashref } ) ) {
logmsg(9, 6, "checking field: $field with value: $$cfghashref{$field}");
logmsg (9, 7, "Does field ($field) with value: $$linehashref{ $field } match the following regex ...");
if ($$cfghashref{$field} =~ /^!/) {
my $exp = $$cfghashref{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
logmsg (9, 8, "neg regexp compar /$$linehashref{ $field }/ !~ /$exp/, ret=$ret");
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{$field}/);
logmsg (9, 8, "regexp compar /$$linehashref{$field}/ =~ /$$cfghashref{$field}/, ret=$ret");
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
my $dumpvar = shift;
my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
# TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
if ($COLOR) {
print STDERR GREEN whowasi."(): d=${time}s:", RESET;
} else {
print STDERR whowasi."(): d=${time}s:";
}
print STDERR " $msg";
if ($dumpvar) {
if ($COLOR) {
print STDERR BLUE Dumper($dumpvar), RESET;
} else {
print STDERR Dumper($dumpvar);
}
}
print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
if ($COLOR >= 1) {
print RED, "WARNING: $msg\n", RESET;
} else {
print "WARNING: $msg\n";
}
} elsif (/e|error/i) {
if ($COLOR >= 1) {
print RED, "ERROR: $msg\n", RESET;
} else {
print "ERROR: $msg\n";
}
} elsif (/c|critical/i) {
if ($COLOR >= 1) {
print RED, "CRITICAL error, aborted ... $msg\n", RESET;
} else {
print "CRITICAL error, aborted ... $msg\n";
}
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
sub array_max {
my $arrayref = shift; # ref to array
my $highestvalue = $$arrayref[0];
for my $i (0 .. @$arrayref ) {
$highestvalue = $$arrayref[$i] if $$arrayref[$i] > $highestvalue;
}
return $highestvalue;
}
|
mikeknox/LogParse | 394c17978d9fc35514a72d8711dcb56552d43771 | Made getpaarameter greedy for forward slashes, this allows forward slashes to be spcified (when escaped) in config lines | diff --git a/logparse.pl b/logparse.pl
index 1ea27bc..a08eb05 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1173 +1,1173 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Long;
use Data::Dumper qw(Dumper);
# Globals
#
my $STARTTIME = time();
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my @CONFIGFILES;# = ("logparse.conf");
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
my $MATCH; # Only lines matching this regex will be parsed
my $COLOR = 0;
my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
"l|log=s" => \@LOGFILES,
"d|debug=i" => \$DEBUG,
"m|match=s" => \$MATCH,
"color" => \$COLOR
);
unless ($result) {
warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>] [--color]\nInvalid config options passed");
}
if ($COLOR) {
use Term::ANSIColor qw(:constants);
}
@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
@LOGFILES = split(/,/,join(',',@LOGFILES));
if ($MATCH) {
$MATCH =~ s/\^\"//;
$MATCH =~ s/\"$//;
logmsg (2, 3, "Skipping lines which match $MATCH");
}
loadcfg (\%cfghash, \@CONFIGFILES);
logmsg(7, 3, "cfghash:", \%cfghash);
processlogfile(\%cfghash, \%reshash, \@LOGFILES);
logmsg (9, 0, "reshash ..\n", %reshash);
report(\%cfghash, \%reshash);
logmsg (9, 0, "reshash ..\n", %reshash);
logmsg (9, 0, "cfghash ..\n", %cfghash);
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text does not contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ", \@tmp);
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
logmsg (9, 4, "line results now ...", $linehashref);
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Processing logfiles: ", $logfileref);
foreach my $logfile (@$logfileref) {
logmsg(1, 0, "processing $logfile using format $format...");
open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
$line{line} =~ s/\s+?$//;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
#logmsg(5, 1, "skipping as line doesn't match the match regex") and
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
logmsg(9, 1, "Checking line: $line{line}");
#logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
if (not $MATCH or $line{line} =~ /$MATCH/) {
my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
if (keys %rules >= 0) {
- logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
+ logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
- # loop through matching rules and collect data as defined in the ACTIONS section of %config
+ # loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
- my %tmprules = %rules;
+ my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
- $execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
+ $execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
- logmsg (9, 3, "#rules in list .., ".keys(%rules) );
- logmsg (9, 3, "\%rules ..", \%rules);
+ logmsg (9, 3, "#rules in list .., ".keys(%rules) );
+ logmsg (9, 3, "\%rules ..", \%rules);
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
} else {
logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
}
logmsg(9 ,1, "Results hash ...", \%$reshashref );
logmsg (5, 1, "finished processing line");
}
close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
- @A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
+ @A = $line =~ /(\/.+\/|\{.+?\}|".+?"|\S+)/g;
# Bug
# Chops field at /, this is normally correct, except when a string value has a / such as a file path
# Ignore any escaping of \, i.e \/
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line\n";
}
}
if ($COLOR) {
print RED "\n\nSummaries:\n", RESET;
} else {
print "\n\nSummaries:\n";
}
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
logmsg (4, 1, "Processing report# $rptid for rule: $rule ...");
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (5, 2, "\%ruleresults rule ($rule) report ID ($rptid) ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
if ($COLOR) {
print BLUE "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n", RESET;
} else {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
}
} else {
logmsg (4, 2, "Report has no title for rule: $rule\[$rptid\]");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
if ($COLOR) {
print GREEN rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key), RESET;
} else {
print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
}
} else {
if ($COLOR) {
print GREEN "\t$$reshashref{$rule}{$key}: $key\n", RESET;
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
- logmsg (9, 5, "cfghashref ...", $cfghashref);
- logmsg (9, 5, "reshashref ...", $reshashref);
+ logmsg (9, 5, "cfghashref ...", $cfghashref);
+ logmsg (9, 5, "reshashref ...", $reshashref);
for my $actionid (keys( %$reshashref ) ) {
- logmsg (5, 5, "Processing actionid: $actionid ...");
+ logmsg (5, 5, "Processing actionid: $actionid ...");
for my $key (keys %{ $$reshashref{$actionid} } ) {
logmsg (5, 6, "Processing key: $key for actionid: $actionid");
(my @values) = split (/:/, $key);
- logmsg (9, 7, "values from key($key) ... @values");
+ logmsg (9, 7, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
logmsg (5, 7, "Processing report ID: $rptid with key: $key for actionid: $actionid");
if (exists($$cfghashref{reports}[$rptid]{field})) {
logmsg (9, 8, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 7, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
# Compare max fieldid to number of entries in $key, skip if maxid > $key
my $targetmaxfield = array_max(\@targetfieldids);
if ($targetmaxfield > ($#values + 1) ) {
logmsg (2, 5, "There is a field id ($targetmaxfield) in the target key greater than the number of fields ($#values) in the key, skipping");
next;
}
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 8, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} elsif ($fieldid == $$cfghashref{reports}[$rptid]{field} ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid is used report matching, so adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 9, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
logmsg (9, 8, "targetkeymatch is now: $targetkeymatch");
}
$targetkeymatch =~ s/^://;
$targetkeymatch =~ s/\(/\\\(/g;
$targetkeymatch =~ s/\)/\\\)/g;
logmsg (9, 7, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$targetkeymatch =~ s/\\\(/\(/g;
$targetkeymatch =~ s/\\\)/\)/g;
logmsg (9, 8, "$key does matched $targetkeymatch, so I'm doing the necssary calcs ...");
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Incremented count for report\[$rptid\]\[$targetkeymatch\] by $$reshashref{$actionid}{$key}{count} so it's now $$reshashref{$actionid}{$key}{count}");
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
logmsg (9, 9, "Added $$reshashref{$actionid}{$key}{total} to total for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{count}");
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Avg for report\[$rptid\]\[$targetkeymatch\] is now $results{$rptid}{$targetkeymatch}{avg}");
} else {
logmsg (9, 8, "$key does not match $targetkeymatch<eol>");
logmsg (9, 8, " key $key<eol>");
logmsg (9, 8, "targetkey $targetkeymatch<eol>");
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
logmsg (9, 5, "Returning ... results", \%results);
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ", $cfghashref);
logmsg (7, 3, "reshash ... ", $reshashref);
my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "Settting \$fields[$field] ($fields[$field]) = \$fields[$i] ($fields[$i])");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
$line.="\n";
#if (exists($$cfghashref{field})) {
#logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
#if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
#logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
#$line = "";
#}
#}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
logmsg (9, 5, "Matchlist ... $matchlist");
logmsg (9, 5, "Matchlist has morphed in \@matrix with elements ... ", \@matrix);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
logmsg (9, 6, "\$matchlist didn't have a \",\", so we shoved it onto \@matrix. Which is now ... ", \@matrix);
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
logmsg (9, 7, "\$i: $i");
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
logmsg (9, 8, "element $i ($matrix[$i]) was an integer so we pushed it onto the matrix");
} else {
logmsg (9, 8, "element $i ($matrix[$i]) wasn't an integer so we ignored it");
}
}
if ($numericonly) {
logmsg (9, 5, "Returning numeric only results ... ", \@tmpmatrix);
return @tmpmatrix;
} else {
logmsg (9, 5, "Returning full results ... ", \@matrix);
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid using matches $$cfghashref{matches}");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0;
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
} else {
logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count/i) {
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/sum/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..", \@matrix);
logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
logmsg (9, 4, "cfghashref:", $cfghashref);
for my $rule (keys %{ $cfghashref } ) {
logmsg (9, 4, "Checking to see if $rule applies ...");
if (matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref)) {
$rules{$rule} = $rule ;
logmsg (9, 5, "it matches");
} else {
logmsg (9, 5, "it doesn't match");
}
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1; # 1 = match, 0 = fail
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
logmsg (9, 5, "cfghashref:", $cfghashref);
if (exists ( $$cfghashref{fields} ) ) {
logmsg (9, 5, "cfghashref{fields}:", \%{ $$cfghashref{fields} });
}
logmsg (9, 5, "linehashref:", $linehashref);
foreach my $field (keys (%{ $cfghashref } ) ) {
logmsg(9, 6, "checking field: $field with value: $$cfghashref{$field}");
logmsg (9, 7, "Does field ($field) with value: $$linehashref{ $field } match the following regex ...");
if ($$cfghashref{$field} =~ /^!/) {
my $exp = $$cfghashref{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
logmsg (9, 8, "neg regexp compar /$$linehashref{ $field }/ !~ /$exp/, ret=$ret");
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{$field}/);
logmsg (9, 8, "regexp compar /$$linehashref{$field}/ =~ /$$cfghashref{$field}/, ret=$ret");
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
my $dumpvar = shift;
my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
# TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
if ($COLOR) {
print STDERR GREEN whowasi."(): d=${time}s:", RESET;
} else {
print STDERR whowasi."(): d=${time}s:";
}
print STDERR " $msg";
if ($dumpvar) {
if ($COLOR) {
print STDERR BLUE Dumper($dumpvar), RESET;
} else {
print STDERR Dumper($dumpvar);
}
}
print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
if ($COLOR >= 1) {
print RED, "WARNING: $msg\n", RESET;
} else {
print "WARNING: $msg\n";
}
} elsif (/e|error/i) {
if ($COLOR >= 1) {
print RED, "ERROR: $msg\n", RESET;
} else {
print "ERROR: $msg\n";
}
} elsif (/c|critical/i) {
if ($COLOR >= 1) {
print RED, "CRITICAL error, aborted ... $msg\n", RESET;
} else {
print "CRITICAL error, aborted ... $msg\n";
}
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
sub array_max {
my $arrayref = shift; # ref to array
my $highestvalue = $$arrayref[0];
for my $i (0 .. @$arrayref ) {
$highestvalue = $$arrayref[$i] if $$arrayref[$i] > $highestvalue;
}
return $highestvalue;
}
|
mikeknox/LogParse | d0192fa1c574964fa998ee729d6b8e5d89a0d4cf | Strip trailing whitespace from ssyslog lines Extra testcases | diff --git a/logparse.pl b/logparse.pl
index 0fdda19..1ea27bc 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1172 +1,1173 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Long;
use Data::Dumper qw(Dumper);
# Globals
#
my $STARTTIME = time();
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my @CONFIGFILES;# = ("logparse.conf");
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
my $MATCH; # Only lines matching this regex will be parsed
my $COLOR = 0;
my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
"l|log=s" => \@LOGFILES,
"d|debug=i" => \$DEBUG,
"m|match=s" => \$MATCH,
"color" => \$COLOR
);
unless ($result) {
warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>] [--color]\nInvalid config options passed");
}
if ($COLOR) {
use Term::ANSIColor qw(:constants);
}
@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
@LOGFILES = split(/,/,join(',',@LOGFILES));
if ($MATCH) {
$MATCH =~ s/\^\"//;
$MATCH =~ s/\"$//;
logmsg (2, 3, "Skipping lines which match $MATCH");
}
loadcfg (\%cfghash, \@CONFIGFILES);
logmsg(7, 3, "cfghash:", \%cfghash);
processlogfile(\%cfghash, \%reshash, \@LOGFILES);
logmsg (9, 0, "reshash ..\n", %reshash);
report(\%cfghash, \%reshash);
logmsg (9, 0, "reshash ..\n", %reshash);
logmsg (9, 0, "cfghash ..\n", %cfghash);
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text does not contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ", \@tmp);
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
logmsg (9, 4, "line results now ...", $linehashref);
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Processing logfiles: ", $logfileref);
foreach my $logfile (@$logfileref) {
logmsg(1, 0, "processing $logfile using format $format...");
open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
+ $line{line} =~ s/\s+?$//;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
#logmsg(5, 1, "skipping as line doesn't match the match regex") and
- parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
+ parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
logmsg(9, 1, "Checking line: $line{line}");
- logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
+ #logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
- if ($line{line} =~ /$MATCH/) {
+ if (not $MATCH or $line{line} =~ /$MATCH/) {
my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
if (keys %rules >= 0) {
logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
$execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
logmsg (9, 3, "#rules in list .., ".keys(%rules) );
logmsg (9, 3, "\%rules ..", \%rules);
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
} else {
logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
}
logmsg(9 ,1, "Results hash ...", \%$reshashref );
logmsg (5, 1, "finished processing line");
}
close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
# Bug
# Chops field at /, this is normally correct, except when a string value has a / such as a file path
# Ignore any escaping of \, i.e \/
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
- print "\t$line";
+ print "\t$line\n";
}
}
if ($COLOR) {
print RED "\n\nSummaries:\n", RESET;
} else {
print "\n\nSummaries:\n";
}
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
logmsg (4, 1, "Processing report# $rptid for rule: $rule ...");
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (5, 2, "\%ruleresults rule ($rule) report ID ($rptid) ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
if ($COLOR) {
print BLUE "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n", RESET;
} else {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
}
} else {
logmsg (4, 2, "Report has no title for rule: $rule\[$rptid\]");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
if ($COLOR) {
print GREEN rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key), RESET;
} else {
print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
}
} else {
if ($COLOR) {
print GREEN "\t$$reshashref{$rule}{$key}: $key\n", RESET;
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
logmsg (9, 5, "cfghashref ...", $cfghashref);
logmsg (9, 5, "reshashref ...", $reshashref);
for my $actionid (keys( %$reshashref ) ) {
logmsg (5, 5, "Processing actionid: $actionid ...");
for my $key (keys %{ $$reshashref{$actionid} } ) {
logmsg (5, 6, "Processing key: $key for actionid: $actionid");
(my @values) = split (/:/, $key);
logmsg (9, 7, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
logmsg (5, 7, "Processing report ID: $rptid with key: $key for actionid: $actionid");
if (exists($$cfghashref{reports}[$rptid]{field})) {
logmsg (9, 8, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 7, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
# Compare max fieldid to number of entries in $key, skip if maxid > $key
my $targetmaxfield = array_max(\@targetfieldids);
if ($targetmaxfield > ($#values + 1) ) {
logmsg (2, 5, "There is a field id ($targetmaxfield) in the target key greater than the number of fields ($#values) in the key, skipping");
next;
}
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 8, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} elsif ($fieldid == $$cfghashref{reports}[$rptid]{field} ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 9, "fieldid: $fieldid is used report matching, so adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 9, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
logmsg (9, 8, "targetkeymatch is now: $targetkeymatch");
}
$targetkeymatch =~ s/^://;
$targetkeymatch =~ s/\(/\\\(/g;
$targetkeymatch =~ s/\)/\\\)/g;
logmsg (9, 7, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$targetkeymatch =~ s/\\\(/\(/g;
$targetkeymatch =~ s/\\\)/\)/g;
logmsg (9, 8, "$key does matched $targetkeymatch, so I'm doing the necssary calcs ...");
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Incremented count for report\[$rptid\]\[$targetkeymatch\] by $$reshashref{$actionid}{$key}{count} so it's now $$reshashref{$actionid}{$key}{count}");
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
logmsg (9, 9, "Added $$reshashref{$actionid}{$key}{total} to total for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{count}");
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
logmsg (9, 9, "Avg for report\[$rptid\]\[$targetkeymatch\] is now $results{$rptid}{$targetkeymatch}{avg}");
} else {
logmsg (9, 8, "$key does not match $targetkeymatch<eol>");
logmsg (9, 8, " key $key<eol>");
logmsg (9, 8, "targetkey $targetkeymatch<eol>");
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
logmsg (9, 5, "Returning ... results", \%results);
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ", $cfghashref);
logmsg (7, 3, "reshash ... ", $reshashref);
my $line = "\t".$$cfghashref{line};
- logmsg (7, 3, "report line: $line");
+ logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "Settting \$fields[$field] ($fields[$field]) = \$fields[$i] ($fields[$i])");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
$line.="\n";
#if (exists($$cfghashref{field})) {
#logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
#if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
#logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
#$line = "";
#}
#}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
logmsg (9, 5, "Matchlist ... $matchlist");
logmsg (9, 5, "Matchlist has morphed in \@matrix with elements ... ", \@matrix);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
logmsg (9, 6, "\$matchlist didn't have a \",\", so we shoved it onto \@matrix. Which is now ... ", \@matrix);
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
logmsg (9, 7, "\$i: $i");
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
logmsg (9, 8, "element $i ($matrix[$i]) was an integer so we pushed it onto the matrix");
} else {
logmsg (9, 8, "element $i ($matrix[$i]) wasn't an integer so we ignored it");
}
}
if ($numericonly) {
logmsg (9, 5, "Returning numeric only results ... ", \@tmpmatrix);
return @tmpmatrix;
} else {
logmsg (9, 5, "Returning full results ... ", \@matrix);
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid using matches $$cfghashref{matches}");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0;
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
} else {
logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count/i) {
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/sum/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..", \@matrix);
logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
logmsg (9, 4, "cfghashref:", $cfghashref);
for my $rule (keys %{ $cfghashref } ) {
logmsg (9, 4, "Checking to see if $rule applies ...");
if (matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref)) {
$rules{$rule} = $rule ;
logmsg (9, 5, "it matches");
} else {
logmsg (9, 5, "it doesn't match");
}
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1; # 1 = match, 0 = fail
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
logmsg (9, 5, "cfghashref:", $cfghashref);
if (exists ( $$cfghashref{fields} ) ) {
logmsg (9, 5, "cfghashref{fields}:", \%{ $$cfghashref{fields} });
}
logmsg (9, 5, "linehashref:", $linehashref);
foreach my $field (keys (%{ $cfghashref } ) ) {
logmsg(9, 6, "checking field: $field with value: $$cfghashref{$field}");
logmsg (9, 7, "Does field ($field) with value: $$linehashref{ $field } match the following regex ...");
if ($$cfghashref{$field} =~ /^!/) {
my $exp = $$cfghashref{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
logmsg (9, 8, "neg regexp compar /$$linehashref{ $field }/ !~ /$exp/, ret=$ret");
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{$field}/);
logmsg (9, 8, "regexp compar /$$linehashref{$field}/ =~ /$$cfghashref{$field}/, ret=$ret");
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
my $dumpvar = shift;
my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
# TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
if ($COLOR) {
print STDERR GREEN whowasi."(): d=${time}s:", RESET;
} else {
print STDERR whowasi."(): d=${time}s:";
}
print STDERR " $msg";
if ($dumpvar) {
if ($COLOR) {
print STDERR BLUE Dumper($dumpvar), RESET;
} else {
print STDERR Dumper($dumpvar);
}
}
print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
if ($COLOR >= 1) {
print RED, "WARNING: $msg\n", RESET;
} else {
print "WARNING: $msg\n";
}
} elsif (/e|error/i) {
if ($COLOR >= 1) {
print RED, "ERROR: $msg\n", RESET;
} else {
print "ERROR: $msg\n";
}
} elsif (/c|critical/i) {
if ($COLOR >= 1) {
print RED, "CRITICAL error, aborted ... $msg\n", RESET;
} else {
print "CRITICAL error, aborted ... $msg\n";
}
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
sub array_max {
my $arrayref = shift; # ref to array
my $highestvalue = $$arrayref[0];
for my $i (0 .. @$arrayref ) {
$highestvalue = $$arrayref[$i] if $$arrayref[$i] > $highestvalue;
}
return $highestvalue;
}
diff --git a/testcases/12/Description b/testcases/12/Description
new file mode 100644
index 0000000..3597c40
--- /dev/null
+++ b/testcases/12/Description
@@ -0,0 +1 @@
+Validate using summarised/roll up data in reports
diff --git a/testcases/12/expected.output b/testcases/12/expected.output
new file mode 100644
index 0000000..328956b
--- /dev/null
+++ b/testcases/12/expected.output
@@ -0,0 +1,18 @@
+
+
+No match for lines:
+
+
+Summaries:
+SSH logins by method and source host:
+ 1 keyboard-interactive/pam logins to userb@hostA from 192.168.1.20
+ 1 publickey logins to userb@hostA from 192.168.1.10
+ 1 publickey logins to userb@hostA from 192.168.1.20
+
+SSH logins by source host:
+ 2 logins to userb@hostA from 192.168.1.20
+ 1 logins to userb@hostA from 192.168.1.10
+
+SSH logins to a host:
+ 3 logins to userb@hostA
+
diff --git a/testcases/12/logparse.conf b/testcases/12/logparse.conf
new file mode 100644
index 0000000..979c445
--- /dev/null
+++ b/testcases/12/logparse.conf
@@ -0,0 +1,48 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 FULLAPP
+ FIELDS 5-2 /\[/
+ FIELD 5-1 APP default
+ FIELD 5-2 APPPID
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /\]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+RULE sshd-pam-accepted {
+
+ APP sshd
+ MSG /^Accepted/
+ ACTION MSG /Accepted (.*) for (.*) from (.*) port \d+ ssh2/ {HOST, 1, 2, 3}
+
+ REPORT "SSH logins by method and source host:" "{x} {2} logins to {3}@{1} from {4}" count
+ REPORT "SSH logins by source host:" "{x} logins to {3}@{1} from {4}" count
+ REPORT "SSH logins to a host:" "{x} logins to {3}@{1}" count
+}
+
+
+#######################
diff --git a/testcases/12/test.log b/testcases/12/test.log
new file mode 100644
index 0000000..7714add
--- /dev/null
+++ b/testcases/12/test.log
@@ -0,0 +1,3 @@
+May 13 06:49:57 hostA sshd[17464]: Accepted publickey for userb from 192.168.1.10 port 63182 ssh2
+May 13 08:57:13 hostA sshd[18367]: Accepted keyboard-interactive/pam for userb from 192.168.1.20 port 6395 ssh2
+May 13 09:14:19 hostA sshd[18525]: Accepted publickey for userb from 192.168.1.20 port 6464 ssh2
diff --git a/testcases/13/Description b/testcases/13/Description
new file mode 100644
index 0000000..34596a4
--- /dev/null
+++ b/testcases/13/Description
@@ -0,0 +1 @@
+Additional summarisation tests
diff --git a/testcases/13/expected.output b/testcases/13/expected.output
new file mode 100644
index 0000000..ee6c522
--- /dev/null
+++ b/testcases/13/expected.output
@@ -0,0 +1,15 @@
+
+
+No match for lines:
+ May 13 09:42:13 hostA syslog-ng[10704]: Termination requested via signal, terminating;
+
+
+Summaries:
+Syslog-ng started up:
+ Syslog-ng has been started 1 times on HostA
+ Syslog-ng has been started 1 times on HostB
+
+Syslog-ng versions:
+ 1 of '2.0.9'
+ 1 of '2.0.9
+
diff --git a/testcases/13/logparse.conf b/testcases/13/logparse.conf
new file mode 100644
index 0000000..af3537f
--- /dev/null
+++ b/testcases/13/logparse.conf
@@ -0,0 +1,47 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 FULLAPP
+ FIELDS 5-2 /\[/
+ FIELD 5-1 APP default
+ FIELD 5-2 APPPID
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /\]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE syslog-ng {
+ APP syslog-ng
+ ACTION MSG /^Log statistics;/ IGNORE
+ ACTION MSG /syslog-ng (.*); version=\'(.*)/ {HOST, 2, 3}
+ #ACTION MSG /syslog-ng (.*); version=\'(.*)/ {HOST, 2, 3}
+
+ REPORT "Syslog-ng started up:" "Syslog-ng has been started {x} times on {1}" 2="starting up"
+ REPORT "Syslog-ng versions:" "{x} of {3}"
+}
+
+#######################
diff --git a/testcases/13/test.log b/testcases/13/test.log
new file mode 100644
index 0000000..8c5d543
--- /dev/null
+++ b/testcases/13/test.log
@@ -0,0 +1,5 @@
+May 13 09:36:12 hostA syslog-ng[10704]: Log statistics; dropped='pipe(/dev/xconsole)=685', dropped='pipe(/dev/tty10)=0', processed='center(queued)=10969', processed='center(received)=3755', processed='destination(newsnotice)=0', processed='destination(acpid)=1', processed='destination(firewall)=0', processed='destination(null)=1', processed='destination(mail)=2', processed='destination(mailinfo)=2', processed='destination(console)=2404', processed='destination(newserr)=0', processed='destination(newscrit)=0', processed='destination(messages)=3751', processed='destination(mailwarn)=0', processed='destination(localmessages)=0', processed='destination(netmgm)=0', processed='destination(mailerr)=0', processed='destination(xconsole)=2404', processed='destination(warn)=2404', processed='source(src)=3755'
+May 13 09:42:13 hostA syslog-ng[10704]: Termination requested via signal, terminating;
+May 13 09:42:13 hostA syslog-ng[10704]: syslog-ng shutting down; version='2.0.9'
+May 13 09:42:14 hostA syslog-ng[18923]: syslog-ng starting up; version='2.0.9'
+May 13 09:46:00 hostB syslog-ng[7200]: syslog-ng starting up; version='2.0.9
diff --git a/testcases/14/Description b/testcases/14/Description
new file mode 100644
index 0000000..28d1ea3
--- /dev/null
+++ b/testcases/14/Description
@@ -0,0 +1 @@
+Test summarisation when a field contains colon's
diff --git a/testcases/14/expected.output b/testcases/14/expected.output
new file mode 100644
index 0000000..06ffcbc
--- /dev/null
+++ b/testcases/14/expected.output
@@ -0,0 +1,9 @@
+
+
+No match for lines:
+
+
+Summaries:
+DHCP Reuqests
+ 1 requests for 192.168.8.20 (192.168.8.10) from 00:26:b9:1f:fc:76 (user-PC)
+
diff --git a/testcases/14/logparse.conf b/testcases/14/logparse.conf
new file mode 100644
index 0000000..8204673
--- /dev/null
+++ b/testcases/14/logparse.conf
@@ -0,0 +1,42 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 FULLAPP
+ FIELDS 5-2 /\[/
+ FIELD 5-1 APP default
+ FIELD 5-2 APPPID
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /\]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE dhcpd {
+ FULLAPP dhcpd
+ ACTION MSG /DHCPREQUEST for (.*?) from (.*) \((.*)\) via (.*)/ {HOST, 1, 2, 3, 4}
+ REPORT "DHCP Reuqests" "{x} requests for {2} from {3} ({4})" count
+}
+#######################
diff --git a/testcases/14/test.log b/testcases/14/test.log
new file mode 100644
index 0000000..cc45ec3
--- /dev/null
+++ b/testcases/14/test.log
@@ -0,0 +1 @@
+May 13 10:38:18 dhcphost dhcpd: DHCPREQUEST for 192.168.8.20 (192.168.8.10) from 00:26:b9:1f:fc:76 (user-PC) via eth0
|
mikeknox/LogParse | c303bc88832ccc0ea746a81a70cdd79b8f98935a | Fixed a couploe of bugs that caused lines containing brackets that were't IGNORE'd to be handled incorectly. Added some more debug information. The color option is also controllable on the debug output now as well. | diff --git a/logparse.conf b/logparse.conf
index 2896da8..a40b106 100644
--- a/logparse.conf
+++ b/logparse.conf
@@ -1,79 +1,85 @@
# Describe config file for log parse / summary engine
#
#
# FORMAT <name> {
# DELIMITER <xyz>
# FIELDS <x>
# FIELD<x> <name>
#}
FORMAT dummy {
DELIMITER \t
FIELDS 2
FIELD1 abc
FIELD2 def
}
# Need to redefine the language structure for the config file
# there are a lot of different commands, and the language needs to be formalised
# to make it easier to automate
# Current only support logical ops AND and NOT, need to add grouping and OR
# Also being able to use LASTLINE in rules would be neat, especially against HOSTS different to current
# Need to track which FIELD the lastline should be indexed against
# eg in consolidated logfiles, last line would be indexed on HOST
# also need to handle the scenario that last line is a continued line?
# Structure definition ...
#########
FORMAT syslog {
# FIELDS <field count> <delimiter>
# FIELDS <field count> <delimiter> [<parent field>]
# FIELD <field id #> <label>
# FIELD <parent field id#>-<child field id#> <label>
FIELDS 6 "\s+"
FIELD 1 MONTH
FIELD 2 DAY
FIELD 3 TIME
FIELD 4 HOST
FIELD 5 APP
FIELD 6 FULLMSG
FIELDS 6-2 /]\s+/
FIELD 6-1 FACILITY
FIELD 6-2 MSG default
LASTLINEINDEX HOST
# LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
# default format to be used for log file analysis
DEFAULT
# ACTION <field> </regex/> <{matches}> sum <{sum field}>
#ACTION MSG /^message repeated (.*) times/ {1} sum {1}
# Apply {1} as {x} in the previously applied rule for HOST
#ACTION MSG /^message repeated$/ count
}
RULE {
MSG /^message repeated (.*) times/ OR /^message repeated$/
ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
# Apply {1} as {x} in the previously applied rule for HOST
ACTION MSG /^message repeated$/ count append LASTLINE
}
+RULE {
+ #May 12 09:56:12 hhostA -- MARK --
+ APP /--/
+ ACTION MSG /^MARK --$/ IGNORE
+}
+
RULE sudo {
APP sudo
MSG /.* : .* ; PWD=/
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times" count
# by default {x} is total
}
#######################
#2
diff --git a/logparse.pl b/logparse.pl
index e439d99..0fdda19 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1123 +1,1172 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Long;
use Data::Dumper qw(Dumper);
# Globals
#
my $STARTTIME = time();
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my @CONFIGFILES;# = ("logparse.conf");
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
my $MATCH; # Only lines matching this regex will be parsed
my $COLOR = 0;
my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
"l|log=s" => \@LOGFILES,
"d|debug=i" => \$DEBUG,
"m|match=s" => \$MATCH,
"color" => \$COLOR
);
unless ($result) {
warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>] [--color]\nInvalid config options passed");
}
if ($COLOR) {
use Term::ANSIColor qw(:constants);
}
@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
@LOGFILES = split(/,/,join(',',@LOGFILES));
if ($MATCH) {
$MATCH =~ s/\^\"//;
$MATCH =~ s/\"$//;
logmsg (2, 3, "Skipping lines which match $MATCH");
}
loadcfg (\%cfghash, \@CONFIGFILES);
logmsg(7, 3, "cfghash:", \%cfghash);
processlogfile(\%cfghash, \%reshash, \@LOGFILES);
logmsg (9, 0, "reshash ..\n", %reshash);
report(\%cfghash, \%reshash);
logmsg (9, 0, "reshash ..\n", %reshash);
logmsg (9, 0, "cfghash ..\n", %cfghash);
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text does not contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ", \@tmp);
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
logmsg (9, 4, "line results now ...", $linehashref);
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Processing logfiles: ", $logfileref);
foreach my $logfile (@$logfileref) {
logmsg(1, 0, "processing $logfile using format $format...");
open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
#logmsg(5, 1, "skipping as line doesn't match the match regex") and
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
logmsg(9, 1, "Checking line: $line{line}");
logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
if ($line{line} =~ /$MATCH/) {
my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
if (keys %rules >= 0) {
logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
$execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
logmsg (9, 3, "#rules in list .., ".keys(%rules) );
logmsg (9, 3, "\%rules ..", \%rules);
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
} else {
logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
}
logmsg(9 ,1, "Results hash ...", \%$reshashref );
logmsg (5, 1, "finished processing line");
}
close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
+# Bug
+# Chops field at /, this is normally correct, except when a string value has a / such as a file path
+# Ignore any escaping of \, i.e \/
+
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
}
if ($COLOR) {
print RED "\n\nSummaries:\n", RESET;
} else {
print "\n\nSummaries:\n";
}
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
+ logmsg (4, 1, "Processing report# $rptid for rule: $rule ...");
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
- logmsg (4, 1, "Rule[rptid]: $rule\[$rptid\]");
- logmsg (5, 2, "\%ruleresults ... ", \%ruleresults);
+ logmsg (5, 2, "\%ruleresults rule ($rule) report ID ($rptid) ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
if ($COLOR) {
print BLUE "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n", RESET;
} else {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
}
} else {
- logmsg (4, 2, "No title");
+ logmsg (4, 2, "Report has no title for rule: $rule\[$rptid\]");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
if ($COLOR) {
print GREEN rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key), RESET;
} else {
print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
}
} else {
if ($COLOR) {
print GREEN "\t$$reshashref{$rule}{$key}: $key\n", RESET;
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
+ logmsg (9, 5, "cfghashref ...", $cfghashref);
+ logmsg (9, 5, "reshashref ...", $reshashref);
for my $actionid (keys( %$reshashref ) ) {
+ logmsg (5, 5, "Processing actionid: $actionid ...");
for my $key (keys %{ $$reshashref{$actionid} } ) {
+ logmsg (5, 6, "Processing key: $key for actionid: $actionid");
(my @values) = split (/:/, $key);
- logmsg (9, 5, "values from key($key) ... @values");
+ logmsg (9, 7, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
+ logmsg (5, 7, "Processing report ID: $rptid with key: $key for actionid: $actionid");
if (exists($$cfghashref{reports}[$rptid]{field})) {
- logmsg (9, 4, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
+ logmsg (9, 8, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
- logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
+ logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
- logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
+ logmsg(9, 9, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
- logmsg (9, 5, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
+ logmsg (9, 7, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
+
+ # Compare max fieldid to number of entries in $key, skip if maxid > $key
+ my $targetmaxfield = array_max(\@targetfieldids);
+ if ($targetmaxfield > ($#values + 1) ) {
+ logmsg (2, 5, "There is a field id ($targetmaxfield) in the target key greater than the number of fields ($#values) in the key, skipping");
+ next;
+ }
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
- logmsg (9, 6, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
+ logmsg (9, 8, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
- logmsg(9, 7, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
+ logmsg(9, 9, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
+ } elsif ($fieldid == $$cfghashref{reports}[$rptid]{field} ) {
+ $targetkeymatch .= ":$values[$resfieldid]";
+ logmsg(9, 9, "fieldid: $fieldid is used report matching, so adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
- logmsg(9, 7, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
+ logmsg(9, 9, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
+ logmsg (9, 8, "targetkeymatch is now: $targetkeymatch");
}
$targetkeymatch =~ s/^://;
-
- logmsg (9, 5, "targetkey is $targetkeymatch");
+
+ $targetkeymatch =~ s/\(/\\\(/g;
+ $targetkeymatch =~ s/\)/\\\)/g;
+
+ logmsg (9, 7, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
+ $targetkeymatch =~ s/\\\(/\(/g;
+ $targetkeymatch =~ s/\\\)/\)/g;
+ logmsg (9, 8, "$key does matched $targetkeymatch, so I'm doing the necssary calcs ...");
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
+ logmsg (9, 9, "Incremented count for report\[$rptid\]\[$targetkeymatch\] by $$reshashref{$actionid}{$key}{count} so it's now $$reshashref{$actionid}{$key}{count}");
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
+ logmsg (9, 9, "Added $$reshashref{$actionid}{$key}{total} to total for report\[$rptid\]\[$targetkeymatch\], so it's now ... $results{$rptid}{$targetkeymatch}{count}");
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
+ logmsg (9, 9, "Avg for report\[$rptid\]\[$targetkeymatch\] is now $results{$rptid}{$targetkeymatch}{avg}");
+ } else {
+ logmsg (9, 8, "$key does not match $targetkeymatch<eol>");
+ logmsg (9, 8, " key $key<eol>");
+ logmsg (9, 8, "targetkey $targetkeymatch<eol>");
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
+ logmsg (9, 5, "Returning ... results", \%results);
+
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ", $cfghashref);
logmsg (7, 3, "reshash ... ", $reshashref);
my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "Settting \$fields[$field] ($fields[$field]) = \$fields[$i] ($fields[$i])");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
$line.="\n";
#if (exists($$cfghashref{field})) {
#logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
#if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
#logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
#$line = "";
#}
#}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
logmsg (9, 5, "Matchlist ... $matchlist");
logmsg (9, 5, "Matchlist has morphed in \@matrix with elements ... ", \@matrix);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
logmsg (9, 6, "\$matchlist didn't have a \",\", so we shoved it onto \@matrix. Which is now ... ", \@matrix);
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
logmsg (9, 7, "\$i: $i");
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
logmsg (9, 8, "element $i ($matrix[$i]) was an integer so we pushed it onto the matrix");
} else {
logmsg (9, 8, "element $i ($matrix[$i]) wasn't an integer so we ignored it");
}
}
if ($numericonly) {
logmsg (9, 5, "Returning numeric only results ... ", \@tmpmatrix);
return @tmpmatrix;
} else {
logmsg (9, 5, "Returning full results ... ", \@matrix);
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid using matches $$cfghashref{matches}");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0;
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
} else {
logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count/i) {
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/sum/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..", \@matrix);
logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
logmsg (9, 4, "cfghashref:", $cfghashref);
for my $rule (keys %{ $cfghashref } ) {
logmsg (9, 4, "Checking to see if $rule applies ...");
if (matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref)) {
$rules{$rule} = $rule ;
logmsg (9, 5, "it matches");
} else {
logmsg (9, 5, "it doesn't match");
}
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
- my $ret = 1;
+ my $ret = 1; # 1 = match, 0 = fail
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
logmsg (9, 5, "cfghashref:", $cfghashref);
if (exists ( $$cfghashref{fields} ) ) {
logmsg (9, 5, "cfghashref{fields}:", \%{ $$cfghashref{fields} });
}
logmsg (9, 5, "linehashref:", $linehashref);
foreach my $field (keys (%{ $cfghashref } ) ) {
- logmsg(9, 6, "checking field: $field");
- logmsg(9, 7, "value: $$cfghashref{$field}");
- logmsg (9, 7, "Does field ($field) value - $$linehashref{ $field } match the following regex ...");
- #if ($$cfghashref{fields}{$field} =~ /^!/) {
+ logmsg(9, 6, "checking field: $field with value: $$cfghashref{$field}");
+ logmsg (9, 7, "Does field ($field) with value: $$linehashref{ $field } match the following regex ...");
if ($$cfghashref{$field} =~ /^!/) {
- #my $exp = $$cfghashref{fields}{$field};
my $exp = $$cfghashref{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
- logmsg (9, 7, "neg regexp compar=/$exp/, ret=$ret");
+ logmsg (9, 8, "neg regexp compar /$$linehashref{ $field }/ !~ /$exp/, ret=$ret");
} else {
- #$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{fields}{$field}/);
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{$field}/);
- #logmsg (9, 7, "regexp compar=/$$cfghashref{fields}{$field}/, ret=$ret");
- logmsg (9, 7, "regexp compar=/$$cfghashref{$field}/, ret=$ret");
+ logmsg (9, 8, "regexp compar /$$linehashref{$field}/ =~ /$$cfghashref{$field}/, ret=$ret");
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
my $dumpvar = shift;
my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
# TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
- print STDERR GREEN whowasi."(): $time:", RESET;
+ if ($COLOR) {
+ print STDERR GREEN whowasi."(): d=${time}s:", RESET;
+ } else {
+ print STDERR whowasi."(): d=${time}s:";
+ }
print STDERR " $msg";
if ($dumpvar) {
- print STDERR BLUE Dumper($dumpvar), RESET;
+ if ($COLOR) {
+ print STDERR BLUE Dumper($dumpvar), RESET;
+ } else {
+ print STDERR Dumper($dumpvar);
+ }
}
print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
if ($COLOR >= 1) {
print RED, "WARNING: $msg\n", RESET;
} else {
print "WARNING: $msg\n";
}
} elsif (/e|error/i) {
if ($COLOR >= 1) {
print RED, "ERROR: $msg\n", RESET;
} else {
print "ERROR: $msg\n";
}
} elsif (/c|critical/i) {
if ($COLOR >= 1) {
print RED, "CRITICAL error, aborted ... $msg\n", RESET;
} else {
print "CRITICAL error, aborted ... $msg\n";
}
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
+sub array_max {
+ my $arrayref = shift; # ref to array
+
+ my $highestvalue = $$arrayref[0];
+ for my $i (0 .. @$arrayref ) {
+ $highestvalue = $$arrayref[$i] if $$arrayref[$i] > $highestvalue;
+ }
+
+ return $highestvalue;
+}
+
diff --git a/testcases/4/expected.output b/testcases/4/expected.output
index 6092b81..f97c2c9 100644
--- a/testcases/4/expected.output
+++ b/testcases/4/expected.output
@@ -1,14 +1,14 @@
No match for lines:
Summaries:
pam_unix sessions's opened
- 4 sessions of CRON opened on hostA for root by 0
- 5 sessions of sshd opened on hostA for userx by 0
+ 5 sessions of sshd opened on hostA for userx by uid: 0
+ 4 sessions of CRON opened on hostA for root by uid: 0
pam_unix session's closed
- 5 sessions of sshd closed on hostA for userx
6 sessions of CRON closed on hostA for root
+ 5 sessions of sshd closed on hostA for userx
diff --git a/testcases/4/logparse.conf b/testcases/4/logparse.conf
index 5e95549..4628d5c 100644
--- a/testcases/4/logparse.conf
+++ b/testcases/4/logparse.conf
@@ -1,50 +1,50 @@
#########
FORMAT syslog {
# FIELDS <field count> <delimiter>
# FIELDS <field count> <delimiter> [<parent field>]
# FIELD <field id #> <label>
# FIELD <parent field id#>-<child field id#> <label>
FIELDS 6 "\s+"
FIELD 1 MONTH
FIELD 2 DAY
FIELD 3 TIME
FIELD 4 HOST
FIELD 5 FULLAPP
FIELDS 5-2 /\[/
FIELD 5-1 APP default
FIELD 5-2 APPPID
FIELD 6 FULLMSG
FIELDS 6-2 /\]\s+/
FIELD 6-1 FACILITY
FIELD 6-2 MSG default
LASTLINEINDEX HOST
# LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
# default format to be used for log file analysis
DEFAULT
}
RULE {
MSG /^message repeated (.*) times/ OR /^message repeated$/
ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
# Apply {1} as {x} in the previously applied rule for HOST
ACTION MSG /^message repeated$/ count append LASTLINE
}
RULE pam_unix {
# Nov 15 10:33:21 sysam sshd[25854]: pam_unix(sshd:session): session opened for user mike by (uid=0)
# Nov 15 10:34:01 sysam sshd[25961]: pam_unix(sshd:session): session opened for user mike by (uid=0)
# Nov 15 16:49:43 sysam sshd[25854]: pam_unix(sshd:session): session closed for user mike
MSG /pam_unix\((.*):session\):/
# opened
ACTION MSG /pam_unix\((.*):session\): session (.*) for user (.*) by \(uid=(.*)\)/ {HOST, APP, 1, 2, 3, 4}
# closed
ACTION MSG /pam_unix\((.*):session\): session (.*) for user (.*)/ {HOST, APP, 1, 2, 3}
- REPORT "pam_unix sessions's opened" "{x} sessions of {2} opened on {1} for {5} by {6}" 4=opened
+ REPORT "pam_unix sessions's opened" "{x} sessions of {2} opened on {1} for {5} by uid: {6}" 4=opened
REPORT "pam_unix session's closed" "{x} sessions of {2} closed on {1} for {5}" 4=closed
}
#######################
diff --git a/testcases/8/expected.output b/testcases/8/expected.output
index c60f1d0..56a2f8b 100644
--- a/testcases/8/expected.output
+++ b/testcases/8/expected.output
@@ -1,14 +1,14 @@
No match for lines:
[31m
Summaries:
[0m[34mpam_unix sessions's opened
- [0m[32m 4 sessions of CRON opened on hostA for root by 0
[0m[32m 5 sessions of sshd opened on hostA for userx by 0
+ [0m[32m 4 sessions of CRON opened on hostA for root by 0
[0m
[34mpam_unix session's closed
- [0m[32m 5 sessions of sshd closed on hostA for userx
[0m[32m 6 sessions of CRON closed on hostA for root
+ [0m[32m 5 sessions of sshd closed on hostA for userx
[0m
diff --git a/testcases/test.sh b/testcases/test.sh
index 12c533b..3d5fea1 100755
--- a/testcases/test.sh
+++ b/testcases/test.sh
@@ -1,25 +1,25 @@
#!/bin/bash
dir="`pwd`/`dirname $0`"
OUTFILE="/tmp/logparse.test.output"
DEFAULTARGS=" -l ./test.log -c ./logparse.conf -d 0"
export LOGPARSE="../../logparse.pl"
cd $dir
-for testcasedir in `ls -dF1 * | grep '/$'`
+for testcasedir in `ls -dF1 * | grep '/$' | sort -n`
do
cd $dir/$testcasedir
if [ -x ./args ] ; then
bash ./args > $OUTFILE
else
${LOGPARSE} $DEFAULTARGS > $OUTFILE
fi
diff -u $OUTFILE ./expected.output
if test $? -eq 0 ; then
echo Testcase `echo $testcasedir | sed 's/\///g'` passed
else
echo Testcase `echo $testcasedir| sed 's/\///g'` failed
fi
rm $OUTFILE
done
|
mikeknox/LogParse | af67f4f0af3b11ac0d14bc534d88b19ccb2f1533 | Fixed a couploe of bugs that caused lines containing brackets that were't IGNORE'd to be handled incorectly. Added some more debug information. The color option is also controllable on the debug output now as well. | diff --git a/testcases/10/Description b/testcases/10/Description
new file mode 100644
index 0000000..a245137
--- /dev/null
+++ b/testcases/10/Description
@@ -0,0 +1 @@
+Check that sumamry actions followed by an ignore action function correctly.
diff --git a/testcases/10/expected.output b/testcases/10/expected.output
new file mode 100644
index 0000000..92db557
--- /dev/null
+++ b/testcases/10/expected.output
@@ -0,0 +1,17 @@
+
+
+No match for lines:
+ Apr 29 14:22:19 dhcp-166 smartd[8607]: Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...
+ Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...
+ Apr 29 14:44:35 dhcp-166 smartd[2902]: smartd 5.39 2008-10-24 22:33 [x86_64-suse-linux-gnu] (openSUSE RPM) Copyright (C) 2002-8 by Bruce Allen, http://smartmontools.sourceforge.net
+
+
+Summaries:
+SMART
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sda on linux-xui7dhcp-166
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sdc on linux-xui7dhcp-166
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sdb on linux-xui7dhcp-166
+ 2 counts of err code 4 (IEC (SMART) mode page) for /dev/sda on dhcp-166
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sdb on dhcp-166
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sdc on dhcp-166
+
diff --git a/testcases/10/logparse.conf b/testcases/10/logparse.conf
new file mode 100644
index 0000000..851ac2d
--- /dev/null
+++ b/testcases/10/logparse.conf
@@ -0,0 +1,50 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 FULLAPP
+ FIELDS 5-2 /\[/
+ FIELD 5-1 APP default
+ FIELD 5-2 APPPID
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /\]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE smartd {
+
+ APP smartd
+ ACTION MSG /^Opened configuration file / IGNORE
+ ACTION MSG /^Configuration file (.*) was parsed, found DEVICESCAN, scanning devices/ IGNORE
+ ACTION MSG /^Device: (.*), opened$/ IGNORE
+ ACTION MSG /^Device: (.*), Bad (.*), err=(\d+), skip device/ {HOST, 1, 2, 3}
+ ACTION MSG /^Unable to monitor any SMART enabled devices."/ IGNORE
+ ACTION MSG /^Drive: DEVICESCAN, implied '(.*)' Directive on line 26 of file/ IGNORE
+
+ REPORT "SMART" "{x} counts of err code {4} ({3}) for {2} on {1}" count
+}
+
+#######################
diff --git a/testcases/10/test.log b/testcases/10/test.log
new file mode 100644
index 0000000..8a9d569
--- /dev/null
+++ b/testcases/10/test.log
@@ -0,0 +1,22 @@
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Configuration file /etc/smartd.conf was parsed, found DEVICESCAN, scanning devices
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sda, opened
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sda, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sdb, opened
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sdb, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sdc, opened
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sdc, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sda, opened
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sda, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sdb, opened
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sdb, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sdc, opened
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sdc, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...
+Apr 29 14:44:35 dhcp-166 smartd[2902]: smartd 5.39 2008-10-24 22:33 [x86_64-suse-linux-gnu] (openSUSE RPM) Copyright (C) 2002-8 by Bruce Allen, http://smartmontools.sourceforge.net
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Opened configuration file /etc/smartd.conf
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Drive: DEVICESCAN, implied '-a' Directive on line 26 of file /etc/smartd.conf
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Configuration file /etc/smartd.conf was parsed, found DEVICESCAN, scanning devices
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Device: /dev/sda, opened
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Device: /dev/sda, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Device: /dev/sdb, opened
diff --git a/testcases/11/Description b/testcases/11/Description
new file mode 100644
index 0000000..9bf6e5e
--- /dev/null
+++ b/testcases/11/Description
@@ -0,0 +1 @@
+Check that a file specified in an ACTION is handled correctly, currently this fails
diff --git a/testcases/11/expected.output b/testcases/11/expected.output
new file mode 100644
index 0000000..92db557
--- /dev/null
+++ b/testcases/11/expected.output
@@ -0,0 +1,17 @@
+
+
+No match for lines:
+ Apr 29 14:22:19 dhcp-166 smartd[8607]: Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...
+ Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...
+ Apr 29 14:44:35 dhcp-166 smartd[2902]: smartd 5.39 2008-10-24 22:33 [x86_64-suse-linux-gnu] (openSUSE RPM) Copyright (C) 2002-8 by Bruce Allen, http://smartmontools.sourceforge.net
+
+
+Summaries:
+SMART
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sda on linux-xui7dhcp-166
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sdc on linux-xui7dhcp-166
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sdb on linux-xui7dhcp-166
+ 2 counts of err code 4 (IEC (SMART) mode page) for /dev/sda on dhcp-166
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sdb on dhcp-166
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sdc on dhcp-166
+
diff --git a/testcases/11/logparse.conf b/testcases/11/logparse.conf
new file mode 100644
index 0000000..6ae44d0
--- /dev/null
+++ b/testcases/11/logparse.conf
@@ -0,0 +1,50 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 FULLAPP
+ FIELDS 5-2 /\[/
+ FIELD 5-1 APP default
+ FIELD 5-2 APPPID
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /\]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE smartd {
+
+ APP smartd
+ ACTION MSG /^Opened configuration file / IGNORE
+ ACTION MSG /^Configuration file (.*) was parsed, found DEVICESCAN, scanning devices/ IGNORE
+ ACTION MSG /^Device: (.*), opened$/ IGNORE
+ ACTION MSG /^Device: (.*), Bad (.*), err=(\d+), skip device/ {HOST, 1, 2, 3}
+ ACTION MSG /^Unable to monitor any SMART enabled devices."/ IGNORE
+ ACTION MSG /^Drive: DEVICESCAN, implied '(.*)' Directive on line 26 of file \/etc\/smartd.conf/ IGNORE
+
+ REPORT "SMART" "{x} counts of err code {4} ({3}) for {2} on {1}" count
+}
+
+#######################
diff --git a/testcases/11/test.log b/testcases/11/test.log
new file mode 100644
index 0000000..8a9d569
--- /dev/null
+++ b/testcases/11/test.log
@@ -0,0 +1,22 @@
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Configuration file /etc/smartd.conf was parsed, found DEVICESCAN, scanning devices
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sda, opened
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sda, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sdb, opened
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sdb, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sdc, opened
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sdc, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sda, opened
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sda, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sdb, opened
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sdb, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sdc, opened
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sdc, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...
+Apr 29 14:44:35 dhcp-166 smartd[2902]: smartd 5.39 2008-10-24 22:33 [x86_64-suse-linux-gnu] (openSUSE RPM) Copyright (C) 2002-8 by Bruce Allen, http://smartmontools.sourceforge.net
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Opened configuration file /etc/smartd.conf
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Drive: DEVICESCAN, implied '-a' Directive on line 26 of file /etc/smartd.conf
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Configuration file /etc/smartd.conf was parsed, found DEVICESCAN, scanning devices
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Device: /dev/sda, opened
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Device: /dev/sda, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Device: /dev/sdb, opened
diff --git a/testcases/9/Description b/testcases/9/Description
new file mode 100644
index 0000000..bca62d7
--- /dev/null
+++ b/testcases/9/Description
@@ -0,0 +1,2 @@
+test log entries with brackets and forward slashes. i.e. ... (, ), and /
+These can create problems with the reports
diff --git a/testcases/9/expected.output b/testcases/9/expected.output
new file mode 100644
index 0000000..45b5d0b
--- /dev/null
+++ b/testcases/9/expected.output
@@ -0,0 +1,18 @@
+
+
+No match for lines:
+ Apr 29 14:22:19 dhcp-166 smartd[8607]: Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...
+ Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...
+ Apr 29 14:44:35 dhcp-166 smartd[2902]: smartd 5.39 2008-10-24 22:33 [x86_64-suse-linux-gnu] (openSUSE RPM) Copyright (C) 2002-8 by Bruce Allen, http://smartmontools.sourceforge.net
+ Apr 29 14:44:35 dhcp-166 smartd[2902]: Drive: DEVICESCAN, implied '-a' Directive on line 26 of file /etc/smartd.conf
+
+
+Summaries:
+SMART
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sda on linux-xui7dhcp-166
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sdc on linux-xui7dhcp-166
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sdb on linux-xui7dhcp-166
+ 2 counts of err code 4 (IEC (SMART) mode page) for /dev/sda on dhcp-166
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sdb on dhcp-166
+ 1 counts of err code 4 (IEC (SMART) mode page) for /dev/sdc on dhcp-166
+
diff --git a/testcases/9/logparse.conf b/testcases/9/logparse.conf
new file mode 100644
index 0000000..c513d15
--- /dev/null
+++ b/testcases/9/logparse.conf
@@ -0,0 +1,52 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 FULLAPP
+ FIELDS 5-2 /\[/
+ FIELD 5-1 APP default
+ FIELD 5-2 APPPID
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /\]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE smartd {
+
+ APP smartd
+ ACTION MSG /^Opened configuration file / IGNORE
+ ACTION MSG /^Configuration file (.*) was parsed, found DEVICESCAN, scanning devices/ IGNORE
+ ACTION MSG /^Device: (.*), opened$/ IGNORE
+ ACTION MSG /^Unable to monitor any SMART enabled devices."/ IGNORE
+}
+
+RULE smartd-skip {
+ APP smartd
+ ACTION MSG /^Device: (.*), Bad (.*), err=(\d+), skip device/ {HOST, 1, 2, 3}
+
+ REPORT "SMART" "{x} counts of err code {4} ({3}) for {2} on {1}" count
+}
+#######################
diff --git a/testcases/9/test.log b/testcases/9/test.log
new file mode 100644
index 0000000..8a9d569
--- /dev/null
+++ b/testcases/9/test.log
@@ -0,0 +1,22 @@
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Configuration file /etc/smartd.conf was parsed, found DEVICESCAN, scanning devices
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sda, opened
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sda, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sdb, opened
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sdb, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sdc, opened
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Device: /dev/sdc, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:22:19 dhcp-166 smartd[8607]: Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sda, opened
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sda, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sdb, opened
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sdb, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sdc, opened
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Device: /dev/sdc, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:34:30 linux-xui7dhcp-166 smartd[2929]: Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...
+Apr 29 14:44:35 dhcp-166 smartd[2902]: smartd 5.39 2008-10-24 22:33 [x86_64-suse-linux-gnu] (openSUSE RPM) Copyright (C) 2002-8 by Bruce Allen, http://smartmontools.sourceforge.net
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Opened configuration file /etc/smartd.conf
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Drive: DEVICESCAN, implied '-a' Directive on line 26 of file /etc/smartd.conf
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Configuration file /etc/smartd.conf was parsed, found DEVICESCAN, scanning devices
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Device: /dev/sda, opened
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Device: /dev/sda, Bad IEC (SMART) mode page, err=4, skip device
+Apr 29 14:44:35 dhcp-166 smartd[2902]: Device: /dev/sdb, opened
|
mikeknox/LogParse | 21d0aa5b496b3c3f94fa212c42b0c297b8761df5 | Added option --color to colorise reports and debug output | diff --git a/logparse.pl b/logparse.pl
index 99ca511..e439d99 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1088 +1,1123 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Long;
use Data::Dumper qw(Dumper);
# Globals
#
my $STARTTIME = time();
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my @CONFIGFILES;# = ("logparse.conf");
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
my $MATCH; # Only lines matching this regex will be parsed
+my $COLOR = 0;
my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
"l|log=s" => \@LOGFILES,
"d|debug=i" => \$DEBUG,
- "m|match=s" => \$MATCH
+ "m|match=s" => \$MATCH,
+ "color" => \$COLOR
);
unless ($result) {
- warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>]\nInvalid config options passed");
+ warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>] [--color]\nInvalid config options passed");
+}
+
+if ($COLOR) {
+ use Term::ANSIColor qw(:constants);
}
@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
@LOGFILES = split(/,/,join(',',@LOGFILES));
if ($MATCH) {
$MATCH =~ s/\^\"//;
$MATCH =~ s/\"$//;
logmsg (2, 3, "Skipping lines which match $MATCH");
}
loadcfg (\%cfghash, \@CONFIGFILES);
logmsg(7, 3, "cfghash:", \%cfghash);
processlogfile(\%cfghash, \%reshash, \@LOGFILES);
logmsg (9, 0, "reshash ..\n", %reshash);
report(\%cfghash, \%reshash);
logmsg (9, 0, "reshash ..\n", %reshash);
logmsg (9, 0, "cfghash ..\n", %cfghash);
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text does not contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ", \@tmp);
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
logmsg (9, 4, "line results now ...", $linehashref);
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Processing logfiles: ", $logfileref);
foreach my $logfile (@$logfileref) {
logmsg(1, 0, "processing $logfile using format $format...");
open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
#logmsg(5, 1, "skipping as line doesn't match the match regex") and
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
logmsg(9, 1, "Checking line: $line{line}");
logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
if ($line{line} =~ /$MATCH/) {
my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
if (keys %rules >= 0) {
logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
$execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
logmsg (9, 3, "#rules in list .., ".keys(%rules) );
logmsg (9, 3, "\%rules ..", \%rules);
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
} else {
logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
}
logmsg(9 ,1, "Results hash ...", \%$reshashref );
logmsg (5, 1, "finished processing line");
}
close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
}
- print "\n\nSummaries:\n";
+ if ($COLOR) {
+ print RED "\n\nSummaries:\n", RESET;
+ } else {
+ print "\n\nSummaries:\n";
+ }
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (4, 1, "Rule[rptid]: $rule\[$rptid\]");
logmsg (5, 2, "\%ruleresults ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
- print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
+ if ($COLOR) {
+ print BLUE "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n", RESET;
+ } else {
+ print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
+ }
} else {
logmsg (4, 2, "No title");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
- print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
+ if ($COLOR) {
+ print GREEN rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key), RESET;
+ } else {
+ print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
+ }
} else {
- print "\t$$reshashref{$rule}{$key}: $key\n";
+ if ($COLOR) {
+ print GREEN "\t$$reshashref{$rule}{$key}: $key\n", RESET;
+ } else {
+ print "\t$$reshashref{$rule}{$key}: $key\n";
+ }
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
for my $actionid (keys( %$reshashref ) ) {
for my $key (keys %{ $$reshashref{$actionid} } ) {
(my @values) = split (/:/, $key);
logmsg (9, 5, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
if (exists($$cfghashref{reports}[$rptid]{field})) {
logmsg (9, 4, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 5, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 6, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 7, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 7, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
}
$targetkeymatch =~ s/^://;
logmsg (9, 5, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ", $cfghashref);
logmsg (7, 3, "reshash ... ", $reshashref);
my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "Settting \$fields[$field] ($fields[$field]) = \$fields[$i] ($fields[$i])");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
$line.="\n";
#if (exists($$cfghashref{field})) {
#logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
#if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
#logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
#$line = "";
#}
#}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
logmsg (9, 5, "Matchlist ... $matchlist");
logmsg (9, 5, "Matchlist has morphed in \@matrix with elements ... ", \@matrix);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
logmsg (9, 6, "\$matchlist didn't have a \",\", so we shoved it onto \@matrix. Which is now ... ", \@matrix);
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
logmsg (9, 7, "\$i: $i");
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
logmsg (9, 8, "element $i ($matrix[$i]) was an integer so we pushed it onto the matrix");
} else {
logmsg (9, 8, "element $i ($matrix[$i]) wasn't an integer so we ignored it");
}
}
if ($numericonly) {
logmsg (9, 5, "Returning numeric only results ... ", \@tmpmatrix);
return @tmpmatrix;
} else {
logmsg (9, 5, "Returning full results ... ", \@matrix);
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid using matches $$cfghashref{matches}");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0;
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
} else {
logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count/i) {
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/sum/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..", \@matrix);
logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
logmsg (9, 4, "cfghashref:", $cfghashref);
for my $rule (keys %{ $cfghashref } ) {
logmsg (9, 4, "Checking to see if $rule applies ...");
if (matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref)) {
$rules{$rule} = $rule ;
logmsg (9, 5, "it matches");
} else {
logmsg (9, 5, "it doesn't match");
}
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1;
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
logmsg (9, 5, "cfghashref:", $cfghashref);
if (exists ( $$cfghashref{fields} ) ) {
logmsg (9, 5, "cfghashref{fields}:", \%{ $$cfghashref{fields} });
}
logmsg (9, 5, "linehashref:", $linehashref);
foreach my $field (keys (%{ $cfghashref } ) ) {
logmsg(9, 6, "checking field: $field");
logmsg(9, 7, "value: $$cfghashref{$field}");
logmsg (9, 7, "Does field ($field) value - $$linehashref{ $field } match the following regex ...");
#if ($$cfghashref{fields}{$field} =~ /^!/) {
if ($$cfghashref{$field} =~ /^!/) {
#my $exp = $$cfghashref{fields}{$field};
my $exp = $$cfghashref{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
logmsg (9, 7, "neg regexp compar=/$exp/, ret=$ret");
} else {
#$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{fields}{$field}/);
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{$field}/);
#logmsg (9, 7, "regexp compar=/$$cfghashref{fields}{$field}/, ret=$ret");
logmsg (9, 7, "regexp compar=/$$cfghashref{$field}/, ret=$ret");
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
my $dumpvar = shift;
my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
# TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
- print STDERR whowasi."(): $time: $msg";
+ print STDERR GREEN whowasi."(): $time:", RESET;
+ print STDERR " $msg";
if ($dumpvar) {
- print STDERR Dumper($dumpvar);
+ print STDERR BLUE Dumper($dumpvar), RESET;
}
print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
- print "WARNING: $msg\n";
+ if ($COLOR >= 1) {
+ print RED, "WARNING: $msg\n", RESET;
+ } else {
+ print "WARNING: $msg\n";
+ }
} elsif (/e|error/i) {
- print "ERROR: $msg\n";
+ if ($COLOR >= 1) {
+ print RED, "ERROR: $msg\n", RESET;
+ } else {
+ print "ERROR: $msg\n";
+ }
} elsif (/c|critical/i) {
- print "CRITICAL error, aborted ... $msg\n";
+ if ($COLOR >= 1) {
+ print RED, "CRITICAL error, aborted ... $msg\n", RESET;
+ } else {
+ print "CRITICAL error, aborted ... $msg\n";
+ }
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
|
mikeknox/LogParse | 4c54573e790c386a6e3a409304915553667c35c2 | Added test case for option --color | diff --git a/testcases/8/Description b/testcases/8/Description
new file mode 100644
index 0000000..20a4068
--- /dev/null
+++ b/testcases/8/Description
@@ -0,0 +1 @@
+Test --color option
diff --git a/testcases/8/args b/testcases/8/args
new file mode 100755
index 0000000..8260cf8
--- /dev/null
+++ b/testcases/8/args
@@ -0,0 +1 @@
+${LOGPARSE} -l ./test.log -c ./logparse.conf -d 0 --color
diff --git a/testcases/8/expected.output b/testcases/8/expected.output
new file mode 100644
index 0000000..c60f1d0
--- /dev/null
+++ b/testcases/8/expected.output
@@ -0,0 +1,14 @@
+
+
+No match for lines:
+[31m
+
+Summaries:
+ [0m[34mpam_unix sessions's opened
+ [0m[32m 4 sessions of CRON opened on hostA for root by 0
+ [0m[32m 5 sessions of sshd opened on hostA for userx by 0
+ [0m
+[34mpam_unix session's closed
+ [0m[32m 5 sessions of sshd closed on hostA for userx
+ [0m[32m 6 sessions of CRON closed on hostA for root
+ [0m
diff --git a/testcases/8/logparse.conf b/testcases/8/logparse.conf
new file mode 100644
index 0000000..5e95549
--- /dev/null
+++ b/testcases/8/logparse.conf
@@ -0,0 +1,50 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 FULLAPP
+ FIELDS 5-2 /\[/
+ FIELD 5-1 APP default
+ FIELD 5-2 APPPID
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /\]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE pam_unix {
+# Nov 15 10:33:21 sysam sshd[25854]: pam_unix(sshd:session): session opened for user mike by (uid=0)
+# Nov 15 10:34:01 sysam sshd[25961]: pam_unix(sshd:session): session opened for user mike by (uid=0)
+# Nov 15 16:49:43 sysam sshd[25854]: pam_unix(sshd:session): session closed for user mike
+ MSG /pam_unix\((.*):session\):/
+ # opened
+ ACTION MSG /pam_unix\((.*):session\): session (.*) for user (.*) by \(uid=(.*)\)/ {HOST, APP, 1, 2, 3, 4}
+ # closed
+ ACTION MSG /pam_unix\((.*):session\): session (.*) for user (.*)/ {HOST, APP, 1, 2, 3}
+ REPORT "pam_unix sessions's opened" "{x} sessions of {2} opened on {1} for {5} by {6}" 4=opened
+ REPORT "pam_unix session's closed" "{x} sessions of {2} closed on {1} for {5}" 4=closed
+}
+
+#######################
diff --git a/testcases/8/test.log b/testcases/8/test.log
new file mode 100644
index 0000000..93b0fe2
--- /dev/null
+++ b/testcases/8/test.log
@@ -0,0 +1,20 @@
+Nov 15 06:47:10 hostA CRON[22709]: pam_unix(cron:session): session closed for user root
+Nov 15 06:47:55 hostA CRON[22387]: pam_unix(cron:session): session closed for user root
+Nov 15 06:50:01 hostA CRON[23212]: pam_unix(cron:session): session opened for user root by (uid=0)
+Nov 15 06:50:02 hostA CRON[23212]: pam_unix(cron:session): session closed for user root
+Nov 15 07:00:01 hostA CRON[23322]: pam_unix(cron:session): session opened for user root by (uid=0)
+Nov 15 07:00:01 hostA CRON[23322]: pam_unix(cron:session): session closed for user root
+Nov 15 07:09:01 hostA CRON[23401]: pam_unix(cron:session): session opened for user root by (uid=0)
+Nov 15 07:09:01 hostA CRON[23401]: pam_unix(cron:session): session closed for user root
+Nov 15 07:10:01 hostA CRON[23473]: pam_unix(cron:session): session opened for user root by (uid=0)
+Nov 15 07:10:02 hostA CRON[23473]: pam_unix(cron:session): session closed for user root
+Nov 15 10:33:21 hostA sshd[25854]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 15 10:34:01 hostA sshd[25961]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 15 16:49:43 hostA sshd[25854]: pam_unix(sshd:session): session closed for user userx
+Nov 15 16:53:03 hostA sshd[25961]: pam_unix(sshd:session): session closed for user userx
+Nov 15 18:57:50 hostA sshd[32401]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 15 21:12:48 hostA sshd[32401]: pam_unix(sshd:session): session closed for user userx
+Nov 16 03:01:27 hostA sshd[12059]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 16 03:12:55 hostA sshd[12059]: pam_unix(sshd:session): session closed for user userx
+Nov 16 03:21:54 hostA sshd[12495]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 16 03:56:08 hostA sshd[12495]: pam_unix(sshd:session): session closed for user userx
|
mikeknox/LogParse | 555850de4c41ff1c57ca7c3a82cd2233af8d0156 | additional option message | diff --git a/logparse.pl b/logparse.pl
index 38e95ce..32de31d 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1046 +1,1078 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Long;
use Data::Dumper qw(Dumper);
# Globals
#
my $STARTTIME = time();
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my @CONFIGFILES;# = ("logparse.conf");
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
-#my $SYSLOGFILE = "/var/log/messages";
my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
+my $MATCH; # Only lines matching this regex will be parsed
-#getopt('cdl', \%opts);
my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
"l|log=s" => \@LOGFILES,
- "d|debug=i" => \$DEBUG
+ "d|debug=i" => \$DEBUG,
+ "m|match=s" => \$MATCH
);
+
+unless ($result) {
+ warning ("c", "Usage: logparse.pl -c <config file> -l <log file> [-d <debug level>]\nInvalid config options passed");
+}
+
@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
@LOGFILES = split(/,/,join(',',@LOGFILES));
-unless ($result) {
- warning ("c", "Invalid config options passed");
+if ($MATCH) {
+ $MATCH =~ s/\^\"//;
+ $MATCH =~ s/\"$//;
+ logmsg (2, 3, "Skipping lines which match $MATCH");
}
-#$DEBUG = $opts{d} if $opts{d};
-#$CONFIGFILE = $opts{c} if $opts{c};
-#$SYSLOGFILE = $opts{l} if $opts{l};
loadcfg (\%cfghash, \@CONFIGFILES);
logmsg(7, 3, "cfghash:", \%cfghash);
processlogfile(\%cfghash, \%reshash, \@LOGFILES);
logmsg (9, 0, "reshash ..\n", %reshash);
report(\%cfghash, \%reshash);
logmsg (9, 0, "reshash ..\n", %reshash);
logmsg (9, 0, "cfghash ..\n", %cfghash);
+
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
- logmsg (5, 4, "\$text doesnot contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
+ logmsg (5, 4, "\$text does not contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ", \@tmp);
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
logmsg (9, 4, "line results now ...", $linehashref);
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Processing logfiles: ", $logfileref);
foreach my $logfile (@$logfileref) {
logmsg(1, 0, "processing $logfile using format $format...");
open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
+ #logmsg(5, 1, "skipping as line doesn't match the match regex") and
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
logmsg(9, 1, "Checking line: $line{line}");
logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
- my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
- logmsg(9, 2, keys (%rules)." matches so far");
+ if ($line{line} =~ /$MATCH/) {
+ my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
+ logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
- if (keys %rules >= 0) {
- logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
+ if (keys %rules >= 0) {
+ logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
- my $actrule = 0;
- my %tmprules = %rules;
- for my $rule (keys %tmprules) {
- logmsg (9, 3, "checking rule: $rule");
- my $execruleret = 0;
- if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
- $execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
- } else {
- logmsg (2, 3, "No actions defined for rule; $rule");
- }
- logmsg (9, 4, "execrule returning $execruleret");
- delete $rules{$rule} unless $execruleret;
- # TODO: update &actionrule();
- }
- logmsg (9, 3, "#rules in list .., ".keys(%rules) );
- logmsg (9, 3, "\%rules ..", \%rules);
- $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
- # lastline & repeat
- } # rules > 0
- if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
- delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
- }
- $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
+ my $actrule = 0;
+ my %tmprules = %rules;
+ for my $rule (keys %tmprules) {
+ logmsg (9, 3, "checking rule: $rule");
+ my $execruleret = 0;
+ if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
+ $execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
+ } else {
+ logmsg (2, 3, "No actions defined for rule; $rule");
+ }
+ logmsg (9, 4, "execrule returning $execruleret");
+ delete $rules{$rule} unless $execruleret;
+ # TODO: update &actionrule();
+ }
+ logmsg (9, 3, "#rules in list .., ".keys(%rules) );
+ logmsg (9, 3, "\%rules ..", \%rules);
+ $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
+ # lastline & repeat
+ } # rules > 0
+ if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
+ delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
+ }
+ $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
- if ( keys(%rules) == 0) {
- # Add new unmatched linescode
+ if ( keys(%rules) == 0) {
+ # Add new unmatched linescode
+ }
+ } else {
+ logmsg(5, 1, "Not processing rules as text didn't match match regexp: /$MATCH/");
}
logmsg(9 ,1, "Results hash ...", \%$reshashref );
logmsg (5, 1, "finished processing line");
}
close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
}
print "\n\nSummaries:\n";
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (4, 1, "Rule[rptid]: $rule\[$rptid\]");
logmsg (5, 2, "\%ruleresults ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
} else {
logmsg (4, 2, "No title");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
for my $actionid (keys( %$reshashref ) ) {
for my $key (keys %{ $$reshashref{$actionid} } ) {
(my @values) = split (/:/, $key);
logmsg (9, 5, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
if (exists($$cfghashref{reports}[$rptid]{field})) {
logmsg (9, 4, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 5, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 6, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 7, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 7, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
}
$targetkeymatch =~ s/^://;
logmsg (9, 5, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ", $cfghashref);
logmsg (7, 3, "reshash ... ", $reshashref);
my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "Settting \$fields[$field] ($fields[$field]) = \$fields[$i] ($fields[$i])");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
$line.="\n";
#if (exists($$cfghashref{field})) {
#logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
#if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
#logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
#$line = "";
#}
#}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
}
}
if ($numericonly) {
return @tmpmatrix;
} else {
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0;
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
} else {
logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count/i) {
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/sum/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..", \@matrix);
logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
+ logmsg (9, 4, "cfghashref:", $cfghashref);
for my $rule (keys %{ $cfghashref } ) {
- $rules{$rule} = $rule if matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref);
+ logmsg (9, 4, "Checking to see if $rule applies ...");
+ if (matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref)) {
+ $rules{$rule} = $rule ;
+ logmsg (9, 5, "it matches");
+ } else {
+ logmsg (9, 5, "it doesn't match");
+ }
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1;
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
+ logmsg (9, 5, "cfghashref:", $cfghashref);
+ if (exists ( $$cfghashref{fields} ) ) {
+ logmsg (9, 5, "cfghashref{fields}:", \%{ $$cfghashref{fields} });
+ }
+ logmsg (9, 5, "linehashref:", $linehashref);
+
foreach my $field (keys (%{ $cfghashref } ) ) {
- if ($$cfghashref{fields}{$field} =~ /^!/) {
- my $exp = $$cfghashref{fields}{$field};
+ logmsg(9, 6, "checking field: $field");
+ logmsg(9, 7, "value: $$cfghashref{$field}");
+ logmsg (9, 7, "Does field ($field) value - $$linehashref{ $field } match the following regex ...");
+ #if ($$cfghashref{fields}{$field} =~ /^!/) {
+ if ($$cfghashref{$field} =~ /^!/) {
+ #my $exp = $$cfghashref{fields}{$field};
+ my $exp = $$cfghashref{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
+ logmsg (9, 7, "neg regexp compar=/$exp/, ret=$ret");
} else {
- $ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{fields}{$field}/);
+ #$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{fields}{$field}/);
+ $ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{$field}/);
+ #logmsg (9, 7, "regexp compar=/$$cfghashref{fields}{$field}/, ret=$ret");
+ logmsg (9, 7, "regexp compar=/$$cfghashref{$field}/, ret=$ret");
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
my $dumpvar = shift;
my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
# TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
print STDERR whowasi."(): $time: $msg";
if ($dumpvar) {
print STDERR Dumper($dumpvar);
}
print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
print "WARNING: $msg\n";
} elsif (/e|error/i) {
print "ERROR: $msg\n";
} elsif (/c|critical/i) {
print "CRITICAL error, aborted ... $msg\n";
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
|
mikeknox/LogParse | ac8699c106c1d20134bffa4265895976463a9f19 | Additional debug info | diff --git a/logparse.pl b/logparse.pl
index 38e95ce..ea3c9e0 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -249,798 +249,808 @@ sub processlogfile {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
$execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
logmsg (9, 3, "#rules in list .., ".keys(%rules) );
logmsg (9, 3, "\%rules ..", \%rules);
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
logmsg(9 ,1, "Results hash ...", \%$reshashref );
logmsg (5, 1, "finished processing line");
}
close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
}
print "\n\nSummaries:\n";
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (4, 1, "Rule[rptid]: $rule\[$rptid\]");
logmsg (5, 2, "\%ruleresults ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
} else {
logmsg (4, 2, "No title");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
for my $actionid (keys( %$reshashref ) ) {
for my $key (keys %{ $$reshashref{$actionid} } ) {
(my @values) = split (/:/, $key);
logmsg (9, 5, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
if (exists($$cfghashref{reports}[$rptid]{field})) {
logmsg (9, 4, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 5, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 6, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 7, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 7, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
}
$targetkeymatch =~ s/^://;
logmsg (9, 5, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ", $cfghashref);
logmsg (7, 3, "reshash ... ", $reshashref);
my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "Settting \$fields[$field] ($fields[$field]) = \$fields[$i] ($fields[$i])");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
$line.="\n";
#if (exists($$cfghashref{field})) {
#logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
#if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
#logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
#$line = "";
#}
#}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
+
+ logmsg (9, 5, "Matchlist ... $matchlist");
+ logmsg (9, 5, "Matchlist has morphed in \@matrix with elements ... ", \@matrix);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
+ logmsg (9, 6, "\$matchlist didn't have a \",\", so we shoved it onto \@matrix. Which is now ... ", \@matrix);
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
+ logmsg (9, 7, "\$i: $i");
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
- }
+ logmsg (9, 8, "element $i ($matrix[$i]) was an integer so we pushed it onto the matrix");
+ } else {
+ logmsg (9, 8, "element $i ($matrix[$i]) wasn't an integer so we ignored it");
+ }
}
if ($numericonly) {
+ logmsg (9, 5, "Returning numeric only results ... ", \@tmpmatrix);
return @tmpmatrix;
} else {
+ logmsg (9, 5, "Returning full results ... ", \@matrix);
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
- logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid");
+ logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid using matches $$cfghashref{matches}");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0;
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
} else {
logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count/i) {
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/sum/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..", \@matrix);
logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
for my $rule (keys %{ $cfghashref } ) {
$rules{$rule} = $rule if matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref);
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1;
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
foreach my $field (keys (%{ $cfghashref } ) ) {
if ($$cfghashref{fields}{$field} =~ /^!/) {
my $exp = $$cfghashref{fields}{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{fields}{$field}/);
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
my $dumpvar = shift;
my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
# TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
print STDERR whowasi."(): $time: $msg";
if ($dumpvar) {
print STDERR Dumper($dumpvar);
}
print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
print "WARNING: $msg\n";
} elsif (/e|error/i) {
print "ERROR: $msg\n";
} elsif (/c|critical/i) {
print "CRITICAL error, aborted ... $msg\n";
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
|
mikeknox/LogParse | 04420c57fdc73e6cce1d32cd7c8e720191e13d69 | Added a new option <match> which is optional. [-m <some regexp>] will only process the line if it matches the regexp Added testcases for this. Fixed a bug in the field matching for rules Fixed the testcases after this bug. | diff --git a/testcases/1/logparse.conf b/testcases/1/logparse.conf
index 0ca05fd..8b9db13 100644
--- a/testcases/1/logparse.conf
+++ b/testcases/1/logparse.conf
@@ -1,44 +1,44 @@
#########
FORMAT syslog {
# FIELDS <field count> <delimiter>
# FIELDS <field count> <delimiter> [<parent field>]
# FIELD <field id #> <label>
# FIELD <parent field id#>-<child field id#> <label>
FIELDS 6 "\s+"
FIELD 1 MONTH
FIELD 2 DAY
FIELD 3 TIME
FIELD 4 HOST
FIELD 5 APP
FIELD 6 FULLMSG
FIELDS 6-2 /]\s+/
FIELD 6-1 FACILITY
FIELD 6-2 MSG default
LASTLINEINDEX HOST
# LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
# default format to be used for log file analysis
DEFAULT
}
RULE {
MSG /^message repeated (.*) times/ OR /^message repeated$/
ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
# Apply {1} as {x} in the previously applied rule for HOST
ACTION MSG /^message repeated$/ count append LASTLINE
}
RULE sudo {
APP sudo
- MSG /.* : .* ; PWD=/
+ #MSG /.* : .* ; PWD=/
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
ACTION MSG /(.*): \(command continued\) / IGNORE
REPORT "Sudo usage by cmd/user/host" "{2} ran {4} as {3} on {1}: {x} times" count
REPORT "Sudo usage by user/host" "{2} ran {x} sudo cmds on {1}" count
# by default {x} is total
}
#######################
#2
diff --git a/testcases/2/args b/testcases/2/args
old mode 100644
new mode 100755
index a0baad1..c4302af
--- a/testcases/2/args
+++ b/testcases/2/args
@@ -1 +1 @@
--l ./test.log.1 -l ./test.log.2 -c ./logparse.conf.1 -c ./logparse.conf.2 -d 0
+${LOGPARSE} -l ./test.log.1 -l ./test.log.2 -c ./logparse.conf.1 -c ./logparse.conf.2 -d 0
diff --git a/testcases/2/logparse.conf.2 b/testcases/2/logparse.conf.2
index e346fe4..db5c56a 100644
--- a/testcases/2/logparse.conf.2
+++ b/testcases/2/logparse.conf.2
@@ -1,19 +1,19 @@
RULE {
MSG /^message repeated (.*) times/ OR /^message repeated$/
ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
# Apply {1} as {x} in the previously applied rule for HOST
ACTION MSG /^message repeated$/ count append LASTLINE
}
RULE sudo {
APP sudo
- MSG /.* : .* ; PWD=/
+# MSG /.* : .* ; PWD=/
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
ACTION MSG /(.*): \(command continued\) / IGNORE
REPORT "Sudo usage by cmd/user/host" "{2} ran {4} as {3} on {1}: {x} times" count
REPORT "Sudo usage by user/host" "{2} ran {x} sudo cmds on {1}" count
# by default {x} is total
}
#######################
#2
diff --git a/testcases/3/args b/testcases/3/args
old mode 100644
new mode 100755
index 55deb8c..a2028ef
--- a/testcases/3/args
+++ b/testcases/3/args
@@ -1 +1 @@
--l ./test.log.1,./test.log.2 -c ./logparse.conf.1,./logparse.conf.2 -d 0
+${LOGPARSE} -l ./test.log.1,./test.log.2 -c ./logparse.conf.1,./logparse.conf.2 -d 0
diff --git a/testcases/3/logparse.conf.2 b/testcases/3/logparse.conf.2
index e346fe4..db5c56a 100644
--- a/testcases/3/logparse.conf.2
+++ b/testcases/3/logparse.conf.2
@@ -1,19 +1,19 @@
RULE {
MSG /^message repeated (.*) times/ OR /^message repeated$/
ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
# Apply {1} as {x} in the previously applied rule for HOST
ACTION MSG /^message repeated$/ count append LASTLINE
}
RULE sudo {
APP sudo
- MSG /.* : .* ; PWD=/
+# MSG /.* : .* ; PWD=/
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
ACTION MSG /(.*): \(command continued\) / IGNORE
REPORT "Sudo usage by cmd/user/host" "{2} ran {4} as {3} on {1}: {x} times" count
REPORT "Sudo usage by user/host" "{2} ran {x} sudo cmds on {1}" count
# by default {x} is total
}
#######################
#2
diff --git a/testcases/5/Description b/testcases/5/Description
new file mode 100644
index 0000000..7ea94eb
--- /dev/null
+++ b/testcases/5/Description
@@ -0,0 +1 @@
+Test -m option for macro parsing of input
diff --git a/testcases/5/args b/testcases/5/args
new file mode 100755
index 0000000..53a4827
--- /dev/null
+++ b/testcases/5/args
@@ -0,0 +1,2 @@
+${LOGPARSE} -l ./test.log -c ./logparse.conf -d 0 -m '^Nov 15 07:'
+
diff --git a/testcases/5/expected.output b/testcases/5/expected.output
new file mode 100644
index 0000000..d94b318
--- /dev/null
+++ b/testcases/5/expected.output
@@ -0,0 +1,12 @@
+
+
+No match for lines:
+
+
+Summaries:
+pam_unix sessions's opened
+ 3 sessions of CRON opened on hostA for root by 0
+
+pam_unix session's closed
+ 3 sessions of CRON closed on hostA for root
+
diff --git a/testcases/5/logparse.conf b/testcases/5/logparse.conf
new file mode 100644
index 0000000..5e95549
--- /dev/null
+++ b/testcases/5/logparse.conf
@@ -0,0 +1,50 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 FULLAPP
+ FIELDS 5-2 /\[/
+ FIELD 5-1 APP default
+ FIELD 5-2 APPPID
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /\]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE pam_unix {
+# Nov 15 10:33:21 sysam sshd[25854]: pam_unix(sshd:session): session opened for user mike by (uid=0)
+# Nov 15 10:34:01 sysam sshd[25961]: pam_unix(sshd:session): session opened for user mike by (uid=0)
+# Nov 15 16:49:43 sysam sshd[25854]: pam_unix(sshd:session): session closed for user mike
+ MSG /pam_unix\((.*):session\):/
+ # opened
+ ACTION MSG /pam_unix\((.*):session\): session (.*) for user (.*) by \(uid=(.*)\)/ {HOST, APP, 1, 2, 3, 4}
+ # closed
+ ACTION MSG /pam_unix\((.*):session\): session (.*) for user (.*)/ {HOST, APP, 1, 2, 3}
+ REPORT "pam_unix sessions's opened" "{x} sessions of {2} opened on {1} for {5} by {6}" 4=opened
+ REPORT "pam_unix session's closed" "{x} sessions of {2} closed on {1} for {5}" 4=closed
+}
+
+#######################
diff --git a/testcases/5/test.log b/testcases/5/test.log
new file mode 100644
index 0000000..93b0fe2
--- /dev/null
+++ b/testcases/5/test.log
@@ -0,0 +1,20 @@
+Nov 15 06:47:10 hostA CRON[22709]: pam_unix(cron:session): session closed for user root
+Nov 15 06:47:55 hostA CRON[22387]: pam_unix(cron:session): session closed for user root
+Nov 15 06:50:01 hostA CRON[23212]: pam_unix(cron:session): session opened for user root by (uid=0)
+Nov 15 06:50:02 hostA CRON[23212]: pam_unix(cron:session): session closed for user root
+Nov 15 07:00:01 hostA CRON[23322]: pam_unix(cron:session): session opened for user root by (uid=0)
+Nov 15 07:00:01 hostA CRON[23322]: pam_unix(cron:session): session closed for user root
+Nov 15 07:09:01 hostA CRON[23401]: pam_unix(cron:session): session opened for user root by (uid=0)
+Nov 15 07:09:01 hostA CRON[23401]: pam_unix(cron:session): session closed for user root
+Nov 15 07:10:01 hostA CRON[23473]: pam_unix(cron:session): session opened for user root by (uid=0)
+Nov 15 07:10:02 hostA CRON[23473]: pam_unix(cron:session): session closed for user root
+Nov 15 10:33:21 hostA sshd[25854]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 15 10:34:01 hostA sshd[25961]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 15 16:49:43 hostA sshd[25854]: pam_unix(sshd:session): session closed for user userx
+Nov 15 16:53:03 hostA sshd[25961]: pam_unix(sshd:session): session closed for user userx
+Nov 15 18:57:50 hostA sshd[32401]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 15 21:12:48 hostA sshd[32401]: pam_unix(sshd:session): session closed for user userx
+Nov 16 03:01:27 hostA sshd[12059]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 16 03:12:55 hostA sshd[12059]: pam_unix(sshd:session): session closed for user userx
+Nov 16 03:21:54 hostA sshd[12495]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 16 03:56:08 hostA sshd[12495]: pam_unix(sshd:session): session closed for user userx
diff --git a/testcases/6/Description b/testcases/6/Description
new file mode 100644
index 0000000..7ea94eb
--- /dev/null
+++ b/testcases/6/Description
@@ -0,0 +1 @@
+Test -m option for macro parsing of input
diff --git a/testcases/6/args b/testcases/6/args
new file mode 100755
index 0000000..cf0efa8
--- /dev/null
+++ b/testcases/6/args
@@ -0,0 +1 @@
+${LOGPARSE} -l ./test.log -c ./logparse.conf -d 0 -m ""
diff --git a/testcases/6/expected.output b/testcases/6/expected.output
new file mode 100644
index 0000000..e2b8580
--- /dev/null
+++ b/testcases/6/expected.output
@@ -0,0 +1,21 @@
+
+
+No match for lines:
+ Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+ Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+
+
+Summaries:
+Sudo usage by cmd/user/host
+ userb ran /usr/bin/tail /var/log/auth.log as root on hosta: 2 times
+ usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
+ userb ran /bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog as root on hosta: 1 times
+ userb ran /bin/grep -i ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/chown usera auth.log as root on hosta: 1 times
+ userb ran /usr/bin/head /var/log/auth.log as root on hosta: 1 times
+
+Sudo usage by user/host
+ usera ran 4 sudo cmds on hosta
+ userb ran 5 sudo cmds on hosta
+
diff --git a/testcases/6/logparse.conf b/testcases/6/logparse.conf
new file mode 100644
index 0000000..5120a1f
--- /dev/null
+++ b/testcases/6/logparse.conf
@@ -0,0 +1,44 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 APP
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE sudo {
+ APP sudo
+# MSG /.* : .* ; PWD=/
+ ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
+ ACTION MSG /(.*): \(command continued\) / IGNORE
+ REPORT "Sudo usage by cmd/user/host" "{2} ran {4} as {3} on {1}: {x} times" count
+ REPORT "Sudo usage by user/host" "{2} ran {x} sudo cmds on {1}" count
+ # by default {x} is total
+}
+#######################
+#2
diff --git a/testcases/6/test.log b/testcases/6/test.log
new file mode 100644
index 0000000..7009c17
--- /dev/null
+++ b/testcases/6/test.log
@@ -0,0 +1,12 @@
+Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+Oct 2 15:01:19 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/syslog
+Oct 2 15:01:22 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/syslog
+Oct 2 15:01:25 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/messages
+Oct 2 15:01:31 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep -i ssh /var/log/messages
+Oct 2 15:01:35 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog
+Oct 2 15:01:35 hosta sudo: userb : (command continued) /var/log/syslog.1.gz /var/log/syslog.2.gz /var/log/syslog.3.gz /var/log/syslog.4.gz /var/log/syslog.5.gz /var/log/syslog.6.gz /var/log/udev /var/log/user.log /var/log/wtmp /var/log/wtmp.1
+Oct 2 15:02:17 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/head /var/log/auth.log
+Oct 2 15:02:22 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/chown usera auth.log
+Oct 2 15:02:55 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/tail /var/log/auth.log
+Oct 2 15:03:50 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/tail /var/log/auth.log
diff --git a/testcases/7/Description b/testcases/7/Description
new file mode 100644
index 0000000..1274b30
--- /dev/null
+++ b/testcases/7/Description
@@ -0,0 +1,3 @@
+Basic test case for multiple config and logfiles
+Also IGNORE in an ACTION
+Ensure that field macro parsers work correctly
diff --git a/testcases/7/args b/testcases/7/args
new file mode 100755
index 0000000..c4302af
--- /dev/null
+++ b/testcases/7/args
@@ -0,0 +1 @@
+${LOGPARSE} -l ./test.log.1 -l ./test.log.2 -c ./logparse.conf.1 -c ./logparse.conf.2 -d 0
diff --git a/testcases/7/expected.output b/testcases/7/expected.output
new file mode 100644
index 0000000..39aa064
--- /dev/null
+++ b/testcases/7/expected.output
@@ -0,0 +1,22 @@
+
+
+No match for lines:
+ Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+ Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+ Oct 2 15:01:35 hosta sudo: userb : (command continued) /var/log/syslog.1.gz /var/log/syslog.2.gz /var/log/syslog.3.gz /var/log/syslog.4.gz /var/log/syslog.5.gz /var/log/syslog.6.gz /var/log/udev /var/log/user.log /var/log/wtmp /var/log/wtmp.1
+
+
+Summaries:
+Sudo usage by cmd/user/host
+ userb ran /usr/bin/tail /var/log/auth.log as root on hosta: 2 times
+ usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
+ userb ran /bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog as root on hosta: 1 times
+ userb ran /bin/grep -i ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/chown usera auth.log as root on hosta: 1 times
+ userb ran /usr/bin/head /var/log/auth.log as root on hosta: 1 times
+
+Sudo usage by user/host
+ usera ran 4 sudo cmds on hosta
+ userb ran 5 sudo cmds on hosta
+
diff --git a/testcases/7/logparse.conf.1 b/testcases/7/logparse.conf.1
new file mode 100644
index 0000000..4da2a88
--- /dev/null
+++ b/testcases/7/logparse.conf.1
@@ -0,0 +1,26 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 APP
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+#######################
diff --git a/testcases/7/logparse.conf.2 b/testcases/7/logparse.conf.2
new file mode 100644
index 0000000..e346fe4
--- /dev/null
+++ b/testcases/7/logparse.conf.2
@@ -0,0 +1,19 @@
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE sudo {
+ APP sudo
+ MSG /.* : .* ; PWD=/
+ ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
+ ACTION MSG /(.*): \(command continued\) / IGNORE
+ REPORT "Sudo usage by cmd/user/host" "{2} ran {4} as {3} on {1}: {x} times" count
+ REPORT "Sudo usage by user/host" "{2} ran {x} sudo cmds on {1}" count
+ # by default {x} is total
+}
+#######################
+#2
diff --git a/testcases/7/test.log.1 b/testcases/7/test.log.1
new file mode 100644
index 0000000..8120f96
--- /dev/null
+++ b/testcases/7/test.log.1
@@ -0,0 +1,6 @@
+Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+Oct 2 15:01:19 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/syslog
+Oct 2 15:01:22 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/syslog
+Oct 2 15:01:25 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/messages
+Oct 2 15:01:31 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep -i ssh /var/log/messages
diff --git a/testcases/7/test.log.2 b/testcases/7/test.log.2
new file mode 100644
index 0000000..8a3df2e
--- /dev/null
+++ b/testcases/7/test.log.2
@@ -0,0 +1,6 @@
+Oct 2 15:01:35 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog
+Oct 2 15:01:35 hosta sudo: userb : (command continued) /var/log/syslog.1.gz /var/log/syslog.2.gz /var/log/syslog.3.gz /var/log/syslog.4.gz /var/log/syslog.5.gz /var/log/syslog.6.gz /var/log/udev /var/log/user.log /var/log/wtmp /var/log/wtmp.1
+Oct 2 15:02:17 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/head /var/log/auth.log
+Oct 2 15:02:22 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/chown usera auth.log
+Oct 2 15:02:55 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/tail /var/log/auth.log
+Oct 2 15:03:50 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/tail /var/log/auth.log
diff --git a/testcases/test.sh b/testcases/test.sh
index eacffcd..12c533b 100755
--- a/testcases/test.sh
+++ b/testcases/test.sh
@@ -1,24 +1,25 @@
#!/bin/bash
dir="`pwd`/`dirname $0`"
OUTFILE="/tmp/logparse.test.output"
DEFAULTARGS=" -l ./test.log -c ./logparse.conf -d 0"
+export LOGPARSE="../../logparse.pl"
cd $dir
for testcasedir in `ls -dF1 * | grep '/$'`
do
cd $dir/$testcasedir
- if [ -f ./args ] ; then
- ../../logparse.pl `cat ./args` > $OUTFILE
+ if [ -x ./args ] ; then
+ bash ./args > $OUTFILE
else
- ../../logparse.pl $DEFAULTARGS > $OUTFILE
+ ${LOGPARSE} $DEFAULTARGS > $OUTFILE
fi
diff -u $OUTFILE ./expected.output
if test $? -eq 0 ; then
echo Testcase `echo $testcasedir | sed 's/\///g'` passed
else
echo Testcase `echo $testcasedir| sed 's/\///g'` failed
fi
rm $OUTFILE
done
|
mikeknox/LogParse | 64864081347b1ebbac520c6055c19a925188b2ae | bug fix for logmsg | diff --git a/logparse.pl b/logparse.pl
index 5c4e4be..38e95ce 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -220,827 +220,827 @@ sub processlogfile {
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
logmsg(9, 1, "Checking line: $line{line}");
logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
if (keys %rules >= 0) {
logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
$execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
logmsg (9, 3, "#rules in list .., ".keys(%rules) );
logmsg (9, 3, "\%rules ..", \%rules);
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
logmsg(9 ,1, "Results hash ...", \%$reshashref );
logmsg (5, 1, "finished processing line");
}
close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ", $argsref);
logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
logmsg(9,3, "report field regex: $$argsref[3]");
($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
#$$reportref[$reportindex]{regex} = $$argsref[3];
}
if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
$$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
}
print "\n\nSummaries:\n";
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (4, 1, "Rule[rptid]: $rule\[$rptid\]");
logmsg (5, 2, "\%ruleresults ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
} else {
logmsg (4, 2, "No title");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
for my $actionid (keys( %$reshashref ) ) {
for my $key (keys %{ $$reshashref{$actionid} } ) {
(my @values) = split (/:/, $key);
logmsg (9, 5, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
if (exists($$cfghashref{reports}[$rptid]{field})) {
logmsg (9, 4, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
} else {
logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
next;
}
}
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 5, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 6, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 7, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 7, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
}
$targetkeymatch =~ s/^://;
logmsg (9, 5, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ", $cfghashref);
logmsg (7, 3, "reshash ... ", $reshashref);
my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
- logmsg (9, 4, "$fields[$field] = $fields[$i]");
+ logmsg (9, 4, "Settting \$fields[$field] ($fields[$field]) = \$fields[$i] ($fields[$i])");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
$line.="\n";
#if (exists($$cfghashref{field})) {
#logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
#if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
#logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
#$line = "";
#}
#}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
}
}
if ($numericonly) {
return @tmpmatrix;
} else {
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0;
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
} else {
logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count/i) {
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/sum/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..", \@matrix);
logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
for my $rule (keys %{ $cfghashref } ) {
$rules{$rule} = $rule if matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref);
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1;
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
foreach my $field (keys (%{ $cfghashref } ) ) {
if ($$cfghashref{fields}{$field} =~ /^!/) {
my $exp = $$cfghashref{fields}{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{fields}{$field}/);
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
my $dumpvar = shift;
my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
# TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
- print STDERR whowasi."(): $time: ";
+ print STDERR whowasi."(): $time: $msg";
if ($dumpvar) {
print STDERR Dumper($dumpvar);
}
print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
print "WARNING: $msg\n";
} elsif (/e|error/i) {
print "ERROR: $msg\n";
} elsif (/c|critical/i) {
print "CRITICAL error, aborted ... $msg\n";
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
|
mikeknox/LogParse | 7c9cb9c86af642f8a772f78bf2b20dcf750013b6 | Added filtering option to reports so reports. This is implemented in the summarise function, so if the field in the report line doesn't match the regex it's data isn't included in the summary. | diff --git a/logparse.pl b/logparse.pl
index f1f634c..23ea135 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1004 +1,1042 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Long;
use Data::Dumper qw(Dumper);
# Globals
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my @CONFIGFILES;# = ("logparse.conf");
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
#my $SYSLOGFILE = "/var/log/messages";
my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
#getopt('cdl', \%opts);
my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
"l|log=s" => \@LOGFILES,
"d|debug=i" => \$DEBUG
);
@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
@LOGFILES = split(/,/,join(',',@LOGFILES));
unless ($result) {
warning ("c", "Invalid config options passed");
}
#$DEBUG = $opts{d} if $opts{d};
#$CONFIGFILE = $opts{c} if $opts{c};
#$SYSLOGFILE = $opts{l} if $opts{l};
loadcfg (\%cfghash, \@CONFIGFILES);
-logmsg(7, 3, "cfghash:".Dumper(\%cfghash));
+logmsg(7, 3, "cfghash:", \%cfghash);
processlogfile(\%cfghash, \%reshash, \@LOGFILES);
-logmsg (9, 0, "reshash ..\n".Dumper(%reshash));
+logmsg (9, 0, "reshash ..\n", %reshash);
report(\%cfghash, \%reshash);
-logmsg (9, 0, "reshash ..\n".Dumper(%reshash));
-logmsg (9, 0, "cfghash ..\n".Dumper(%cfghash));
+logmsg (9, 0, "reshash ..\n", %reshash);
+logmsg (9, 0, "cfghash ..\n", %cfghash);
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text doesnot contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
- logmsg (9, 4, "Got field values ... ".Dumper(@tmp));
+ logmsg (9, 4, "Got field values ... ", \@tmp);
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
- logmsg (9, 4, "line results now ...".Dumper($linehashref));
+ logmsg (9, 4, "line results now ...", $linehashref);
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
- logmsg(5, 1, "Processing logfiles: ".Dumper($logfileref));
+ logmsg(5, 1, "Processing logfiles: ", $logfileref);
foreach my $logfile (@$logfileref) {
logmsg(1, 0, "processing $logfile using format $format...");
- open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
- while (<LOGFILE>) {
- my $facility = "";
- my %line;
- # Placing line and line componenents into a hash to be passed to actrule, components can then be refered
- # to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
- $line{line} = $_;
-
- logmsg(5, 1, "Processing next line");
- logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
- logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
-
- parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
+
+ open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
+ while (<LOGFILE>) {
+ my $facility = "";
+ my %line;
+ # Placing line and line componenents into a hash to be passed to actrule, components can then be refered
+ # to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
+ $line{line} = $_;
+
+ logmsg(5, 1, "Processing next line");
+ logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
+ logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
+
+ parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
- logmsg(9, 1, "Checking line: $line{line}");
- logmsg(9, 2, "Extracted Field contents ...\n".Dumper(@{$line{fields}}));
+ logmsg(9, 1, "Checking line: $line{line}");
+ logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
- my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
- logmsg(9, 2, keys (%rules)." matches so far");
-
-#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
-#UP to here
- # FORMAT stanza contains a substanza which describes repeat for the given format
- # format{repeat}{cmd} - normally regex, not sure what other solutions would apply
- # format{repeat}{regex} - array of regex's hashes
- # format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
+ my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
+ logmsg(9, 2, keys (%rules)." matches so far");
+
+ #TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
+ #UP to here
+ # FORMAT stanza contains a substanza which describes repeat for the given format
+ # format{repeat}{cmd} - normally regex, not sure what other solutions would apply
+ # format{repeat}{regex} - array of regex's hashes
+ # format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
- #TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
- # Detect and count repeats
- if (keys %rules >= 0) {
- logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
-
- # loop through matching rules and collect data as defined in the ACTIONS section of %config
- my $actrule = 0;
- my %tmprules = %rules;
- for my $rule (keys %tmprules) {
- logmsg (9, 3, "checking rule: $rule");
- my $execruleret = 0;
- if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
- $execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
- } else {
- logmsg (2, 3, "No actions defined for rule; $rule");
- }
- logmsg (9, 4, "execrule returning $execruleret");
- delete $rules{$rule} unless $execruleret;
- # TODO: update &actionrule();
- }
- logmsg (9, 3, "#rules in list .., ".keys(%rules) );
- logmsg (9, 3, "\%rules ..".Dumper(%rules));
- $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
- # lastline & repeat
- } # rules > 0
- if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
- delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
- }
- $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
+ #TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
+ # Detect and count repeats
+ if (keys %rules >= 0) {
+ logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
+
+ # loop through matching rules and collect data as defined in the ACTIONS section of %config
+ my $actrule = 0;
+ my %tmprules = %rules;
+ for my $rule (keys %tmprules) {
+ logmsg (9, 3, "checking rule: $rule");
+ my $execruleret = 0;
+ if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
+ $execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
+ } else {
+ logmsg (2, 3, "No actions defined for rule; $rule");
+ }
+ logmsg (9, 4, "execrule returning $execruleret");
+ delete $rules{$rule} unless $execruleret;
+ # TODO: update &actionrule();
+ }
+ logmsg (9, 3, "#rules in list .., ".keys(%rules) );
+ logmsg (9, 3, "\%rules ..", \%rules);
+ $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
+ # lastline & repeat
+ } # rules > 0
+ if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
+ delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
+ }
+ $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
- if ( keys(%rules) == 0) {
- # Add new unmatched linescode
+ if ( keys(%rules) == 0) {
+ # Add new unmatched linescode
+ }
+ logmsg(9 ,1, "Results hash ...", \%$reshashref );
+ logmsg (5, 1, "finished processing line");
}
- logmsg(9 ,1, "Results hash ...".Dumper(%$reshashref) );
- logmsg (5, 1, "finished processing line");
- }
close LOGFILE;
- logmsg (1, 0, "Finished processing $logfile.");
+ logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
+=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
-=cut
+#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
+=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
- logmsg (5, 1, "Config Hash contents: ...".Dumper($cfghashref));
+ logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
- logmsg (6, 5, "args passed: ".Dumper(@$argsref));
- logmsg (6, 5, "Actions so far .. ".Dumper($actionref));
+ logmsg (6, 5, "args passed: ", $argsref);
+ logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
- logmsg(5, 5, "action[$actionindex] for rule is now .. ".Dumper(%{ $$actionref[$actionindex] } ) );
+ logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
- logmsg (6, 5, "args: ".Dumper(@$argsref));
+ logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
- if ($$argsref[3]) {
- $$reportref[$reportindex]{cmd} = $$argsref[3];
+
+ if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
+ logmsg(9,3, "report field regex: $$argsref[3]");
+ ($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
+ #$$reportref[$reportindex]{regex} = $$argsref[3];
+ }
+
+ if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
+ $$reportref[$reportindex]{cmd} = $$argsref[3];
+ } elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
+ $$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
- logmsg (6, 5, "args: ".Dumper(@$argsref));
+ logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
- logmsg (6, 5, "args: ".Dumper(@$argsref));
+ logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
- logmsg(5, 1, "Dump of results hash ...".Dumper($reshashref));
+ logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
}
print "\n\nSummaries:\n";
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (4, 1, "Rule[rptid]: $rule\[$rptid\]");
- logmsg (5, 2, "\%ruleresults ... ".Dumper(%ruleresults));
+ logmsg (5, 2, "\%ruleresults ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
} else {
logmsg (4, 2, "No title");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
- print "\t".rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key)."\n";
+ print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
for my $actionid (keys( %$reshashref ) ) {
for my $key (keys %{ $$reshashref{$actionid} } ) {
(my @values) = split (/:/, $key);
- logmsg (9, 5, "values from key($key) ... @values");
+ logmsg (9, 5, "values from key($key) ... @values");
+
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
+ if (exists($$cfghashref{reports}[$rptid]{field})) {
+ logmsg (9, 4, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
+ if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
+ logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
+ } else {
+ logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
+ next;
+ }
+ }
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
- logmsg (9, 5, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ".Dumper(@targetfieldids));
+ logmsg (9, 5, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 6, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 7, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
- logmsg(9, 7, "fieldid: $fieldid doesn't in @targetfieldids, adding wildcard to \$targetkeymatch");
+ logmsg(9, 7, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
}
$targetkeymatch =~ s/^://;
logmsg (9, 5, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
- logmsg (7, 3, "cfghash ... ".Dumper($cfghashref));
- logmsg (7, 3, "reshash ... ".Dumper($reshashref));
- my $line = $$cfghashref{line};
+ logmsg (7, 3, "cfghash ... ", $cfghashref);
+ logmsg (7, 3, "reshash ... ", $reshashref);
+ my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "$fields[$field] = $fields[$i]");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
+
+ $line.="\n";
+
+ #if (exists($$cfghashref{field})) {
+ #logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
+ #if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
+ #logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
+ #$line = "";
+ #}
+ #}
+
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
}
}
if ($numericonly) {
return @tmpmatrix;
} else {
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
- logmsg (9, 6, "rule spec: ".Dumper($cfghashref));
+ logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0;
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
} else {
logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count/i) {
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/sum/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
- logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ".Dumper($cfghashref));
+ logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
- logmsg (9, 3, "cfghashref .. ".Dumper(@$cfghashref));
+ logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
- logmsg (7, 2, "After checking all actions for this rule; \%reshash ...".Dumper($reshashref));
+ logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
- logmsg (9, 5, "\@resmatrix ... ".Dumper($resmatrixref) );
+ logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
- logmsg (9, 6, "\@matrix ..".Dumper(@matrix));
- logmsg (9, 6, "\@tmpmatrix ..".Dumper(@tmpmatrix));
+ logmsg (9, 6, "\@matrix ..", \@matrix);
+ logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
for my $rule (keys %{ $cfghashref } ) {
$rules{$rule} = $rule if matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref);
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1;
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
foreach my $field (keys (%{ $cfghashref } ) ) {
if ($$cfghashref{fields}{$field} =~ /^!/) {
my $exp = $$cfghashref{fields}{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{fields}{$field}/);
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
+ my $dumpvar = shift;
if ($DEBUG >= $level) {
for my $i (0..$indent) {
print STDERR " ";
}
- print STDERR whowasi."(): $msg\n";
+ print STDERR whowasi."(): $msg";
+ if ($dumpvar) {
+ print STDERR Dumper($dumpvar);
+ }
+ print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
print "WARNING: $msg\n";
} elsif (/e|error/i) {
print "ERROR: $msg\n";
} elsif (/c|critical/i) {
print "CRITICAL error, aborted ... $msg\n";
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
|
mikeknox/LogParse | 392a2c74d13e1f846643026b67268b48cf3b4188 | Added filtering option to reports so reports. This is implemented in the summarise function, so if the field in the report line doesn't match the regex it's data isn't included in the summary. | diff --git a/logparse.pl b/logparse.pl
index f1f634c..23ea135 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1004 +1,1042 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Long;
use Data::Dumper qw(Dumper);
# Globals
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my @CONFIGFILES;# = ("logparse.conf");
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
#my $SYSLOGFILE = "/var/log/messages";
my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
#getopt('cdl', \%opts);
my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
"l|log=s" => \@LOGFILES,
"d|debug=i" => \$DEBUG
);
@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
@LOGFILES = split(/,/,join(',',@LOGFILES));
unless ($result) {
warning ("c", "Invalid config options passed");
}
#$DEBUG = $opts{d} if $opts{d};
#$CONFIGFILE = $opts{c} if $opts{c};
#$SYSLOGFILE = $opts{l} if $opts{l};
loadcfg (\%cfghash, \@CONFIGFILES);
-logmsg(7, 3, "cfghash:".Dumper(\%cfghash));
+logmsg(7, 3, "cfghash:", \%cfghash);
processlogfile(\%cfghash, \%reshash, \@LOGFILES);
-logmsg (9, 0, "reshash ..\n".Dumper(%reshash));
+logmsg (9, 0, "reshash ..\n", %reshash);
report(\%cfghash, \%reshash);
-logmsg (9, 0, "reshash ..\n".Dumper(%reshash));
-logmsg (9, 0, "cfghash ..\n".Dumper(%cfghash));
+logmsg (9, 0, "reshash ..\n", %reshash);
+logmsg (9, 0, "cfghash ..\n", %cfghash);
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text doesnot contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
- logmsg (9, 4, "Got field values ... ".Dumper(@tmp));
+ logmsg (9, 4, "Got field values ... ", \@tmp);
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
- logmsg (9, 4, "line results now ...".Dumper($linehashref));
+ logmsg (9, 4, "line results now ...", $linehashref);
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(5, 1, " and I was called by ... ".&whowasi);
- logmsg(5, 1, "Processing logfiles: ".Dumper($logfileref));
+ logmsg(5, 1, "Processing logfiles: ", $logfileref);
foreach my $logfile (@$logfileref) {
logmsg(1, 0, "processing $logfile using format $format...");
- open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
- while (<LOGFILE>) {
- my $facility = "";
- my %line;
- # Placing line and line componenents into a hash to be passed to actrule, components can then be refered
- # to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
- $line{line} = $_;
-
- logmsg(5, 1, "Processing next line");
- logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
- logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
-
- parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
+
+ open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
+ while (<LOGFILE>) {
+ my $facility = "";
+ my %line;
+ # Placing line and line componenents into a hash to be passed to actrule, components can then be refered
+ # to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
+ $line{line} = $_;
+
+ logmsg(5, 1, "Processing next line");
+ logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
+ logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
+
+ parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
- logmsg(9, 1, "Checking line: $line{line}");
- logmsg(9, 2, "Extracted Field contents ...\n".Dumper(@{$line{fields}}));
+ logmsg(9, 1, "Checking line: $line{line}");
+ logmsg(9, 2, "Extracted Field contents ...\n", \@{$line{fields}});
- my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
- logmsg(9, 2, keys (%rules)." matches so far");
-
-#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
-#UP to here
- # FORMAT stanza contains a substanza which describes repeat for the given format
- # format{repeat}{cmd} - normally regex, not sure what other solutions would apply
- # format{repeat}{regex} - array of regex's hashes
- # format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
+ my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
+ logmsg(9, 2, keys (%rules)." matches so far");
+
+ #TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
+ #UP to here
+ # FORMAT stanza contains a substanza which describes repeat for the given format
+ # format{repeat}{cmd} - normally regex, not sure what other solutions would apply
+ # format{repeat}{regex} - array of regex's hashes
+ # format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
- #TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
- # Detect and count repeats
- if (keys %rules >= 0) {
- logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
-
- # loop through matching rules and collect data as defined in the ACTIONS section of %config
- my $actrule = 0;
- my %tmprules = %rules;
- for my $rule (keys %tmprules) {
- logmsg (9, 3, "checking rule: $rule");
- my $execruleret = 0;
- if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
- $execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
- } else {
- logmsg (2, 3, "No actions defined for rule; $rule");
- }
- logmsg (9, 4, "execrule returning $execruleret");
- delete $rules{$rule} unless $execruleret;
- # TODO: update &actionrule();
- }
- logmsg (9, 3, "#rules in list .., ".keys(%rules) );
- logmsg (9, 3, "\%rules ..".Dumper(%rules));
- $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
- # lastline & repeat
- } # rules > 0
- if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
- delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
- }
- $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
+ #TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
+ # Detect and count repeats
+ if (keys %rules >= 0) {
+ logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
+
+ # loop through matching rules and collect data as defined in the ACTIONS section of %config
+ my $actrule = 0;
+ my %tmprules = %rules;
+ for my $rule (keys %tmprules) {
+ logmsg (9, 3, "checking rule: $rule");
+ my $execruleret = 0;
+ if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
+ $execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
+ } else {
+ logmsg (2, 3, "No actions defined for rule; $rule");
+ }
+ logmsg (9, 4, "execrule returning $execruleret");
+ delete $rules{$rule} unless $execruleret;
+ # TODO: update &actionrule();
+ }
+ logmsg (9, 3, "#rules in list .., ".keys(%rules) );
+ logmsg (9, 3, "\%rules ..", \%rules);
+ $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
+ # lastline & repeat
+ } # rules > 0
+ if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
+ delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
+ }
+ $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
- if ( keys(%rules) == 0) {
- # Add new unmatched linescode
+ if ( keys(%rules) == 0) {
+ # Add new unmatched linescode
+ }
+ logmsg(9 ,1, "Results hash ...", \%$reshashref );
+ logmsg (5, 1, "finished processing line");
}
- logmsg(9 ,1, "Results hash ...".Dumper(%$reshashref) );
- logmsg (5, 1, "finished processing line");
- }
close LOGFILE;
- logmsg (1, 0, "Finished processing $logfile.");
+ logmsg (1, 0, "Finished processing $logfile.");
} # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
+=depricate
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
-=cut
+#=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
+=cut
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfileref = shift;
foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (1, 0, "finished processing cfg: $cfgfile");
}
- logmsg (5, 1, "Config Hash contents: ...".Dumper($cfghashref));
+ logmsg (5, 1, "Config Hash contents: ...", $cfghashref);
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
- logmsg (6, 5, "args passed: ".Dumper(@$argsref));
- logmsg (6, 5, "Actions so far .. ".Dumper($actionref));
+ logmsg (6, 5, "args passed: ", $argsref);
+ logmsg (6, 5, "Actions so far .. ", $actionref);
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
- logmsg(5, 5, "action[$actionindex] for rule is now .. ".Dumper(%{ $$actionref[$actionindex] } ) );
+ logmsg(5, 5, "action[$actionindex] for rule is now .. ", \%{ $$actionref[$actionindex] } );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
- logmsg (6, 5, "args: ".Dumper(@$argsref));
+ logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
- if ($$argsref[3]) {
- $$reportref[$reportindex]{cmd} = $$argsref[3];
+
+ if ($$argsref[3] and $$argsref[3] =~ /^\/|\d+/) {
+ logmsg(9,3, "report field regex: $$argsref[3]");
+ ($$reportref[$reportindex]{field}, $$reportref[$reportindex]{regex} ) = split (/=/, $$argsref[3], 2);
+ #$$reportref[$reportindex]{regex} = $$argsref[3];
+ }
+
+ if ($$argsref[3] and $$argsref[3] !~ /^\/|\d+/) {
+ $$reportref[$reportindex]{cmd} = $$argsref[3];
+ } elsif ($$argsref[4] and $$argsref[4] !~ /^\/|\d+/) {
+ $$reportref[$reportindex]{cmd} = $$argsref[4];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
- logmsg (6, 5, "args: ".Dumper(@$argsref));
+ logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
- logmsg (6, 5, "args: ".Dumper(@$argsref));
+ logmsg (6, 5, "args: ", $argsref);
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
- logmsg(5, 1, "Dump of results hash ...".Dumper($reshashref));
+ logmsg(5, 1, "Dump of results hash ...", $reshashref);
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
}
print "\n\nSummaries:\n";
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (4, 1, "Rule[rptid]: $rule\[$rptid\]");
- logmsg (5, 2, "\%ruleresults ... ".Dumper(%ruleresults));
+ logmsg (5, 2, "\%ruleresults ... ", \%ruleresults);
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
} else {
logmsg (4, 2, "No title");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
- print "\t".rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key)."\n";
+ print rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key);
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
for my $actionid (keys( %$reshashref ) ) {
for my $key (keys %{ $$reshashref{$actionid} } ) {
(my @values) = split (/:/, $key);
- logmsg (9, 5, "values from key($key) ... @values");
+ logmsg (9, 5, "values from key($key) ... @values");
+
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
+ if (exists($$cfghashref{reports}[$rptid]{field})) {
+ logmsg (9, 4, "Checking to see if field($$cfghashref{reports}[$rptid]{field}) in the results matches $$cfghashref{reports}[$rptid]{regex}");
+ if ($values[$$cfghashref{reports}[$rptid]{field} - 1] =~ /$$cfghashref{reports}[$rptid]{regex}/) {
+ logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." is a match.");
+ } else {
+ logmsg(9, 5, $values[$$cfghashref{reports}[$rptid]{field} - 1]." isn't a match.");
+ next;
+ }
+ }
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
- logmsg (9, 5, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ".Dumper(@targetfieldids));
+ logmsg (9, 5, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ", \@targetfieldids);
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 6, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 7, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
- logmsg(9, 7, "fieldid: $fieldid doesn't in @targetfieldids, adding wildcard to \$targetkeymatch");
+ logmsg(9, 7, "fieldid: $fieldid wasn't listed in @targetfieldids, adding wildcard to \$targetkeymatch");
}
}
$targetkeymatch =~ s/^://;
logmsg (9, 5, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
- logmsg (7, 3, "cfghash ... ".Dumper($cfghashref));
- logmsg (7, 3, "reshash ... ".Dumper($reshashref));
- my $line = $$cfghashref{line};
+ logmsg (7, 3, "cfghash ... ", $cfghashref);
+ logmsg (7, 3, "reshash ... ", $reshashref);
+ my $line = "\t".$$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "$fields[$field] = $fields[$i]");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
+
+ $line.="\n";
+
+ #if (exists($$cfghashref{field})) {
+ #logmsg (9, 4, "Checking to see if field($$cfghashref{field}) in the results matches $$cfghashref{regex}");
+ #if ($fields[$$cfghashref{field} - 1] =~ /$$cfghashref{regex}/) {
+ #logmsg(9, 5, $fields[$$cfghashref{field} - 1]." is a match.");
+ #$line = "";
+ #}
+ #}
+
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
}
}
if ($numericonly) {
return @tmpmatrix;
} else {
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
- logmsg (9, 6, "rule spec: ".Dumper($cfghashref));
+ logmsg (9, 6, "rule spec: ", $cfghashref);
my $retval = 0;
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
} else {
logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count/i) {
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/sum/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
- logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ".Dumper($cfghashref));
+ logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ", $cfghashref);
}
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
- logmsg (9, 3, "cfghashref .. ".Dumper(@$cfghashref));
+ logmsg (9, 3, "cfghashref .. ", $cfghashref);
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
- logmsg (7, 2, "After checking all actions for this rule; \%reshash ...".Dumper($reshashref));
+ logmsg (7, 2, "After checking all actions for this rule; \%reshash ...", $reshashref);
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
- logmsg (9, 5, "\@resmatrix ... ".Dumper($resmatrixref) );
+ logmsg (9, 5, "\@resmatrix ... ", $resmatrixref) ;
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
- logmsg (9, 6, "\@matrix ..".Dumper(@matrix));
- logmsg (9, 6, "\@tmpmatrix ..".Dumper(@tmpmatrix));
+ logmsg (9, 6, "\@matrix ..", \@matrix);
+ logmsg (9, 6, "\@tmpmatrix ..", \@tmpmatrix);
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
for my $rule (keys %{ $cfghashref } ) {
$rules{$rule} = $rule if matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref);
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1;
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
foreach my $field (keys (%{ $cfghashref } ) ) {
if ($$cfghashref{fields}{$field} =~ /^!/) {
my $exp = $$cfghashref{fields}{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{fields}{$field}/);
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
+ my $dumpvar = shift;
if ($DEBUG >= $level) {
for my $i (0..$indent) {
print STDERR " ";
}
- print STDERR whowasi."(): $msg\n";
+ print STDERR whowasi."(): $msg";
+ if ($dumpvar) {
+ print STDERR Dumper($dumpvar);
+ }
+ print STDERR "\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
print "WARNING: $msg\n";
} elsif (/e|error/i) {
print "ERROR: $msg\n";
} elsif (/c|critical/i) {
print "CRITICAL error, aborted ... $msg\n";
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
|
mikeknox/LogParse | 93d7df5866412cac43ab8a6cda1b3a409a4f50e2 | Added filtering option to reports so reports. This is implemented in the summarise function, so if the field in the report line doesn't match the regex it's data isn't included in the summary. | diff --git a/testcases/4/Description b/testcases/4/Description
new file mode 100644
index 0000000..731ac58
--- /dev/null
+++ b/testcases/4/Description
@@ -0,0 +1 @@
+Test applying conditionals to fields in data lines for reports
diff --git a/testcases/4/expected.output b/testcases/4/expected.output
new file mode 100644
index 0000000..6092b81
--- /dev/null
+++ b/testcases/4/expected.output
@@ -0,0 +1,14 @@
+
+
+No match for lines:
+
+
+Summaries:
+pam_unix sessions's opened
+ 4 sessions of CRON opened on hostA for root by 0
+ 5 sessions of sshd opened on hostA for userx by 0
+
+pam_unix session's closed
+ 5 sessions of sshd closed on hostA for userx
+ 6 sessions of CRON closed on hostA for root
+
diff --git a/testcases/4/logparse.conf b/testcases/4/logparse.conf
new file mode 100644
index 0000000..5e95549
--- /dev/null
+++ b/testcases/4/logparse.conf
@@ -0,0 +1,50 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 FULLAPP
+ FIELDS 5-2 /\[/
+ FIELD 5-1 APP default
+ FIELD 5-2 APPPID
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /\]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE pam_unix {
+# Nov 15 10:33:21 sysam sshd[25854]: pam_unix(sshd:session): session opened for user mike by (uid=0)
+# Nov 15 10:34:01 sysam sshd[25961]: pam_unix(sshd:session): session opened for user mike by (uid=0)
+# Nov 15 16:49:43 sysam sshd[25854]: pam_unix(sshd:session): session closed for user mike
+ MSG /pam_unix\((.*):session\):/
+ # opened
+ ACTION MSG /pam_unix\((.*):session\): session (.*) for user (.*) by \(uid=(.*)\)/ {HOST, APP, 1, 2, 3, 4}
+ # closed
+ ACTION MSG /pam_unix\((.*):session\): session (.*) for user (.*)/ {HOST, APP, 1, 2, 3}
+ REPORT "pam_unix sessions's opened" "{x} sessions of {2} opened on {1} for {5} by {6}" 4=opened
+ REPORT "pam_unix session's closed" "{x} sessions of {2} closed on {1} for {5}" 4=closed
+}
+
+#######################
diff --git a/testcases/4/test.log b/testcases/4/test.log
new file mode 100644
index 0000000..93b0fe2
--- /dev/null
+++ b/testcases/4/test.log
@@ -0,0 +1,20 @@
+Nov 15 06:47:10 hostA CRON[22709]: pam_unix(cron:session): session closed for user root
+Nov 15 06:47:55 hostA CRON[22387]: pam_unix(cron:session): session closed for user root
+Nov 15 06:50:01 hostA CRON[23212]: pam_unix(cron:session): session opened for user root by (uid=0)
+Nov 15 06:50:02 hostA CRON[23212]: pam_unix(cron:session): session closed for user root
+Nov 15 07:00:01 hostA CRON[23322]: pam_unix(cron:session): session opened for user root by (uid=0)
+Nov 15 07:00:01 hostA CRON[23322]: pam_unix(cron:session): session closed for user root
+Nov 15 07:09:01 hostA CRON[23401]: pam_unix(cron:session): session opened for user root by (uid=0)
+Nov 15 07:09:01 hostA CRON[23401]: pam_unix(cron:session): session closed for user root
+Nov 15 07:10:01 hostA CRON[23473]: pam_unix(cron:session): session opened for user root by (uid=0)
+Nov 15 07:10:02 hostA CRON[23473]: pam_unix(cron:session): session closed for user root
+Nov 15 10:33:21 hostA sshd[25854]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 15 10:34:01 hostA sshd[25961]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 15 16:49:43 hostA sshd[25854]: pam_unix(sshd:session): session closed for user userx
+Nov 15 16:53:03 hostA sshd[25961]: pam_unix(sshd:session): session closed for user userx
+Nov 15 18:57:50 hostA sshd[32401]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 15 21:12:48 hostA sshd[32401]: pam_unix(sshd:session): session closed for user userx
+Nov 16 03:01:27 hostA sshd[12059]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 16 03:12:55 hostA sshd[12059]: pam_unix(sshd:session): session closed for user userx
+Nov 16 03:21:54 hostA sshd[12495]: pam_unix(sshd:session): session opened for user userx by (uid=0)
+Nov 16 03:56:08 hostA sshd[12495]: pam_unix(sshd:session): session closed for user userx
|
mikeknox/LogParse | 849e2449ba8d33d036cb7801fa35b5fb56407b79 | Delta for debug msgs | diff --git a/logparse.pl b/logparse.pl
index e8cd963..773c85d 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,989 +1,993 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Std;
use Data::Dumper qw(Dumper);
# Globals
+#
+my $STARTTIME = time();
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my $CONFIGFILE="logparse.conf";
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
my $SYSLOGFILE = "/var/log/messages";
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
getopt('cdl', \%opts);
$DEBUG = $opts{d} if $opts{d};
$CONFIGFILE = $opts{c} if $opts{c};
$SYSLOGFILE = $opts{l} if $opts{l};
loadcfg (\%cfghash, $CONFIGFILE);
logmsg(7, 3, "cfghash:".Dumper(\%cfghash));
processlogfile(\%cfghash, \%reshash, $SYSLOGFILE);
logmsg (9, 0, "reshash ..\n".Dumper(%reshash));
report(\%cfghash, \%reshash);
logmsg (9, 0, "reshash ..\n".Dumper(%reshash));
logmsg (9, 0, "cfghash ..\n".Dumper(%cfghash));
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text doesnot contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ".Dumper(@tmp));
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
logmsg (9, 4, "line results now ...".Dumper($linehashref));
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfile = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(1, 0, "processing $logfile using format $format...");
logmsg(5, 1, " and I was called by ... ".&whowasi);
open (LOGFILE, "<$logfile") or die "Unable to open $SYSLOGFILE for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
logmsg(9, 1, "Checking line: $line{line}");
logmsg(9, 2, "Extracted Field contents ...\n".Dumper(@{$line{fields}}));
my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
if (keys %rules >= 0) {
logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
$execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
logmsg (9, 3, "#rules in list .., ".keys(%rules) );
logmsg (9, 3, "\%rules ..".Dumper(%rules));
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
logmsg(9 ,1, "Results hash ...".Dumper(%$reshashref) );
logmsg (5, 1, "finished processing line");
}
logmsg (1, 0, "Finished processing $logfile.");
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfile = shift;
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (5, 1, "Config Hash contents:");
&Dumper( %$cfghashref );
logmsg (1, 0, "finished processing cfg: $cfgfile");
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ".Dumper(@$argsref));
logmsg (6, 5, "Actions so far .. ".Dumper($actionref));
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ".Dumper(%{ $$actionref[$actionindex] } ) );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3]) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...".Dumper($reshashref));
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
}
print "\n\nSummaries:\n";
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (4, 1, "Rule[rptid]: $rule\[$rptid\]");
logmsg (5, 2, "\%ruleresults ... ".Dumper(%ruleresults));
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
} else {
logmsg (4, 2, "No title");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
print "\t".rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key)."\n";
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
for my $actionid (keys( %$reshashref ) ) {
for my $key (keys %{ $$reshashref{$actionid} } ) {
(my @values) = split (/:/, $key);
logmsg (9, 5, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 5, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ".Dumper(@targetfieldids));
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 6, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 7, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 7, "fieldid: $fieldid doesn't in @targetfieldids, adding wildcard to \$targetkeymatch");
}
}
$targetkeymatch =~ s/^://;
logmsg (9, 5, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ".Dumper($cfghashref));
logmsg (7, 3, "reshash ... ".Dumper($reshashref));
my $line = $$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "$fields[$field] = $fields[$i]");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
}
}
if ($numericonly) {
return @tmpmatrix;
} else {
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ".Dumper($cfghashref));
my $retval = 0;
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
} else {
logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count/i) {
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/sum/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ".Dumper($cfghashref));
}
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ".Dumper(@$cfghashref));
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...".Dumper($reshashref));
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ".Dumper($resmatrixref) );
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..".Dumper(@matrix));
logmsg (9, 6, "\@tmpmatrix ..".Dumper(@tmpmatrix));
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
for my $rule (keys %{ $cfghashref } ) {
$rules{$rule} = $rule if matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref);
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1;
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
foreach my $field (keys (%{ $cfghashref } ) ) {
if ($$cfghashref{fields}{$field} =~ /^!/) {
my $exp = $$cfghashref{fields}{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{fields}{$field}/);
}
}
return $ret;
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
+ my $time = time() - $STARTTIME;
if ($DEBUG >= $level) {
+ # TODO replace this with a regex so \n can also be matched and multi line (ie Dumper) can be correctly formatted
for my $i (0..$indent) {
print STDERR " ";
}
- print STDERR whowasi."(): $msg\n";
+ print STDERR whowasi."(): $time: $msg\n";
}
}
sub warning {
my $level = shift;
my $msg = shift;
for ($level) {
if (/w|warning/i) {
print "WARNING: $msg\n";
} elsif (/e|error/i) {
print "ERROR: $msg\n";
} elsif (/c|critical/i) {
print "CRITICAL error, aborted ... $msg\n";
exit 1;
} else {
warning("warning", "No warning message level set");
}
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
|
mikeknox/LogParse | e43edf095bd6e437d1a1440b0375cf799ac1f5ff | Minor fix to test.sh fix paths | diff --git a/testcases/test.sh b/testcases/test.sh
index 5e6de3c..eacffcd 100755
--- a/testcases/test.sh
+++ b/testcases/test.sh
@@ -1,24 +1,24 @@
#!/bin/bash
dir="`pwd`/`dirname $0`"
OUTFILE="/tmp/logparse.test.output"
DEFAULTARGS=" -l ./test.log -c ./logparse.conf -d 0"
cd $dir
for testcasedir in `ls -dF1 * | grep '/$'`
do
cd $dir/$testcasedir
if [ -f ./args ] ; then
- $1 `cat ./args` > $OUTFILE
+ ../../logparse.pl `cat ./args` > $OUTFILE
else
- $1 $DEFAULTARGS > $OUTFILE
+ ../../logparse.pl $DEFAULTARGS > $OUTFILE
fi
diff -u $OUTFILE ./expected.output
if test $? -eq 0 ; then
echo Testcase `echo $testcasedir | sed 's/\///g'` passed
else
echo Testcase `echo $testcasedir| sed 's/\///g'` failed
fi
rm $OUTFILE
done
|
mikeknox/LogParse | c4fd2f56d40f026b103fd83ac5a08bf420f5b4f0 | Ability to use multiple config and/or logfiles Tweaks to test harness to support different args if necessary | diff --git a/logparse.pl b/logparse.pl
index e8cd963..f1f634c 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,912 +1,927 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
-use Getopt::Std;
+use Getopt::Long;
use Data::Dumper qw(Dumper);
# Globals
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
-my $CONFIGFILE="logparse.conf";
+my @CONFIGFILES;# = ("logparse.conf");
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
-my $SYSLOGFILE = "/var/log/messages";
+#my $SYSLOGFILE = "/var/log/messages";
+my @LOGFILES;
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
-getopt('cdl', \%opts);
-$DEBUG = $opts{d} if $opts{d};
-$CONFIGFILE = $opts{c} if $opts{c};
-$SYSLOGFILE = $opts{l} if $opts{l};
+#getopt('cdl', \%opts);
+my $result = GetOptions("c|conf=s" => \@CONFIGFILES,
+ "l|log=s" => \@LOGFILES,
+ "d|debug=i" => \$DEBUG
+ );
+@CONFIGFILES = split(/,/,join(',',@CONFIGFILES));
+@LOGFILES = split(/,/,join(',',@LOGFILES));
+unless ($result) {
+ warning ("c", "Invalid config options passed");
+}
+#$DEBUG = $opts{d} if $opts{d};
+#$CONFIGFILE = $opts{c} if $opts{c};
+#$SYSLOGFILE = $opts{l} if $opts{l};
-loadcfg (\%cfghash, $CONFIGFILE);
+loadcfg (\%cfghash, \@CONFIGFILES);
logmsg(7, 3, "cfghash:".Dumper(\%cfghash));
-processlogfile(\%cfghash, \%reshash, $SYSLOGFILE);
+processlogfile(\%cfghash, \%reshash, \@LOGFILES);
logmsg (9, 0, "reshash ..\n".Dumper(%reshash));
report(\%cfghash, \%reshash);
logmsg (9, 0, "reshash ..\n".Dumper(%reshash));
logmsg (9, 0, "cfghash ..\n".Dumper(%cfghash));
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text doesnot contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ".Dumper(@tmp));
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
logmsg (9, 4, "line results now ...".Dumper($linehashref));
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
- my $logfile = shift;
+ my $logfileref = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
- logmsg(1, 0, "processing $logfile using format $format...");
logmsg(5, 1, " and I was called by ... ".&whowasi);
- open (LOGFILE, "<$logfile") or die "Unable to open $SYSLOGFILE for reading...";
+ logmsg(5, 1, "Processing logfiles: ".Dumper($logfileref));
+ foreach my $logfile (@$logfileref) {
+ logmsg(1, 0, "processing $logfile using format $format...");
+ open (LOGFILE, "<$logfile") or die "Unable to open $logfile for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
logmsg(9, 1, "Checking line: $line{line}");
logmsg(9, 2, "Extracted Field contents ...\n".Dumper(@{$line{fields}}));
my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
logmsg(9, 2, keys (%rules)." matches so far");
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
if (keys %rules >= 0) {
logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
my $execruleret = 0;
if (exists($$cfghashref{RULE}{$rule}{actions} ) ) {
$execruleret = execrule(\@{ $$cfghashref{RULE}{$rule}{actions} }, $reshashref, $rule, \%line);
} else {
logmsg (2, 3, "No actions defined for rule; $rule");
}
logmsg (9, 4, "execrule returning $execruleret");
delete $rules{$rule} unless $execruleret;
# TODO: update &actionrule();
}
logmsg (9, 3, "#rules in list .., ".keys(%rules) );
logmsg (9, 3, "\%rules ..".Dumper(%rules));
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
# lastline & repeat
} # rules > 0
if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
logmsg(9 ,1, "Results hash ...".Dumper(%$reshashref) );
logmsg (5, 1, "finished processing line");
}
+ close LOGFILE;
logmsg (1, 0, "Finished processing $logfile.");
+ } # loop through logfiles
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
- my $cfgfile = shift;
+ my $cfgfileref = shift;
+ foreach my $cfgfile (@$cfgfileref) {
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 3, "stanzatype: $stanzatype rulename:$rulename");
logmsg(9, 3, "There are #".($#{$$cfghashref{$stanzatype}{$rulename}{actions}}+1)." elements so far in the action array.");
setaction($$cfghashref{$stanzatype}{$rulename}{actions} , \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
- logmsg (5, 1, "Config Hash contents:");
- &Dumper( %$cfghashref );
- logmsg (1, 0, "finished processing cfg: $cfgfile");
+ logmsg (1, 0, "finished processing cfg: $cfgfile");
+ }
+ logmsg (5, 1, "Config Hash contents: ...".Dumper($cfghashref));
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args passed: ".Dumper(@$argsref));
logmsg (6, 5, "Actions so far .. ".Dumper($actionref));
no strict;
my $actionindex = $#{$actionref}+1;
use strict;
logmsg(5, 5, "There are # $actionindex so far, time to add another one.");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /ignore/i) {
logmsg(5, 6, "cmd is ignore");
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
logmsg(5, 6, "setting matches to $$argsref[3] & cmd to $$argsref[4]");
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
if ($$argsref[4]) {
logmsg (5, 6, "cmd is set in action cmd ... ");
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} elsif (/count/i) {
} else {
warning ("WARNING", "unrecognised command ($$argsref[4]) in ACTION command");
logmsg (1, 6, "unrecognised command in cfg line @$argsref");
}
}
} else {
$$actionref[$actionindex]{cmd} = "count";
logmsg (5, 6, "cmd isn't set in action cmd, defaulting to \"count\"");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp >= 0) {
$$actionref[$actionindex]{lastline} = 1;
}
logmsg(5, 5, "action[$actionindex] for rule is now .. ".Dumper(%{ $$actionref[$actionindex] } ) );
#$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "args: $$argsref[2]");
no strict;
my $reportindex = $#{ $reportref } + 1;
use strict;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3]) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
#my $rpthashref = shift;
logmsg(1, 0, "Runing report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...".Dumper($reshashref));
print "\n\nNo match for lines:\n";
if (exists ($$reshashref{nomatch}) ) {
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
}
print "\n\nSummaries:\n";
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
logmsg (4, 1, "Rule[rptid]: $rule\[$rptid\]");
logmsg (5, 2, "\%ruleresults ... ".Dumper(%ruleresults));
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
} else {
logmsg (4, 2, "No title");
}
for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
print "\t".rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key)."\n";
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
# returns a summarised hash
my %results;
for my $actionid (keys( %$reshashref ) ) {
for my $key (keys %{ $$reshashref{$actionid} } ) {
(my @values) = split (/:/, $key);
logmsg (9, 5, "values from key($key) ... @values");
for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
(my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
logmsg (9, 5, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ".Dumper(@targetfieldids));
my $targetkeymatch;# my $targetid;
# create key using only fieldids required for rptline
# field id's are relative to the fields collected by the action cmds
for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
my $fieldid = $resfieldid+1;
logmsg (9, 6, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
if (grep(/^$fieldid$/, @targetfieldids ) ) {
$targetkeymatch .= ":$values[$resfieldid]";
logmsg(9, 7, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
} else {
$targetkeymatch .= ":.*?";
logmsg(9, 7, "fieldid: $fieldid doesn't in @targetfieldids, adding wildcard to \$targetkeymatch");
}
}
$targetkeymatch =~ s/^://;
logmsg (9, 5, "targetkey is $targetkeymatch");
if ($key =~ /$targetkeymatch/) {
$results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
$results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
$results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
}
} # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ".Dumper($cfghashref));
logmsg (7, 3, "reshash ... ".Dumper($reshashref));
my $line = $$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
$line =~ s/\{x\}/$$reshashref{$key}{count}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
$line =~ s/\{x\}/$$reshashref{$key}{total}/;
logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "$fields[$field] = $fields[$i]");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
}
}
if ($numericonly) {
return @tmpmatrix;
} else {
return @matrix;
}
}
#TODO rename actionrule to execaction, execaction should be called from execrule
#TODO extract handling of individual actions
sub execaction {
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}[$actionid]
my $reshashref = shift;
my $rule = shift;
my $actionid = shift;
my $line = shift; # hash passed by ref, DO NOT mod
logmsg (7, 4, "Processing line with rule ${rule}'s action# $actionid");
my @matrix = getmatchlist($$cfghashref{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{matches}, 1);
if ($#tmpmatrix == -1 ) {
logmsg (7, 5, "hmm, no entries in tmpmatrix and there was ".($#matrix+1)." entries for \@matrix.");
} else {
logmsg (7, 5, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
}
logmsg (9, 6, "rule spec: ".Dumper($cfghashref));
my $retval = 0;
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{regex} =~ /^\!/) {
my $regex = $$cfghashref{regex};
$regex =~ s/^!//;
logmsg(8, 5, "negative regex - !$regex");
if ($$line{ $$cfghashref{field} } !~ /$regex/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
} else {
logmsg(8, 5, "Using regex - $$cfghashref{regex} on field content $$line{ $$cfghashref{field} }");
if ($$line{ $$cfghashref{field} } =~ /$$cfghashref{regex}/ ) {
logmsg(8, 6, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,6, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{matches}, $line);
$retval = 1;
}
logmsg(6, 5, "matrix for rule ... @matrix & matchid $matchid");
}
use strict;
if ($retval) {
if (exists($$cfghashref{cmd} ) ) {
for ($$cfghashref{cmd}) {
logmsg (7, 6, "Processing $$cfghashref{cmd} for $rule [$actionid]");
if (/count/i) {
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/sum/i) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
} elsif (/append/i) {
} elsif (/ignore/i) {
} else {
warning ("w", "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
logmsg(1, 5, "unrecognised cmd ($$cfghashref{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg(1, 5, "hmmm, no cmd set for rule ($rule)'s actionid: $actionid. The cfghashref data is .. ".Dumper($cfghashref));
}
}
logmsg (7, 5, "returning: $retval");
return $retval;
}
sub execrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (6, 3, "rule: $rule called for $$line{line}");
logmsg (9, 3, (@$cfghashref)." actions for rule: $rule");
logmsg (9, 3, "cfghashref .. ".Dumper(@$cfghashref));
for my $actionid ( 0 .. (@$cfghashref - 1) ) {
logmsg (6, 4, "Processing action[$actionid]");
# actionid needs to recorded in resultsref as well as ruleid
if (exists($$cfghashref[$actionid])) {
$retval += execaction(\%{ $$cfghashref[$actionid] }, $reshashref, $rule, $actionid, $line );
} else {
logmsg (6, 3, "\$\$cfghashref[$actionid] doesn't exist, but according to the loop counter it should !! ");
}
}
logmsg (7, 2, "After checking all actions for this rule; \%reshash ...".Dumper($reshashref));
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash{RULES}{$rule}{actions}{$actionid}
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ".Dumper($resmatrixref) );
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..".Dumper(@matrix));
logmsg (9, 6, "\@tmpmatrix ..".Dumper(@tmpmatrix));
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
diff --git a/testcases/test.sh b/testcases/test.sh
index 51dcdfb..5e6de3c 100755
--- a/testcases/test.sh
+++ b/testcases/test.sh
@@ -1,17 +1,24 @@
#!/bin/bash
-dir=`dirname $0`
+dir="`pwd`/`dirname $0`"
OUTFILE="/tmp/logparse.test.output"
+DEFAULTARGS=" -l ./test.log -c ./logparse.conf -d 0"
-for testcase in `ls -dF1 $dir/* | grep '/$'`
+cd $dir
+
+for testcasedir in `ls -dF1 * | grep '/$'`
do
- echo Testcase: $testcase
- $1 -l $testcase/test.log -c $testcase/logparse.conf -d0 > $OUTFILE
- diff -u $OUTFILE $testcase/expected.output
+ cd $dir/$testcasedir
+ if [ -f ./args ] ; then
+ $1 `cat ./args` > $OUTFILE
+ else
+ $1 $DEFAULTARGS > $OUTFILE
+ fi
+ diff -u $OUTFILE ./expected.output
if test $? -eq 0 ; then
- echo $testcase passed
+ echo Testcase `echo $testcasedir | sed 's/\///g'` passed
else
- echo $testcase failed
+ echo Testcase `echo $testcasedir| sed 's/\///g'` failed
fi
rm $OUTFILE
done
|
mikeknox/LogParse | b58b90fe809e8dc75b903a66f3f843f6c3f924fc | Added ability to use process multiple logfiles and/or config files in the same run Also added some testcases for this functionality and made some fixes to the test harness script | diff --git a/testcases/2/Description b/testcases/2/Description
new file mode 100644
index 0000000..a4b7c7f
--- /dev/null
+++ b/testcases/2/Description
@@ -0,0 +1,2 @@
+Basic test case for multiple config and logfiles
+Also IGNORE in an ACTION
diff --git a/testcases/2/args b/testcases/2/args
new file mode 100644
index 0000000..a0baad1
--- /dev/null
+++ b/testcases/2/args
@@ -0,0 +1 @@
+-l ./test.log.1 -l ./test.log.2 -c ./logparse.conf.1 -c ./logparse.conf.2 -d 0
diff --git a/testcases/2/expected.output b/testcases/2/expected.output
new file mode 100644
index 0000000..e2b8580
--- /dev/null
+++ b/testcases/2/expected.output
@@ -0,0 +1,21 @@
+
+
+No match for lines:
+ Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+ Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+
+
+Summaries:
+Sudo usage by cmd/user/host
+ userb ran /usr/bin/tail /var/log/auth.log as root on hosta: 2 times
+ usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
+ userb ran /bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog as root on hosta: 1 times
+ userb ran /bin/grep -i ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/chown usera auth.log as root on hosta: 1 times
+ userb ran /usr/bin/head /var/log/auth.log as root on hosta: 1 times
+
+Sudo usage by user/host
+ usera ran 4 sudo cmds on hosta
+ userb ran 5 sudo cmds on hosta
+
diff --git a/testcases/2/logparse.conf.1 b/testcases/2/logparse.conf.1
new file mode 100644
index 0000000..4da2a88
--- /dev/null
+++ b/testcases/2/logparse.conf.1
@@ -0,0 +1,26 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 APP
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+#######################
diff --git a/testcases/2/logparse.conf.2 b/testcases/2/logparse.conf.2
new file mode 100644
index 0000000..e346fe4
--- /dev/null
+++ b/testcases/2/logparse.conf.2
@@ -0,0 +1,19 @@
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE sudo {
+ APP sudo
+ MSG /.* : .* ; PWD=/
+ ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
+ ACTION MSG /(.*): \(command continued\) / IGNORE
+ REPORT "Sudo usage by cmd/user/host" "{2} ran {4} as {3} on {1}: {x} times" count
+ REPORT "Sudo usage by user/host" "{2} ran {x} sudo cmds on {1}" count
+ # by default {x} is total
+}
+#######################
+#2
diff --git a/testcases/2/test.log.1 b/testcases/2/test.log.1
new file mode 100644
index 0000000..8120f96
--- /dev/null
+++ b/testcases/2/test.log.1
@@ -0,0 +1,6 @@
+Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+Oct 2 15:01:19 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/syslog
+Oct 2 15:01:22 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/syslog
+Oct 2 15:01:25 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/messages
+Oct 2 15:01:31 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep -i ssh /var/log/messages
diff --git a/testcases/2/test.log.2 b/testcases/2/test.log.2
new file mode 100644
index 0000000..8a3df2e
--- /dev/null
+++ b/testcases/2/test.log.2
@@ -0,0 +1,6 @@
+Oct 2 15:01:35 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog
+Oct 2 15:01:35 hosta sudo: userb : (command continued) /var/log/syslog.1.gz /var/log/syslog.2.gz /var/log/syslog.3.gz /var/log/syslog.4.gz /var/log/syslog.5.gz /var/log/syslog.6.gz /var/log/udev /var/log/user.log /var/log/wtmp /var/log/wtmp.1
+Oct 2 15:02:17 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/head /var/log/auth.log
+Oct 2 15:02:22 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/chown usera auth.log
+Oct 2 15:02:55 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/tail /var/log/auth.log
+Oct 2 15:03:50 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/tail /var/log/auth.log
diff --git a/testcases/3/Description b/testcases/3/Description
new file mode 100644
index 0000000..a4b7c7f
--- /dev/null
+++ b/testcases/3/Description
@@ -0,0 +1,2 @@
+Basic test case for multiple config and logfiles
+Also IGNORE in an ACTION
diff --git a/testcases/3/args b/testcases/3/args
new file mode 100644
index 0000000..55deb8c
--- /dev/null
+++ b/testcases/3/args
@@ -0,0 +1 @@
+-l ./test.log.1,./test.log.2 -c ./logparse.conf.1,./logparse.conf.2 -d 0
diff --git a/testcases/3/expected.output b/testcases/3/expected.output
new file mode 100644
index 0000000..e2b8580
--- /dev/null
+++ b/testcases/3/expected.output
@@ -0,0 +1,21 @@
+
+
+No match for lines:
+ Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+ Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+
+
+Summaries:
+Sudo usage by cmd/user/host
+ userb ran /usr/bin/tail /var/log/auth.log as root on hosta: 2 times
+ usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
+ userb ran /bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog as root on hosta: 1 times
+ userb ran /bin/grep -i ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/chown usera auth.log as root on hosta: 1 times
+ userb ran /usr/bin/head /var/log/auth.log as root on hosta: 1 times
+
+Sudo usage by user/host
+ usera ran 4 sudo cmds on hosta
+ userb ran 5 sudo cmds on hosta
+
diff --git a/testcases/3/logparse.conf.1 b/testcases/3/logparse.conf.1
new file mode 100644
index 0000000..4da2a88
--- /dev/null
+++ b/testcases/3/logparse.conf.1
@@ -0,0 +1,26 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 APP
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+#######################
diff --git a/testcases/3/logparse.conf.2 b/testcases/3/logparse.conf.2
new file mode 100644
index 0000000..e346fe4
--- /dev/null
+++ b/testcases/3/logparse.conf.2
@@ -0,0 +1,19 @@
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE sudo {
+ APP sudo
+ MSG /.* : .* ; PWD=/
+ ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
+ ACTION MSG /(.*): \(command continued\) / IGNORE
+ REPORT "Sudo usage by cmd/user/host" "{2} ran {4} as {3} on {1}: {x} times" count
+ REPORT "Sudo usage by user/host" "{2} ran {x} sudo cmds on {1}" count
+ # by default {x} is total
+}
+#######################
+#2
diff --git a/testcases/3/test.log.1 b/testcases/3/test.log.1
new file mode 100644
index 0000000..8120f96
--- /dev/null
+++ b/testcases/3/test.log.1
@@ -0,0 +1,6 @@
+Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+Oct 2 15:01:19 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/syslog
+Oct 2 15:01:22 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/syslog
+Oct 2 15:01:25 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/messages
+Oct 2 15:01:31 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep -i ssh /var/log/messages
diff --git a/testcases/3/test.log.2 b/testcases/3/test.log.2
new file mode 100644
index 0000000..8a3df2e
--- /dev/null
+++ b/testcases/3/test.log.2
@@ -0,0 +1,6 @@
+Oct 2 15:01:35 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog
+Oct 2 15:01:35 hosta sudo: userb : (command continued) /var/log/syslog.1.gz /var/log/syslog.2.gz /var/log/syslog.3.gz /var/log/syslog.4.gz /var/log/syslog.5.gz /var/log/syslog.6.gz /var/log/udev /var/log/user.log /var/log/wtmp /var/log/wtmp.1
+Oct 2 15:02:17 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/head /var/log/auth.log
+Oct 2 15:02:22 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/chown usera auth.log
+Oct 2 15:02:55 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/tail /var/log/auth.log
+Oct 2 15:03:50 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/tail /var/log/auth.log
|
mikeknox/LogParse | bf4a8ac1a59bf9d72585ae648afaed6c4c255fd9 | Moved the tmp output file out of the working area, so git status doesn't get annoyed about it. (Also cleaned up the file) | diff --git a/testcases/test.sh b/testcases/test.sh
index 72caaaf..51dcdfb 100755
--- a/testcases/test.sh
+++ b/testcases/test.sh
@@ -1,15 +1,17 @@
#!/bin/bash
dir=`dirname $0`
+OUTFILE="/tmp/logparse.test.output"
for testcase in `ls -dF1 $dir/* | grep '/$'`
do
echo Testcase: $testcase
- $1 -l $testcase/test.log -c $testcase/logparse.conf -d0 > tmp.output
- diff -u tmp.output $testcase/expected.output
+ $1 -l $testcase/test.log -c $testcase/logparse.conf -d0 > $OUTFILE
+ diff -u $OUTFILE $testcase/expected.output
if test $? -eq 0 ; then
echo $testcase passed
else
echo $testcase failed
fi
+ rm $OUTFILE
done
|
mikeknox/LogParse | d6844ae007309b17cb94245f131df58a4256ae81 | Added basic test framework, so functionality can be simple check (regression etc) Also added a new feature, multiple reports for each rule. IGNORE in ACTION isn't working yet in this reimplementation | diff --git a/logparse.pl b/logparse.pl
index e50ba53..059a0a5 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -340,1103 +340,1129 @@ sub processlogfile {
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfile = shift;
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 5, "stanzatype: $stanzatype rulename:$rulename");
setaction(\@{ $$cfghashref{$stanzatype}{$rulename}{actions} }, \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (5, 1, "Config Hash contents:");
&Dumper( %$cfghashref );
logmsg (1, 0, "finished processing cfg: $cfgfile");
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "args: $$argsref[2]");
unless (exists ${@$actionref}[0] ) {
logmsg(9, 3, "actions array, doesn't exist, initialising");
@$actionref = ();
}
my $actionindex = $#{ @$actionref } + 1;
logmsg(9, 3, "actionindex: $actionindex");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /count/i) {
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
}
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} else {
logmsg (1,0, "WARNING, unrecognised command ($$argsref[4]) in ACTION command");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp) {
$$actionref[$actionindex]{lastline} = 1;
}
$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "args: $$argsref[2]");
unless (exists ${@$reportref}[0] ) {
logmsg(9, 3, "report array, doesn't exist, initialising");
@$reportref = ();
}
my $reportindex = $#{ @$reportref } + 1;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
if ($$argsref[3]) {
$$reportref[$reportindex]{cmd} = $$argsref[3];
} else {
$$reportref[$reportindex]{cmd} = "count";
}
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
=obsolete
sub processformat {
my $cfghashref = shift;
my $rule = shift; # name of the rule to be processed
my $cmd = shift;
my $arg = shift;
#profile( whoami(), whowasi() );
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (5, 4, "Processing rule: $rule");
logmsg(9, 5, "passed cmd: $cmd");
logmsg(9, 5, "passed arg: $arg");
next unless $cmd;
for ($cmd) {
if (/DELIMITER/) {
$$cfghashref{delimiter} = $arg;
logmsg (5, 1, "Config Hash contents:");
&Dumper( %$cfghashref ) if $DEBUG >= 9;
} elsif (/FIELDS/) {
$$cfghashref{totalfields} = $arg;
for my $i(1..$$cfghashref{totalfields}) {
$$cfghashref{fields}{byindex}{$i} = "$i"; # map index to name
$$cfghashref{fields}{byname}{$i} = "$i"; # map name to index
}
} elsif (/FIELD(\d+)/) {
logmsg(6, 6, "FIELD#: $1 arg:$arg");
$$cfghashref{fields}{byindex}{$1} = "$arg"; # map index to name
$$cfghashref{fields}{byname}{$arg} = "$1"; # map name to index
if (exists($$cfghashref{fields}{byname}{$1}) ) {
delete($$cfghashref{fields}{byname}{$1});
}
} elsif (/DEFAULT/) {
$$cfghashref{default} = 1;
#} elsif (/REPEAT/) {
#TODO Define sub stanzas, it's currently hacked in
# extractcmd(\%{$$cfghashref{repeat}}, $cmd, "repeat", $arg);0
} elsif (/REGEX/) {
extractcmd(\%{$$cfghashref{repeat}}, $cmd, "regex", $arg);
} elsif (/FIELD/) {
$$cfghashref{repeat}{field} = $arg;
} elsif (/^\}$/) {
} elsif (/^\{$/) {
} else {
print "Error: $cmd didn't match any known fields\n\n";
} # if cmd
} # for cmd
logmsg (5, 4, "Finished processing rule: $rule");
} # sub processformat
sub processrule {
my $cfghashref = shift;
my $forhashref = shift; # ref to log format hash
my $cmd = shift;
my $arg = shift;
#profile( whoami(), whowasi() );
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (5, 4, "Processing $$cfghashref{name} with cmd: $cmd and arg: $arg");
logmsg (5, 5, "Format hash ...".Dumper(%$forhashref) );
next unless $cmd;
for ($cmd) {
# Static parameters
if (/FORMAT/){
# This really should be the first entry in a rule stanza if it's set
$$cfghashref{format} = $arg;
} elsif (/CMD/) {
extractcmd($cfghashref, $cmd, "cmd", $arg);
} elsif (/^REGEX/) {
extractcmd($cfghashref, $cmd, "regex", $arg);
} elsif (/MATCH/) {
extractcmd($cfghashref, $cmd, "matrix", $arg);
} elsif (/IGNORE/) {
extractcmd(\%{$$cfghashref{CMD}}, $cmd, "", $arg);
} elsif (/COUNT/) {
extractcmd(\%{$$cfghashref{CMD}}, $cmd, "", $arg);
} elsif (/SUM/) {
extractcmd(\%{$$cfghashref{CMD}}, $cmd, "targetfield", $arg);
} elsif (/AVG/) {
extractcmd(\%{$$cfghashref{CMD}}, $cmd, "targetfield", $arg);
} elsif (/TITLE/) {
$$cfghashref{RPT}{title} = $arg;
$$cfghashref{RPT}{title} = $1 if $$cfghashref{RPT}{title} =~ /^\"(.*)\"$/;
} elsif (/LINE/) {
$$cfghashref{RPT}{line} = $arg;
$$cfghashref{RPT}{line} = $1 if $$cfghashref{RPT}{line} =~ /\^"(.*)\"$/;
} elsif (/APPEND/) {
$$cfghashref{RPT}{appendrule} = $arg;
logmsg (1, 0, "*** Setting append for $$cfghashref{name} to $arg");
} elsif (/REPORT/) {
} elsif (/^\}$/) {
} elsif (/^\{$/) {
# Dynamic parameters (defined in FORMAT stanza)
} elsif (exists($$forhashref{fields}{byname}{$cmd} ) ) {
extractregex (\%{$$cfghashref{fields} }, $cmd, $arg);
# End Dynamic parameters
} else {
print "Error: $cmd didn't match any known fields\n\n";
}
} # for
logmsg (5, 1, "Finished processing rule: $$cfghashref{name}");
logmsg (9, 1, "Config hash after running processrule");
Dumper(%$cfghashref);
} # sub processrule
=cut
=obsolete?
sub extractcmd {
my $cfghashref = shift;
my $cmd = shift;
my $param = shift; # The activity associated with cmd
my $arg = shift; # The value for param
if ($param) {
extractregex ($cfghashref, "$param", $arg);
$$cfghashref{$param} =~ s/\s+//g; # strip all whitespace
}
$$cfghashref{cmd} = $cmd;
}
sub extractregexold {
# Keep the old behaviour
my $cfghashref = shift;
my $param = shift;
my $arg = shift;
# profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $paramnegat = $param."negate";
logmsg (5, 1, "rule: $$cfghashref{name} param: $param arg: $arg");
if ($arg =~ /^!/) {
$arg =~ s/^!//g;
$$cfghashref{$paramnegat} = 1;
} else {
$$cfghashref{$paramnegat} = 0;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^\{//;
$arg =~ s/\}$//;
$$cfghashref{$param} = $arg;
logmsg (5, 2, "$param = $$cfghashref{$param}");
}
sub extractregex {
# Put the matches into an array, but would need to change how we handle negates
# Currently the negate is assigned to match group (ie facility or host) or rather than
# an indivudal regex, not an issue immediately because we only support 1 regex
# Need to assign the negate to the regex
# Make the structure ...
# $$cfghashref{rules}{$rule}{$param}[$index] is a hash with {regex} and {negate}
my $cfghashref = shift;
my $param = shift;
my $arg = shift;
my $index = 0;
# profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
logmsg (1, 3, " rule: $$cfghashref{name} for param $param with arg $arg ");
#TODO {name} is null when called for sub stanzas such as CMD or REPEAT, causes an "uninitialised value" warning
if (exists $$cfghashref{$param}[0] ) {
$index = @{$$cfghashref{$param}};
} else {
$$cfghashref{$param} = ();
}
my $regex = \%{$$cfghashref{$param}[$index]};
$$regex{negate} = 0;
logmsg (5, 1, "$param $arg");
if ($arg =~ /^!/) {
$arg =~ s/^!//g;
$$regex{negate} = 1;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^{//;
$arg =~ s/}$//;
$$regex{regex} = $arg;
logmsg (9, 3, "$regex\{regex\} = $$regex{regex} & \$regex\{negate\} = $$regex{negate}");
logmsg (5,2, "$index = $index");
logmsg (5, 2, "$param \[$index\]\{regex\} = $$cfghashref{$param}[$index]{regex}");
logmsg (5, 2, "$param \[$index\]\{negate\} = $$cfghashref{$param}[$index]{negate}");
for (my $i=0; $i<=$index; $i++)
{
logmsg (5,1, "index: $i");
foreach my $key (keys %{$$cfghashref{$param}[$i]}) {
logmsg (5, 2, "$param \[$i\]\{$key\} = $$cfghashref{$param}[$i]{$key}");
}
}
}
=cut
sub report {
my $cfghashref = shift;
my $reshashref = shift;
my $rpthashref = shift;
logmsg(1, 0, "Ruuning report");
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...".Dumper($reshashref));
print "\n\nNo match for lines:\n";
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
print "\n\nSummaries:\n";
for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
- my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
- logmsg (5, 2, "\%ruleresults ... ".Dumper(%ruleresults));
+
if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
- for my $rptid ($#{ $$cfghashref{RULE}{$rule}{reports} } ) {
- logmsg (4, 1, "Rule: $rule\[$rptid\]");
+ for my $rptid (0 .. $#{ $$cfghashref{RULE}{$rule}{reports} } ) {
+ my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
+ logmsg (4, 1, "Rule[rptid]: $rule\[$rptid\]");
+ logmsg (5, 2, "\%ruleresults ... ".Dumper(%ruleresults));
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
} else {
logmsg (4, 2, "No title");
}
- for my $key (keys %ruleresults) {
+ for my $key (keys %{$ruleresults{$rptid} }) {
logmsg (5, 3, "key:$key");
if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
- print "\t".rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$key} }, $rule, $rptid, $key)."\n";
+ print "\t".rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$rptid} }, $rule, $rptid, $key)."\n";
} else {
print "\t$$reshashref{$rule}{$key}: $key\n";
}
}
print "\n";
} # for rptid
} # if reports in %cfghash{RULE}{$rule}
} # for rule in %reshashref
} #sub
sub summariseresults {
- my $cfghashref = shift; # passed $cfghash{RULE}{$rule}{actions}
+ my $cfghashref = shift; # passed $cfghash{RULE}{$rule}
my $reshashref = shift; # passed $reshashref{$rule}
#my $rule = shift;
# loop through reshash for a given rule and combine the results of all the actions
- # sum and count totals are summed together
- # AVG is avg'd against the running total
- # won't make sense if there are avg and sum/count actions, but this wouldn't make a lot of sense anyway
# returns a summarised hash
my %results;
for my $actionid (keys( %$reshashref ) ) {
for my $key (keys %{ $$reshashref{$actionid} } ) {
- $results{$key}{count} += $$reshashref{$actionid}{$key}{count};
- $results{$key}{total} += $$reshashref{$actionid}{$key}{total};
- $results{$key}{avg} = $results{$key}{total} / $results{$key}{count};
+ (my @values) = split (/:/, $key);
+ logmsg (9, 5, "values from key($key) ... @values");
+ for my $rptid (0 .. $#{ $$cfghashref{reports} }) {
+ (my @targetfieldids) = $$cfghashref{reports}[$rptid]{line} =~ /(\d+?)/g;
+ logmsg (9, 5, "targetfields (from $$cfghashref{reports}[$rptid]{line})... ".Dumper(@targetfieldids));
+
+ my $targetkeymatch;# my $targetid;
+ # create key using only fieldids required for rptline
+ # field id's are relative to the fields collected by the action cmds
+ for my $resfieldid (0 .. $#values) {# loop through the fields in the key from reshash (generated by action)
+ my $fieldid = $resfieldid+1;
+
+ logmsg (9, 6, "Checking for $fieldid in \@targetfieldids(@targetfieldids), \@values[$resfieldid] = $values[$resfieldid]");
+ if (grep(/^$fieldid$/, @targetfieldids ) ) {
+ $targetkeymatch .= ":$values[$resfieldid]";
+ logmsg(9, 7, "fieldid: $fieldid occured in @targetfieldids, adding $values[$resfieldid] to \$targetkeymatch");
+ } else {
+ $targetkeymatch .= ":.*?";
+ logmsg(9, 7, "fieldid: $fieldid doesn't in @targetfieldids, adding wildcard to \$targetkeymatch");
+ }
+ }
+ $targetkeymatch =~ s/^://;
+
+ logmsg (9, 5, "targetkey is $targetkeymatch");
+ if ($key =~ /$targetkeymatch/) {
+ $results{$rptid}{$targetkeymatch}{count} += $$reshashref{$actionid}{$key}{count};
+ $results{$rptid}{$targetkeymatch}{total} += $$reshashref{$actionid}{$key}{total};
+ $results{$rptid}{$targetkeymatch}{avg} = $$reshashref{$actionid}{$key}{total} / $$reshashref{$actionid}{$key}{count};
+ }
+ } # for $rptid in reports
} # for rule/actionid/key
} # for rule/actionid
+
return %results;
}
sub rptline {
my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
my $reshashref = shift; # reshash{$rule}
#my $rpthashref = shift;
my $rule = shift;
my $rptid = shift;
my $key = shift;
logmsg (5, 2, " and I was called by ... ".&whowasi);
# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
logmsg (9, 3, "key: $key");
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (7, 3, "cfghash ... ".Dumper($cfghashref));
logmsg (7, 3, "reshash ... ".Dumper($reshashref));
my $line = $$cfghashref{line};
logmsg (7, 3, "report line: $line");
for ($$cfghashref{cmd}) {
if (/count/i) {
- $line =~ s/\{x\}/$$reshashref{count}/;
- logmsg(9, 3, "subsituting {x} with $$reshashref{count}");
+ $line =~ s/\{x\}/$$reshashref{$key}{count}/;
+ logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{count} (count)");
} elsif (/SUM/i) {
- $line =~ s/\{x\}/$$reshashref{total}/;
- logmsg(9, 3, "subsituting {x} with $$reshashref{total}");
+ $line =~ s/\{x\}/$$reshashref{$key}{total}/;
+ logmsg(9, 3, "subsituting {x} with $$reshashref{$key}{total} (total)");
} elsif (/AVG/i) {
- my $avg = $$reshashref{total} / $$reshashref{count};
+ my $avg = $$reshashref{$key}{total} / $$reshashref{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{x\}/$avg/;
- logmsg(9, 3, "subsituting {x} with $avg");
+ logmsg(9, 3, "subsituting {x} with $avg (avg)");
} else {
logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
}
}
my @fields = split /:/, $key;
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "$fields[$field] = $fields[$i]");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
}
}
if ($numericonly) {
return @tmpmatrix;
} else {
return @matrix;
}
}
sub actionrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{RULES}{$rule} but would break append
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 1, " and I was called by ... ".&whowasi);
logmsg (6, 2, "rule: $rule called for $$line{line}");
logmsg (9, 3, ($#{ $$cfghashref{$rule}{actions} } + 1)." actions for rule: $rule");
for my $actionid ( 0 .. $#{ $$cfghashref{$rule}{actions} } ) {
logmsg (6, 2, "Actionid: $actionid");
# actionid needs to recorded in resultsref as well as ruleid
my @matrix = getmatchlist($$cfghashref{$rule}{actions}[$actionid]{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{$rule}{actions}[$actionid]{matches}, 1);
logmsg (7, 4, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{$rule}{actions}[$actionid]{regex} =~ /^\!/) {
my $regex = $$cfghashref{$rule}{actions}[$actionid]{regex};
$regex =~ s/^!//;
logmsg(8, 4, "negative regex - !$regex");
if ($$line{ $$cfghashref{$rule}{actions}[$actionid]{field} } !~ /$regex/ ) {
logmsg(8, 5, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,5, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{$rule}{actions}[$actionid]{matches}, $line);
$retvalue = 1;
}
} else {
logmsg(8, 4, "Using regex - $$cfghashref{$rule}{actions}[$actionid]{regex}");
if ($$line{ $$cfghashref{$rule}{actions}[$actionid]{field} } =~ /$$cfghashref{$rule}{actions}[$actionid]{regex}/ ) {
logmsg(8, 5, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,5, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{$rule}{actions}[$actionid]{matches}, $line);
$retval = 1;
}
logmsg(6, 3, "matrix for $rule & actionid $actionid: @matrix & matchid $matchid");
}
use strict;
if ($matchid) {
$$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{$rule}{actions}[$actionid]{sourcefield} ];
$$reshashref{$rule}{$actionid}{$matchid}{count}++;
for ($$cfghashref{$rule}{actions}[$actionid]{cmd}) {
if (/append/i) {
} else {
logmsg (1, 0, "Warning: unrecognized cmd ($$cfghashref{$rule}{actions}[$actionid]{cmd}) in action ($actionid) for rule: $rule");
}
}
} else {
logmsg (3, 5, "No matchid");
}
}
logmsg (7, 5, "\%reshash ...".Dumper($reshashref));
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{RULES}{$rule} but would break append
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ".Dumper($resmatrixref) );
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..".Dumper(@matrix));
logmsg (9, 6, "\@tmpmatrix ..".Dumper(@tmpmatrix));
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
=depricate
sub actionrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{rules}{$rule} but would break append
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $value;
my $retval = 0; my $resultsrule;
# profile( whoami(), whowasi() );
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg (9, 2, "rule: $rule");
if (exists ($$cfghashref{rules}{$rule}{appendrule})) {
$resultsrule = $$cfghashref{rules}{$rule}{appendrule};
} else {
$resultsrule = $rule;
}
unless ($$cfghashref{rules}{cmdregex}) {
$$cfghashref{rules}{cmdregex} = "";
}
logmsg (5, 3, "rule: $rule");
logmsg (5, 4, "results goto: $resultsrule");
logmsg (5, 4, "cmdregex: $$cfghashref{rules}{cmdregex}");
logmsg (5, 4, "CMD negative regex: $$cfghashref{rules}{$rule}{cmdregexnegat}");
logmsg (5, 4, "line: $$line{line}");
if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /IGNORE/) {
if (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "rule $rule does matches and is a positive IGNORE rule");
}
} else {
logmsg (5, 4, "rule $rule matches and is an IGNORE rule");
$retval = 1;
}
} elsif (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
if ( not $$cfghashref{rules}{$rule}{cmdregexnegat} ) {
if ( $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "Positive match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
} elsif ($$cfghashref{rules}{$rule}{cmdregexnegat}) {
if ( $$line{line} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "Negative match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
}
} else {
logmsg (5, 4, "No cmd regex, implicit match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
if ($retval == 0) {
logmsg (5, 4, "line does not match cmdregex for rule: $rule");
}
return $retval;
}
=cut
=depricate
sub actionrulecmd
{
my $cfghashref = shift;
my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift;
my $resultsrule = shift;
#3 profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
logmsg (2, 2, "actioning rule $rule for line: $$line{line}");
# This sub contains the first half of the black magic
# The results from the regex's that are applied later
# are used in actioncmdmatrix()
#
# create a matrix that can be used for matching for the black magic happens
# Instead of the string cmdmatrix
# make a hash of matchmatrix{<match field#>} = <cmdregex field #>
# 2 arrays ...
# fieldnums ... the <match field #'s> of matchmatrix{}
# fieldnames ... the named matches of matchmatrix{}, these match back to the names of the fields
# from the file FORMAT
#
my @tmpmatrix = split (/,/, $$cfghashref{rules}{$rule}{cmdmatrix});
my @matrix = ();
for my $val (@tmpmatrix) {
if ($val =~ /(\d+)/ ) {
push @matrix, $val;
} else {
logmsg(3,3, "Not adding val:$val to matrix");
}
}
logmsg(3, 3, "matrix: @matrix");
#
if (not $$cfghashref{rules}{$rule}{cmdregex}) {
$$cfghashref{rules}{$rule}{cmdregex} = "(.*)";
logmsg (5, 3, "rule did not define cmdregex, replacing with global match");
}
if ( exists $$cfghashref{rules}{$rule}{cmd}) {
logmsg (5, 3, "Collecting data from cmd $$cfghashref{rules}{$rule}{cmd}");
logmsg (5, 3, "rule $rule matches cmd") if $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/;
}
if (not exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
logmsg (5, 3, "No cmd regex, calling actioncmdmatrix");
actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
} elsif ($$cfghashref{rules}{$rule}{cmdregexnegat} ) {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 3, "Negative match, calling actioncmdmatrix");
actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
}
} else {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 3, "Positive match, calling actioncmdmatrixnline hash:");
print Dumper($line) if $DEBUG >= 5;
actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
}
}
}
sub printhash
{
# profile( whoami(), whowasi() );
my $line = shift; # hash passed by ref, DO NOT mod
foreach my $key (keys %{ $line} )
{
logmsg (9, 5, "$key: $$line{$key}");
}
}
sub actioncmdmatrix
{
my $cfghashref = shift;
my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift; # Name or ID of rule thats been matched
my $resultsrule = shift; # Name or ID of rule which contains the result set to be updated
my $matrixref = shift; # arrayref
logmsg(5, 4, " ... actioning resultsrule = $rule");
logmsg(5, 5, " and I was called by ... ".&whowasi);
logmsg(9, 5, "Line hash ...");
print Dumper(%$line);
#profile( whoami(), whowasi() );
my $cmdmatrix = $$cfghashref{rules}{$rule}{cmdmatrix};
#my @matrix = shift; #split (/,/, $cmdmatrix);
my $fieldhash;
my $cmdfield;
# @matrix - array of parameters that are used in results
if ( exists ($$cfghashref{rules}{$rule}{cmdfield}) ) {
$cmdfield = ${$$cfghashref{rules}{$rule}{cmdfield}};
}
if ( exists $$cfghashref{rules}{$rule}{cmdmatrix}) {
logmsg (5, 5, "Collecting data for matrix $$cfghashref{rules}{$rule}{cmdmatrix}");
print Dumper(@$matrixref);
logmsg (5, 5, "Using matrix @$matrixref");
# this is where "strict refs" breaks things
# sample: @matrix = svr,1,4,5
# error ... can't use string ("svr") as a SCALAR ref while "strict refs" in use
#
# soln: create a temp array which only has the field #'s and match that
# might need a hash to match
no strict 'refs'; # turn strict refs off just for this section
foreach my $field (@$matrixref) {
# This is were the black magic occurs, ${$field} causes becomes $1 or $2 etc
# and hence contains the various matches from the previous regex match
# which occured just before this function was called
logmsg (9, 5, "matrix field $field has value ${$field}");
if (exists $$line{$field}) {
if ($fieldhash) {
$fieldhash = "$fieldhash:$$line{$field}";
} else {
$fieldhash = "$$line{$field}";
}
} else {
if ($fieldhash) {
$fieldhash = "$fieldhash:${$field}";
} else {
if ( ${$field} ) {
$fieldhash = "${$field}";
} else {
logmsg (1, 6, "$field not found in \"$$line{line}\" with regex $$cfghashref{rules}{$rule}{cmdregex}");
logmsg (1, 6, "line hash:");
print Dumper(%$line) if $DEBUG >= 1;
}
}
}
}
use strict 'refs';
if ($$cfghashref{rules}{$rule}{targetfield}) {
logmsg (1, 5, "Setting cmdfield (field $$cfghashref{rules}{$rule}{targetfield}) to ${$$cfghashref{rules}{$rule}{targetfield}}");
$cmdfield = ${$$cfghashref{rules}{$rule}{targetfield}};
}
#if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
$$reshashref{$resultsrule}{$fieldhash}{count}++;
logmsg (5, 5, "$$reshashref{$resultsrule}{$fieldhash}{count} matches for rule $rule so far from $fieldhash");
#} els
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
$$reshashref{$resultsrule}{$fieldhash}{sum} = $$reshashref{$resultsrule}{$fieldhash}{sum} + $cmdfield;
logmsg (5, 5, "Adding $cmdfield to total (now $$reshashref{$resultsrule}{$fieldhash}{sum}) for rule $rule so far from $fieldhash");
if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
logmsg (5, 5, "Average is ".$$reshashref{$resultsrule}{$fieldhash}{sum} / $$reshashref{$resultsrule}{$fieldhash}{count}." for rule $rule so far from $fieldhash");
}
}
for my $key (keys %{$$reshashref{$resultsrule}}) {
logmsg (5, 5, "key $key for rule:$rule with $$reshashref{$resultsrule}{$key}{count} matches");
}
logmsg (5, 5, "$fieldhash matches for rule $rule so far from matrix: $$cfghashref{rules}{$rule}{cmdmatrix}");
} else {
logmsg (5, 5, "cmdmatrix is not set for $rule");
#if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
$$reshashref{$resultsrule}{count}++;
logmsg (5, 5, "$$reshashref{$resultsrule}{count} lines match rule $rule so far");
# } els
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
$$reshashref{$resultsrule}{sum} = $$reshashref{$resultsrule}{sum} + $cmdfield;
logmsg (5, 5, "$$reshashref{$resultsrule}{sum} lines match rule $rule so far");
}
}
logmsg(5, 4, " ... Finished actioning resultsrule = $rule");
}
=cut
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
for my $rule (keys %{ $cfghashref } ) {
$rules{$rule} = $rule if matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref);
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1;
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
foreach my $field (keys (%{ $cfghashref } ) ) {
if ($$cfghashref{fields}{$field} =~ /^!/) {
my $exp = $$cfghashref{fields}{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{fields}{$field}/);
}
}
return $ret;
}
sub matchingrules {
my $cfghashref = shift;
my $param = shift;
my $matchref = shift;
my $value = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 3, "param:$param");
logmsg (6, 3, "value:$value") if $value;
logmsg (3, 2, "$param, match count: ".keys(%{$matchref}) );
if (keys %{$matchref} == 0) {
# Check all rules as we haevn't had a match yet
foreach my $rule (keys %{$cfghashref->{rules} } ) {
checkrule($cfghashref, $param, $matchref, $rule, $value);
}
} else {
# As we've allready had a match on the rules, only check those that matched in earlier rounds
# key in %matches is the rule that matches
foreach my $rule (keys %{$matchref}) {
checkrule($cfghashref, $param, $matchref, $rule, $value);
}
}
}
sub checkrule {
my $cfghashref = shift;
my $param = shift;
my $matches = shift;
my $rule = shift; # key to %matches
my $value = shift;
logmsg(2, 1, "Checking rule ($rule) & param ($param) for matches against: $value");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $paramref = \@{ $$cfghashref{rules}{$rule}{$param} };
defaultregex($paramref); # This should be done when reading the config
foreach my $index (@{ $paramref } ) {
my $match = matchregex($index, $value);
if ($$index{negate} ) {
if ( $match) {
delete $$matches{$rule};
logmsg (5, 5, "matches $index->{regex} for param \'$param\', but negative rule is set, so removing rule $match from list.");
} else {
$$matches{$rule} = "match" if $match;
diff --git a/testcases/1/Description b/testcases/1/Description
new file mode 100644
index 0000000..b0ae886
--- /dev/null
+++ b/testcases/1/Description
@@ -0,0 +1,2 @@
+Basic test case for multiple reports in a rule & counts.
+Also IGNORE in an ACTION
diff --git a/testcases/1/expected.output b/testcases/1/expected.output
new file mode 100644
index 0000000..e2b8580
--- /dev/null
+++ b/testcases/1/expected.output
@@ -0,0 +1,21 @@
+
+
+No match for lines:
+ Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+ Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+
+
+Summaries:
+Sudo usage by cmd/user/host
+ userb ran /usr/bin/tail /var/log/auth.log as root on hosta: 2 times
+ usera ran /bin/grep ssh /var/log/syslog as root on hosta: 2 times
+ userb ran /bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog as root on hosta: 1 times
+ userb ran /bin/grep -i ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/grep ssh /var/log/messages as root on hosta: 1 times
+ usera ran /bin/chown usera auth.log as root on hosta: 1 times
+ userb ran /usr/bin/head /var/log/auth.log as root on hosta: 1 times
+
+Sudo usage by user/host
+ usera ran 4 sudo cmds on hosta
+ userb ran 5 sudo cmds on hosta
+
diff --git a/testcases/1/logparse.conf b/testcases/1/logparse.conf
new file mode 100644
index 0000000..e908fd8
--- /dev/null
+++ b/testcases/1/logparse.conf
@@ -0,0 +1,44 @@
+#########
+FORMAT syslog {
+ # FIELDS <field count> <delimiter>
+ # FIELDS <field count> <delimiter> [<parent field>]
+ # FIELD <field id #> <label>
+ # FIELD <parent field id#>-<child field id#> <label>
+
+ FIELDS 6 "\s+"
+ FIELD 1 MONTH
+ FIELD 2 DAY
+ FIELD 3 TIME
+ FIELD 4 HOST
+ FIELD 5 APP
+ FIELD 6 FULLMSG
+ FIELDS 6-2 /]\s+/
+ FIELD 6-1 FACILITY
+ FIELD 6-2 MSG default
+
+ LASTLINEINDEX HOST
+ # LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
+
+ # default format to be used for log file analysis
+ DEFAULT
+}
+
+RULE {
+ MSG /^message repeated (.*) times/ OR /^message repeated$/
+
+ ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
+ # Apply {1} as {x} in the previously applied rule for HOST
+ ACTION MSG /^message repeated$/ count append LASTLINE
+}
+
+RULE sudo {
+ APP sudo
+ MSG /.* : .* ; PWD=/
+ ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
+ ACTION MSG /(.*): (command continued) / IGNORE
+ REPORT "Sudo usage by cmd/user/host" "{2} ran {4} as {3} on {1}: {x} times" count
+ REPORT "Sudo usage by user/host" "{2} ran {x} sudo cmds on {1}" count
+ # by default {x} is total
+}
+#######################
+#2
diff --git a/testcases/1/test.log b/testcases/1/test.log
new file mode 100644
index 0000000..7009c17
--- /dev/null
+++ b/testcases/1/test.log
@@ -0,0 +1,12 @@
+Oct 2 15:00:01 hosta CRON[3836]: pam_unix(cron:session): session opened for user root by (uid=0)
+Oct 2 15:00:02 hosta CRON[3836]: pam_unix(cron:session): session closed for user root
+Oct 2 15:01:19 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/syslog
+Oct 2 15:01:22 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/syslog
+Oct 2 15:01:25 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep ssh /var/log/messages
+Oct 2 15:01:31 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep -i ssh /var/log/messages
+Oct 2 15:01:35 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/grep -i ssh /var/log/apache2 /var/log/apparmor /var/log/apt /var/log/aptitude /var/log/aptitude.1.gz /var/log/auth.log /var/log/auth.log.0 /var/log/auth.log.1.gz /var/log/boot /var/log/btmp /var/log/btmp.1 /var/log/ConsoleKit /var/log/daemon.log /var/log/dbconfig-common /var/log/debug /var/log/dist-upgrade /var/log/dmesg /var/log/dmesg.0 /var/log/dmesg.1.gz /var/log/dmesg.2.gz /var/log/dmesg.3.gz /var/log/dmesg.4.gz /var/log/dpkg.log /var/log/dpkg.log.1 /var/log/dpkg.log.2.gz /var/log/exim4 /var/log/faillog /var/log/fsck /var/log/installer /var/log/kern.log /var/log/landscape /var/log/lastlog /var/log/lpr.log /var/log/mail.err /var/log/mail.info /var/log/mail.log /var/log/mail.warn /var/log/messages /var/log/mysql /var/log/mysql.err /var/log/mysql.log /var/log/mysql.log.1.gz /var/log/news /var/log/pycentral.log /var/log/request-tracker3.6 /var/log/syslog /var/log/syslog
+Oct 2 15:01:35 hosta sudo: userb : (command continued) /var/log/syslog.1.gz /var/log/syslog.2.gz /var/log/syslog.3.gz /var/log/syslog.4.gz /var/log/syslog.5.gz /var/log/syslog.6.gz /var/log/udev /var/log/user.log /var/log/wtmp /var/log/wtmp.1
+Oct 2 15:02:17 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/head /var/log/auth.log
+Oct 2 15:02:22 hosta sudo: usera : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/bin/chown usera auth.log
+Oct 2 15:02:55 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/tail /var/log/auth.log
+Oct 2 15:03:50 hosta sudo: userb : TTY=pts/0 ; PWD=/home/mike/src/LogParse ; USER=root ; COMMAND=/usr/bin/tail /var/log/auth.log
diff --git a/testcases/test.sh b/testcases/test.sh
new file mode 100755
index 0000000..72caaaf
--- /dev/null
+++ b/testcases/test.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+
+dir=`dirname $0`
+
+for testcase in `ls -dF1 $dir/* | grep '/$'`
+do
+ echo Testcase: $testcase
+ $1 -l $testcase/test.log -c $testcase/logparse.conf -d0 > tmp.output
+ diff -u tmp.output $testcase/expected.output
+ if test $? -eq 0 ; then
+ echo $testcase passed
+ else
+ echo $testcase failed
+ fi
+done
|
mikeknox/LogParse | 4a6fb9dd617b2f09a8750bb049199dd5ff588aac | initial phase of rewrite complete, report now runs again. | diff --git a/logparse.conf b/logparse.conf
index 385ab55..2896da8 100644
--- a/logparse.conf
+++ b/logparse.conf
@@ -1,78 +1,79 @@
# Describe config file for log parse / summary engine
#
#
# FORMAT <name> {
# DELIMITER <xyz>
# FIELDS <x>
# FIELD<x> <name>
#}
FORMAT dummy {
DELIMITER \t
FIELDS 2
FIELD1 abc
FIELD2 def
}
# Need to redefine the language structure for the config file
# there are a lot of different commands, and the language needs to be formalised
# to make it easier to automate
# Current only support logical ops AND and NOT, need to add grouping and OR
# Also being able to use LASTLINE in rules would be neat, especially against HOSTS different to current
# Need to track which FIELD the lastline should be indexed against
# eg in consolidated logfiles, last line would be indexed on HOST
# also need to handle the scenario that last line is a continued line?
# Structure definition ...
#########
FORMAT syslog {
# FIELDS <field count> <delimiter>
# FIELDS <field count> <delimiter> [<parent field>]
# FIELD <field id #> <label>
# FIELD <parent field id#>-<child field id#> <label>
FIELDS 6 "\s+"
FIELD 1 MONTH
FIELD 2 DAY
FIELD 3 TIME
FIELD 4 HOST
FIELD 5 APP
FIELD 6 FULLMSG
FIELDS 6-2 /]\s+/
FIELD 6-1 FACILITY
FIELD 6-2 MSG default
LASTLINEINDEX HOST
# LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
# default format to be used for log file analysis
DEFAULT
# ACTION <field> </regex/> <{matches}> sum <{sum field}>
#ACTION MSG /^message repeated (.*) times/ {1} sum {1}
# Apply {1} as {x} in the previously applied rule for HOST
#ACTION MSG /^message repeated$/ count
}
RULE {
MSG /^message repeated (.*) times/ OR /^message repeated$/
ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
# Apply {1} as {x} in the previously applied rule for HOST
ACTION MSG /^message repeated$/ count append LASTLINE
}
RULE sudo {
APP sudo
MSG /.* : .* ; PWD=/
- ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
- REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
+ ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5}
+ REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times" count
+ # by default {x} is total
}
#######################
#2
diff --git a/logparse.pl b/logparse.pl
index 160721e..e50ba53 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1436 +1,1483 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Std;
use Data::Dumper qw(Dumper);
# Globals
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my $CONFIGFILE="logparse.conf";
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
my $SYSLOGFILE = "/var/log/messages";
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
getopt('cdl', \%opts);
$DEBUG = $opts{d} if $opts{d};
$CONFIGFILE = $opts{c} if $opts{c};
$SYSLOGFILE = $opts{l} if $opts{l};
loadcfg (\%cfghash, $CONFIGFILE);
-print Dumper(\%cfghash);
+logmsg(7, 3, "cfghash:".Dumper(\%cfghash));
processlogfile(\%cfghash, \%reshash, $SYSLOGFILE);
-#report(\%cfghash, \%reshash);
-#profilereport();
+report(\%cfghash, \%reshash);
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
logmsg (5, 4, "\$text doesnot contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
$$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
}
} else {
(@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
logmsg (9, 4, "Got field values ... ".Dumper(@tmp));
for (my $i = 0; $i <= $#tmp+1; $i++) {
$$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
logmsg(9, 4, "Checking field $i(".($i+1).")");
if (exists($$cfghashref{$i + 1} ) ) {
logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
}
}
}
logmsg (9, 4, "line results now ...".Dumper($linehashref));
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfile = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
my %lastline;
logmsg(1, 0, "processing $logfile using format $format...");
logmsg(5, 1, " and I was called by ... ".&whowasi);
open (LOGFILE, "<$logfile") or die "Unable to open $SYSLOGFILE for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
- #@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
+
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
#($line{mth}, $line{date}, $line{time}, $line{svr}, $line{app}, $line{msg}) = split (/\s+/, $line{line}, 6);
# logmsg(9, 2, "mth: $line{mth}, date: $line{date}, time: $line{time}, svr: $line{svr}, app: $line{app}, msg: $line{msg}");
logmsg(9, 1, "Checking line: $line{line}");
logmsg(9, 2, "Extracted Field contents ...\n".Dumper(@{$line{fields}}));
my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
# my %matchregex = ("svrregex", "svr", "appregex", "app", "facregex", "facility", "msgregex", "line");
# for my $field (keys %{$$cfghashref{formats}{$format}{fields}{byname} }) {
# matchingrules($cfghashref, $field, \%matches, $line{ $field } );
# }
###matchingrules($cfghashref, $param, \%matches, $line{ $matchregex{$param} } );
#}
logmsg(9, 2, keys (%rules)." matches so far");
- $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} and next unless keys(%rules) > 0;
- logmsg(9,1,"Results hash ...".Dumper(%$reshashref) );
+# $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} and next unless keys(%rules) > 0;
+
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
=replace with repeat rule
if ( exists( $$cfghashref{formats}{$format}{repeat} ) ) {
my $repeatref = \%{$$cfghashref{formats}{$format}{repeat} };
if ($$repeatref{cmd} =~ /REGEX/ ) {
foreach my $i (@{$$repeatref{regex}}) {
if ($line{$$repeatref{field}} =~ /$$repeatref{regex}[$i]{regex}/) {
}
}
}
}
if ($line{msg} =~ /message repeated/ and exists $svrlastline{$line{svr} }{line}{msg} ) { # and keys %{$svrlastline{ $line{svr} }{rulematches}} ) {
logmsg (9, 2, "last message repeated and matching svr line");
my $numrepeats = 0;
if ($line{msg} =~ /message repeated (.*) times/) {
$numrepeats = $1;
}
logmsg(9, 2, "Last message repeated $numrepeats times");
for my $i (1..$numrepeats) {
for my $rule (keys %{$svrlastline{ $line{svr} }{rulematches} } ) {
logmsg (5, 3, "Applying cmd for rule $rule: $$cfghashref{rules}{$rule}{cmd} - as prelim regexs pass");
actionrule($cfghashref, $reshashref, $rule, \%{ $svrlastline{$line{svr} }{line} }); # if $actrule == 0;
}
}
} else {
logmsg (5, 2, "No recorded last line for $line{svr}") if $line{msg} =~ /message repeated/;
logmsg (9, 2, "msg: $line{msg}");
%{ $svrlastline{$line{svr} }{line} } = %line;
# track line
# track matching rule(s)
logmsg (3, 2, keys (%matches)." matches after checking all rules");
=cut
if (keys %rules > 0) {
#dep logmsg (5, 2, "svr & app & fac & msg matched rules: ");
logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmprules = %rules;
for my $rule (keys %tmprules) {
logmsg (9, 3, "checking rule: $rule");
delete $rules{$rule} unless actionrule(\%{ $$cfghashref{RULE} }, $reshashref, $rule, \%line);
# TODO: update &actionrule();
#unless $result ;
#$actrule = $result unless $actrule;
#dep logmsg (5, 3, "Applying cmds for rule $rule, as passed prelim regexes");
#dep logmsg (10, 4, "an action rule matched: $actrule");
}
#dep logmsg (10, 4, "an action rule matched: $actrule");
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
# HERE
# lastline & repeat
} # rules > 0
=dep
# now handled in action rules
%{$svrlastline{$line{svr} }{rulematches}} = %matches unless ($line{msg} =~ /last message repeated d+ times/);
logmsg (5, 2, "setting lastline match for server: $line{svr} and line:\n$line{line}");
logmsg (5, 3, "added matches for $line{svr} for rules:");
for my $key (keys %{$svrlastline{$line{svr} }{rulematches}}) {
logmsg (5, 4, "$key");
}
=cut
#dep logmsg (5, 3, "rules from line $line{line}");
if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
}
$lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
if ( keys(%rules) == 0) {
# Add new unmatched linescode
}
=dep
#} else {
logmsg (5, 2, "No match: $line{line}");
if ($svrlastline{$line{svr} }{unmatchedline}{msg} eq $line{msg} ) {
$svrlastline{$line{svr} }{unmatchedline}{count}++;
logmsg (9, 3, "$svrlastline{$line{svr} }{unmatchedline}{count} instances of msg: $line{msg} on $line{svr}");
} else {
$svrlastline{$line{svr} }{unmatchedline}{count} = 0 unless exists $svrlastline{$line{svr} }{unmatchedline}{count};
if ($svrlastline{$line{svr} }{unmatchedline}{msg} and $svrlastline{$line{svr} }{unmatchedline}{count} >= 1) {
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = "$line{svr}: Last unmatched message repeated $svrlastline{$line{svr} }{unmatchedline}{count} timesn";
} else {
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line};
$svrlastline{$line{svr} }{unmatchedline}{msg} = $line{msg};
}
$svrlastline{$line{svr} }{unmatchedline}{count} = 0;
}
logmsg (5, 2, "set unmatched{ $line{svr} }{msg} to $svrlastline{$line{svr} }{unmatchedline}{msg} and count to: $svrlastline{$line{svr} }{unmatchedline}{count}");
}
}
=cut
- logmsg (5, 1, "finished processing line");
+ logmsg(9 ,1, "Results hash ...".Dumper(%$reshashref) );
+ logmsg (5, 1, "finished processing line");
}
=does this segment need to be rewritten or depricated?
foreach my $server (keys %svrlastline) {
if ( $svrlastline{$server}{unmatchedline}{count} >= 1) {
logmsg (9, 2, "Added record #".( $#{$$reshashref{nomatch}} + 1 )." for unmatched results");
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = "$server: Last unmatched message repeated $svrlastline{$server }{unmatchedline}{count} timesn";
}
}
=cut
logmsg (1, 0, "Finished processing $logfile.");
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfile = shift;
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 5, "stanzatype: $stanzatype rulename:$rulename");
setaction(\@{ $$cfghashref{$stanzatype}{$rulename}{actions} }, \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
# Assume to be a match
$$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (5, 1, "Config Hash contents:");
&Dumper( %$cfghashref );
logmsg (1, 0, "finished processing cfg: $cfgfile");
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "args: $$argsref[2]");
unless (exists ${@$actionref}[0] ) {
logmsg(9, 3, "actions array, doesn't exist, initialising");
@$actionref = ();
}
my $actionindex = $#{ @$actionref } + 1;
logmsg(9, 3, "actionindex: $actionindex");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /count/i) {
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
}
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} else {
logmsg (1,0, "WARNING, unrecognised command ($$argsref[4]) in ACTION command");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp) {
$$actionref[$actionindex]{lastline} = 1;
}
$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "args: $$argsref[2]");
unless (exists ${@$reportref}[0] ) {
logmsg(9, 3, "report array, doesn't exist, initialising");
@$reportref = ();
}
my $reportindex = $#{ @$reportref } + 1;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
+ if ($$argsref[3]) {
+ $$reportref[$reportindex]{cmd} = $$argsref[3];
+ } else {
+ $$reportref[$reportindex]{cmd} = "count";
+ }
+
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
=obsolete
sub processformat {
my $cfghashref = shift;
my $rule = shift; # name of the rule to be processed
my $cmd = shift;
my $arg = shift;
#profile( whoami(), whowasi() );
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (5, 4, "Processing rule: $rule");
logmsg(9, 5, "passed cmd: $cmd");
logmsg(9, 5, "passed arg: $arg");
next unless $cmd;
for ($cmd) {
if (/DELIMITER/) {
$$cfghashref{delimiter} = $arg;
logmsg (5, 1, "Config Hash contents:");
&Dumper( %$cfghashref ) if $DEBUG >= 9;
} elsif (/FIELDS/) {
$$cfghashref{totalfields} = $arg;
for my $i(1..$$cfghashref{totalfields}) {
$$cfghashref{fields}{byindex}{$i} = "$i"; # map index to name
$$cfghashref{fields}{byname}{$i} = "$i"; # map name to index
}
} elsif (/FIELD(\d+)/) {
logmsg(6, 6, "FIELD#: $1 arg:$arg");
$$cfghashref{fields}{byindex}{$1} = "$arg"; # map index to name
$$cfghashref{fields}{byname}{$arg} = "$1"; # map name to index
if (exists($$cfghashref{fields}{byname}{$1}) ) {
delete($$cfghashref{fields}{byname}{$1});
}
} elsif (/DEFAULT/) {
$$cfghashref{default} = 1;
#} elsif (/REPEAT/) {
#TODO Define sub stanzas, it's currently hacked in
# extractcmd(\%{$$cfghashref{repeat}}, $cmd, "repeat", $arg);0
} elsif (/REGEX/) {
extractcmd(\%{$$cfghashref{repeat}}, $cmd, "regex", $arg);
} elsif (/FIELD/) {
$$cfghashref{repeat}{field} = $arg;
} elsif (/^\}$/) {
} elsif (/^\{$/) {
} else {
print "Error: $cmd didn't match any known fields\n\n";
} # if cmd
} # for cmd
logmsg (5, 4, "Finished processing rule: $rule");
} # sub processformat
sub processrule {
my $cfghashref = shift;
my $forhashref = shift; # ref to log format hash
my $cmd = shift;
my $arg = shift;
#profile( whoami(), whowasi() );
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (5, 4, "Processing $$cfghashref{name} with cmd: $cmd and arg: $arg");
logmsg (5, 5, "Format hash ...".Dumper(%$forhashref) );
next unless $cmd;
for ($cmd) {
# Static parameters
if (/FORMAT/){
# This really should be the first entry in a rule stanza if it's set
$$cfghashref{format} = $arg;
} elsif (/CMD/) {
extractcmd($cfghashref, $cmd, "cmd", $arg);
} elsif (/^REGEX/) {
extractcmd($cfghashref, $cmd, "regex", $arg);
} elsif (/MATCH/) {
extractcmd($cfghashref, $cmd, "matrix", $arg);
} elsif (/IGNORE/) {
extractcmd(\%{$$cfghashref{CMD}}, $cmd, "", $arg);
} elsif (/COUNT/) {
extractcmd(\%{$$cfghashref{CMD}}, $cmd, "", $arg);
} elsif (/SUM/) {
extractcmd(\%{$$cfghashref{CMD}}, $cmd, "targetfield", $arg);
} elsif (/AVG/) {
extractcmd(\%{$$cfghashref{CMD}}, $cmd, "targetfield", $arg);
} elsif (/TITLE/) {
$$cfghashref{RPT}{title} = $arg;
$$cfghashref{RPT}{title} = $1 if $$cfghashref{RPT}{title} =~ /^\"(.*)\"$/;
} elsif (/LINE/) {
$$cfghashref{RPT}{line} = $arg;
$$cfghashref{RPT}{line} = $1 if $$cfghashref{RPT}{line} =~ /\^"(.*)\"$/;
} elsif (/APPEND/) {
$$cfghashref{RPT}{appendrule} = $arg;
logmsg (1, 0, "*** Setting append for $$cfghashref{name} to $arg");
} elsif (/REPORT/) {
} elsif (/^\}$/) {
} elsif (/^\{$/) {
# Dynamic parameters (defined in FORMAT stanza)
} elsif (exists($$forhashref{fields}{byname}{$cmd} ) ) {
extractregex (\%{$$cfghashref{fields} }, $cmd, $arg);
# End Dynamic parameters
} else {
print "Error: $cmd didn't match any known fields\n\n";
}
} # for
logmsg (5, 1, "Finished processing rule: $$cfghashref{name}");
logmsg (9, 1, "Config hash after running processrule");
Dumper(%$cfghashref);
} # sub processrule
=cut
=obsolete?
sub extractcmd {
my $cfghashref = shift;
my $cmd = shift;
my $param = shift; # The activity associated with cmd
my $arg = shift; # The value for param
if ($param) {
extractregex ($cfghashref, "$param", $arg);
$$cfghashref{$param} =~ s/\s+//g; # strip all whitespace
}
$$cfghashref{cmd} = $cmd;
}
sub extractregexold {
# Keep the old behaviour
my $cfghashref = shift;
my $param = shift;
my $arg = shift;
# profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $paramnegat = $param."negate";
logmsg (5, 1, "rule: $$cfghashref{name} param: $param arg: $arg");
if ($arg =~ /^!/) {
$arg =~ s/^!//g;
$$cfghashref{$paramnegat} = 1;
} else {
$$cfghashref{$paramnegat} = 0;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^\{//;
$arg =~ s/\}$//;
$$cfghashref{$param} = $arg;
logmsg (5, 2, "$param = $$cfghashref{$param}");
}
sub extractregex {
# Put the matches into an array, but would need to change how we handle negates
# Currently the negate is assigned to match group (ie facility or host) or rather than
# an indivudal regex, not an issue immediately because we only support 1 regex
# Need to assign the negate to the regex
# Make the structure ...
# $$cfghashref{rules}{$rule}{$param}[$index] is a hash with {regex} and {negate}
my $cfghashref = shift;
my $param = shift;
my $arg = shift;
my $index = 0;
# profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
logmsg (1, 3, " rule: $$cfghashref{name} for param $param with arg $arg ");
#TODO {name} is null when called for sub stanzas such as CMD or REPEAT, causes an "uninitialised value" warning
if (exists $$cfghashref{$param}[0] ) {
$index = @{$$cfghashref{$param}};
} else {
$$cfghashref{$param} = ();
}
my $regex = \%{$$cfghashref{$param}[$index]};
$$regex{negate} = 0;
logmsg (5, 1, "$param $arg");
if ($arg =~ /^!/) {
$arg =~ s/^!//g;
$$regex{negate} = 1;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^{//;
$arg =~ s/}$//;
$$regex{regex} = $arg;
logmsg (9, 3, "$regex\{regex\} = $$regex{regex} & \$regex\{negate\} = $$regex{negate}");
logmsg (5,2, "$index = $index");
logmsg (5, 2, "$param \[$index\]\{regex\} = $$cfghashref{$param}[$index]{regex}");
logmsg (5, 2, "$param \[$index\]\{negate\} = $$cfghashref{$param}[$index]{negate}");
for (my $i=0; $i<=$index; $i++)
{
logmsg (5,1, "index: $i");
foreach my $key (keys %{$$cfghashref{$param}[$i]}) {
logmsg (5, 2, "$param \[$i\]\{$key\} = $$cfghashref{$param}[$i]{$key}");
}
}
}
=cut
sub report {
my $cfghashref = shift;
my $reshashref = shift;
my $rpthashref = shift;
logmsg(1, 0, "Ruuning report");
-# profile( whoami(), whowasi() );
logmsg (5, 0, " and I was called by ... ".&whowasi);
- logmsg(5, 1, "Dump of results hash ...");
- Dumper(%$reshashref) if $DEBUG >= 5;
+ logmsg(5, 1, "Dump of results hash ...".Dumper($reshashref));
print "\n\nNo match for lines:\n";
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
print "\n\nSummaries:\n";
- for my $rule (sort keys %$reshashref) {
+ for my $rule (sort keys %{ $$cfghashref{RULE} }) {
next if $rule =~ /nomatch/;
- if (exists ($$cfghashref{rules}{$rule}{rpttitle})) {
- print "$$cfghashref{rules}{$rule}{rpttitle}\n";
- } else {
- logmsg (4, 2, "Rule: $rule");
- }
-
- for my $key (keys %{$$reshashref{$rule}} ) {
- if (exists ($$cfghashref{rules}{$rule}{rptline})) {
- print "\t".rptline($cfghashref, $reshashref, $rpthashref, $rule, $key)."\n";
- } else {
- print "\t$$rpthashref{$rule}{$key}: $key\n";
- }
- }
- print "\n";
- }
+ my %ruleresults = summariseresults(\%{ $$cfghashref{RULE}{$rule} }, \%{ $$reshashref{$rule} });
+ logmsg (5, 2, "\%ruleresults ... ".Dumper(%ruleresults));
+ if (exists ($$cfghashref{RULE}{$rule}{reports} ) ) {
+ for my $rptid ($#{ $$cfghashref{RULE}{$rule}{reports} } ) {
+ logmsg (4, 1, "Rule: $rule\[$rptid\]");
+ if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{title} ) ) {
+ print "$$cfghashref{RULE}{$rule}{reports}[$rptid]{title}\n";
+ } else {
+ logmsg (4, 2, "No title");
+ }
+
+ for my $key (keys %ruleresults) {
+ logmsg (5, 3, "key:$key");
+ if (exists ($$cfghashref{RULE}{$rule}{reports}[$rptid]{line})) {
+ print "\t".rptline(\% {$$cfghashref{RULE}{$rule}{reports}[$rptid] }, \%{$ruleresults{$key} }, $rule, $rptid, $key)."\n";
+ } else {
+ print "\t$$reshashref{$rule}{$key}: $key\n";
+ }
+ }
+ print "\n";
+ } # for rptid
+ } # if reports in %cfghash{RULE}{$rule}
+ } # for rule in %reshashref
+} #sub
+
+sub summariseresults {
+ my $cfghashref = shift; # passed $cfghash{RULE}{$rule}{actions}
+ my $reshashref = shift; # passed $reshashref{$rule}
+ #my $rule = shift;
+ # loop through reshash for a given rule and combine the results of all the actions
+ # sum and count totals are summed together
+ # AVG is avg'd against the running total
+ # won't make sense if there are avg and sum/count actions, but this wouldn't make a lot of sense anyway
+ # returns a summarised hash
+
+ my %results;
+
+ for my $actionid (keys( %$reshashref ) ) {
+ for my $key (keys %{ $$reshashref{$actionid} } ) {
+ $results{$key}{count} += $$reshashref{$actionid}{$key}{count};
+ $results{$key}{total} += $$reshashref{$actionid}{$key}{total};
+ $results{$key}{avg} = $results{$key}{total} / $results{$key}{count};
+ } # for rule/actionid/key
+ } # for rule/actionid
+ return %results;
}
sub rptline {
- my $cfghashref = shift;
- my $reshashref = shift;
- my $rpthashref = shift;
+ my $cfghashref = shift; # %cfghash{RULE}{$rule}{reports}{$rptid}
+ my $reshashref = shift; # reshash{$rule}
+ #my $rpthashref = shift;
my $rule = shift;
+ my $rptid = shift;
my $key = shift;
- my $line = $$cfghashref{rules}{$rule}{rptline};
+ logmsg (5, 2, " and I was called by ... ".&whowasi);
+# logmsg (3, 2, "Starting with rule:$rule & report id:$rptid");
+ logmsg (9, 3, "key: $key");
+
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
+
+ logmsg (7, 3, "cfghash ... ".Dumper($cfghashref));
+ logmsg (7, 3, "reshash ... ".Dumper($reshashref));
+ my $line = $$cfghashref{line};
+ logmsg (7, 3, "report line: $line");
+
+ for ($$cfghashref{cmd}) {
+ if (/count/i) {
+ $line =~ s/\{x\}/$$reshashref{count}/;
+ logmsg(9, 3, "subsituting {x} with $$reshashref{count}");
+ } elsif (/SUM/i) {
+ $line =~ s/\{x\}/$$reshashref{total}/;
+ logmsg(9, 3, "subsituting {x} with $$reshashref{total}");
+ } elsif (/AVG/i) {
+ my $avg = $$reshashref{total} / $$reshashref{count};
+ $avg = sprintf ("%.3f", $avg);
+ $line =~ s/\{x\}/$avg/;
+ logmsg(9, 3, "subsituting {x} with $avg");
+ } else {
+ logmsg (1, 0, "WARNING: Unrecognized cmd ($$cfghashref{cmd}) for report #$rptid in rule ($rule)");
+ }
+ }
-# profile( whoami(), whowasi() );
- logmsg (5, 2, " and I was called by ... ".&whowasi);
- logmsg (3, 2, "Starting with rule:$rule");
- logmsg (9, 3, "key: $key");
my @fields = split /:/, $key;
-
- logmsg (9, 3, "line: $line");
- logmsg(9, 3, "subsituting {x} with $$rpthashref{$rule}{$key}{count}");
- $line =~ s/\{x\}/$$rpthashref{$rule}{$key}{count}/;
-
- if ($$cfghashref{rules}{$rule}{cmd} eq "SUM") {
- $line =~ s/\{s\}/$$rpthashref{$rule}{$key}{sum}/;
- }
- if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
- my $avg = $$rpthashref{$rule}{$key}{sum} / $$reshashref{$rule}{$key}{count};
- $avg = sprintf ("%.3f", $avg);
- $line =~ s/\{a\}/$avg/;
- }
-
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "$fields[$field] = $fields[$i]");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
+ logmsg (7, 3, "report line is now:$line");
return $line;
}
sub getmatchlist {
# given a match field, return 2 lists
# list 1: all fields in that list
# list 2: only numeric fields in the list
my $matchlist = shift;
my $numericonly = shift;
my @matrix = split (/,/, $matchlist);
if ($matchlist !~ /,/) {
push @matrix, $matchlist;
}
my @tmpmatrix = ();
for my $i (0 .. $#matrix) {
$matrix[$i] =~ s/\s+//g;
if ($matrix[$i] =~ /\d+/) {
push @tmpmatrix, $matrix[$i];
}
}
if ($numericonly) {
return @tmpmatrix;
} else {
return @matrix;
}
}
sub actionrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
# use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{RULES}{$rule} but would break append
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
# my $retvalue;
my $retval = 0;
#my $resultsrule;
logmsg (5, 1, " and I was called by ... ".&whowasi);
logmsg (6, 2, "rule: $rule called for $$line{line}");
logmsg (9, 3, ($#{ $$cfghashref{$rule}{actions} } + 1)." actions for rule: $rule");
for my $actionid ( 0 .. $#{ $$cfghashref{$rule}{actions} } ) {
logmsg (6, 2, "Actionid: $actionid");
# actionid needs to recorded in resultsref as well as ruleid
my @matrix = getmatchlist($$cfghashref{$rule}{actions}[$actionid]{matches}, 0);
my @tmpmatrix = getmatchlist($$cfghashref{$rule}{actions}[$actionid]{matches}, 1);
- logmsg (9, 4, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
+ logmsg (7, 4, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
my $matchid;
my @resmatrix = ();
no strict;
if ($$cfghashref{$rule}{actions}[$actionid]{regex} =~ /^\!/) {
my $regex = $$cfghashref{$rule}{actions}[$actionid]{regex};
- $regex =~ s/^!//;
+ $regex =~ s/^!//;
+ logmsg(8, 4, "negative regex - !$regex");
if ($$line{ $$cfghashref{$rule}{actions}[$actionid]{field} } !~ /$regex/ ) {
+ logmsg(8, 5, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,5, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{$rule}{actions}[$actionid]{matches}, $line);
$retvalue = 1;
}
- } else {
+ } else {
+ logmsg(8, 4, "Using regex - $$cfghashref{$rule}{actions}[$actionid]{regex}");
if ($$line{ $$cfghashref{$rule}{actions}[$actionid]{field} } =~ /$$cfghashref{$rule}{actions}[$actionid]{regex}/ ) {
+ logmsg(8, 5, "line matched regex");
for my $val (@tmpmatrix) {
push @resmatrix, ${$val};
logmsg (9,5, "Adding ${$val} (from match: $val) to matrix");
}
$matchid = populatematrix(\@resmatrix, $$cfghashref{$rule}{actions}[$actionid]{matches}, $line);
$retval = 1;
}
logmsg(6, 3, "matrix for $rule & actionid $actionid: @matrix & matchid $matchid");
}
use strict;
if ($matchid) {
+ $$reshashref{$rule}{$actionid}{$matchid}{total} += $resmatrix[ $$cfghashref{$rule}{actions}[$actionid]{sourcefield} ];
+ $$reshashref{$rule}{$actionid}{$matchid}{count}++;
for ($$cfghashref{$rule}{actions}[$actionid]{cmd}) {
- if (/sum/) {
- $$reshashref{$rule}{$actionid}{$matchid} += $resmatrix[ $$cfghashref{$rule}{actions}[$actionid]{sourcefield} ];
- } elsif (/count/) {
- $$reshashref{$rule}{$actionid}{$matchid}++;
- } elsif (/append/) {
+ if (/append/i) {
} else {
- logmsg (1, 0, "Warning: unfrecognized cmd ($$cfghashref{$rule}{actions}[$actionid]{cmd}) in action ($actionid) for rule: $rule");
+ logmsg (1, 0, "Warning: unrecognized cmd ($$cfghashref{$rule}{actions}[$actionid]{cmd}) in action ($actionid) for rule: $rule");
}
}
+ } else {
+ logmsg (3, 5, "No matchid");
}
}
logmsg (7, 5, "\%reshash ...".Dumper($reshashref));
return $retval;
}
sub populatematrix {
#my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{RULES}{$rule} but would break append
#my $reshashref = shift;
my $resmatrixref = shift;
my $matchlist = shift;
my $lineref = shift; # hash passed by ref, DO NOT mod
my $matchid;
logmsg (9, 5, "\@resmatrix ... ".Dumper($resmatrixref) );
my @matrix = getmatchlist($matchlist, 0);
my @tmpmatrix = getmatchlist($matchlist, 1);
logmsg (9, 6, "\@matrix ..".Dumper(@matrix));
logmsg (9, 6, "\@tmpmatrix ..".Dumper(@tmpmatrix));
my $tmpcount = 0;
for my $i (0 .. $#matrix) {
logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
if ($matrix[$i] =~ /\d+/) {
#$matrix[$i] =~ s/\s+$//;
$matchid .= ":".$$resmatrixref[$tmpcount];
$matchid =~ s/\s+$//g;
logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
$tmpcount++;
} else {
$matchid .= ":".$$lineref{ $matrix[$i] };
logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
}
}
$matchid =~ s/^://; # remove leading :
logmsg (6, 4, "Got matchid: $matchid");
return $matchid;
}
=depricate
sub actionrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
# returns 0 if unable to apply rule, else returns 1 (success)
my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{rules}{$rule} but would break append
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $value;
my $retval = 0; my $resultsrule;
# profile( whoami(), whowasi() );
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg (9, 2, "rule: $rule");
if (exists ($$cfghashref{rules}{$rule}{appendrule})) {
$resultsrule = $$cfghashref{rules}{$rule}{appendrule};
} else {
$resultsrule = $rule;
}
unless ($$cfghashref{rules}{cmdregex}) {
$$cfghashref{rules}{cmdregex} = "";
}
logmsg (5, 3, "rule: $rule");
logmsg (5, 4, "results goto: $resultsrule");
logmsg (5, 4, "cmdregex: $$cfghashref{rules}{cmdregex}");
logmsg (5, 4, "CMD negative regex: $$cfghashref{rules}{$rule}{cmdregexnegat}");
logmsg (5, 4, "line: $$line{line}");
if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /IGNORE/) {
if (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "rule $rule does matches and is a positive IGNORE rule");
}
} else {
logmsg (5, 4, "rule $rule matches and is an IGNORE rule");
$retval = 1;
}
} elsif (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
if ( not $$cfghashref{rules}{$rule}{cmdregexnegat} ) {
if ( $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "Positive match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
} elsif ($$cfghashref{rules}{$rule}{cmdregexnegat}) {
if ( $$line{line} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "Negative match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
}
} else {
logmsg (5, 4, "No cmd regex, implicit match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
if ($retval == 0) {
logmsg (5, 4, "line does not match cmdregex for rule: $rule");
}
return $retval;
}
=cut
=depricate
sub actionrulecmd
{
my $cfghashref = shift;
my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift;
my $resultsrule = shift;
#3 profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
logmsg (2, 2, "actioning rule $rule for line: $$line{line}");
# This sub contains the first half of the black magic
# The results from the regex's that are applied later
# are used in actioncmdmatrix()
#
# create a matrix that can be used for matching for the black magic happens
# Instead of the string cmdmatrix
# make a hash of matchmatrix{<match field#>} = <cmdregex field #>
# 2 arrays ...
# fieldnums ... the <match field #'s> of matchmatrix{}
# fieldnames ... the named matches of matchmatrix{}, these match back to the names of the fields
# from the file FORMAT
#
my @tmpmatrix = split (/,/, $$cfghashref{rules}{$rule}{cmdmatrix});
my @matrix = ();
for my $val (@tmpmatrix) {
if ($val =~ /(\d+)/ ) {
push @matrix, $val;
} else {
logmsg(3,3, "Not adding val:$val to matrix");
}
}
logmsg(3, 3, "matrix: @matrix");
#
if (not $$cfghashref{rules}{$rule}{cmdregex}) {
$$cfghashref{rules}{$rule}{cmdregex} = "(.*)";
logmsg (5, 3, "rule did not define cmdregex, replacing with global match");
}
if ( exists $$cfghashref{rules}{$rule}{cmd}) {
logmsg (5, 3, "Collecting data from cmd $$cfghashref{rules}{$rule}{cmd}");
logmsg (5, 3, "rule $rule matches cmd") if $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/;
}
if (not exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
logmsg (5, 3, "No cmd regex, calling actioncmdmatrix");
actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
} elsif ($$cfghashref{rules}{$rule}{cmdregexnegat} ) {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 3, "Negative match, calling actioncmdmatrix");
actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
}
} else {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 3, "Positive match, calling actioncmdmatrixnline hash:");
print Dumper($line) if $DEBUG >= 5;
actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
}
}
}
sub printhash
{
# profile( whoami(), whowasi() );
my $line = shift; # hash passed by ref, DO NOT mod
foreach my $key (keys %{ $line} )
{
logmsg (9, 5, "$key: $$line{$key}");
}
}
sub actioncmdmatrix
{
my $cfghashref = shift;
my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift; # Name or ID of rule thats been matched
my $resultsrule = shift; # Name or ID of rule which contains the result set to be updated
my $matrixref = shift; # arrayref
logmsg(5, 4, " ... actioning resultsrule = $rule");
logmsg(5, 5, " and I was called by ... ".&whowasi);
logmsg(9, 5, "Line hash ...");
print Dumper(%$line);
#profile( whoami(), whowasi() );
my $cmdmatrix = $$cfghashref{rules}{$rule}{cmdmatrix};
#my @matrix = shift; #split (/,/, $cmdmatrix);
my $fieldhash;
my $cmdfield;
# @matrix - array of parameters that are used in results
if ( exists ($$cfghashref{rules}{$rule}{cmdfield}) ) {
$cmdfield = ${$$cfghashref{rules}{$rule}{cmdfield}};
}
if ( exists $$cfghashref{rules}{$rule}{cmdmatrix}) {
logmsg (5, 5, "Collecting data for matrix $$cfghashref{rules}{$rule}{cmdmatrix}");
print Dumper(@$matrixref);
logmsg (5, 5, "Using matrix @$matrixref");
# this is where "strict refs" breaks things
# sample: @matrix = svr,1,4,5
# error ... can't use string ("svr") as a SCALAR ref while "strict refs" in use
#
# soln: create a temp array which only has the field #'s and match that
# might need a hash to match
no strict 'refs'; # turn strict refs off just for this section
foreach my $field (@$matrixref) {
# This is were the black magic occurs, ${$field} causes becomes $1 or $2 etc
# and hence contains the various matches from the previous regex match
# which occured just before this function was called
logmsg (9, 5, "matrix field $field has value ${$field}");
if (exists $$line{$field}) {
if ($fieldhash) {
$fieldhash = "$fieldhash:$$line{$field}";
} else {
$fieldhash = "$$line{$field}";
}
} else {
if ($fieldhash) {
$fieldhash = "$fieldhash:${$field}";
} else {
if ( ${$field} ) {
$fieldhash = "${$field}";
} else {
logmsg (1, 6, "$field not found in \"$$line{line}\" with regex $$cfghashref{rules}{$rule}{cmdregex}");
logmsg (1, 6, "line hash:");
print Dumper(%$line) if $DEBUG >= 1;
}
}
}
}
use strict 'refs';
if ($$cfghashref{rules}{$rule}{targetfield}) {
logmsg (1, 5, "Setting cmdfield (field $$cfghashref{rules}{$rule}{targetfield}) to ${$$cfghashref{rules}{$rule}{targetfield}}");
$cmdfield = ${$$cfghashref{rules}{$rule}{targetfield}};
}
#if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
$$reshashref{$resultsrule}{$fieldhash}{count}++;
logmsg (5, 5, "$$reshashref{$resultsrule}{$fieldhash}{count} matches for rule $rule so far from $fieldhash");
#} els
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
$$reshashref{$resultsrule}{$fieldhash}{sum} = $$reshashref{$resultsrule}{$fieldhash}{sum} + $cmdfield;
logmsg (5, 5, "Adding $cmdfield to total (now $$reshashref{$resultsrule}{$fieldhash}{sum}) for rule $rule so far from $fieldhash");
if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
logmsg (5, 5, "Average is ".$$reshashref{$resultsrule}{$fieldhash}{sum} / $$reshashref{$resultsrule}{$fieldhash}{count}." for rule $rule so far from $fieldhash");
}
}
for my $key (keys %{$$reshashref{$resultsrule}}) {
logmsg (5, 5, "key $key for rule:$rule with $$reshashref{$resultsrule}{$key}{count} matches");
}
logmsg (5, 5, "$fieldhash matches for rule $rule so far from matrix: $$cfghashref{rules}{$rule}{cmdmatrix}");
} else {
logmsg (5, 5, "cmdmatrix is not set for $rule");
#if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
$$reshashref{$resultsrule}{count}++;
logmsg (5, 5, "$$reshashref{$resultsrule}{count} lines match rule $rule so far");
# } els
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
$$reshashref{$resultsrule}{sum} = $$reshashref{$resultsrule}{sum} + $cmdfield;
logmsg (5, 5, "$$reshashref{$resultsrule}{sum} lines match rule $rule so far");
}
}
logmsg(5, 4, " ... Finished actioning resultsrule = $rule");
}
=cut
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
sub matchrules {
my $cfghashref = shift;
my $linehashref = shift;
# loops through the rules and calls matchfield for each rule
# assumes cfghashref{RULE} has been passed
# returns a list of matching rules
my %rules;
for my $rule (keys %{ $cfghashref } ) {
$rules{$rule} = $rule if matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref);
}
return %rules;
}
sub matchfields {
my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
my $linehashref = shift;
my $ret = 1;
# Assume fields match.
# Only fail if a field doesn't match.
# Passed a cfghashref to a rule
foreach my $field (keys (%{ $cfghashref } ) ) {
if ($$cfghashref{fields}{$field} =~ /^!/) {
my $exp = $$cfghashref{fields}{$field};
$exp =~ s/^\!//;
$ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
} else {
$ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{fields}{$field}/);
}
}
return $ret;
}
sub matchingrules {
my $cfghashref = shift;
my $param = shift;
my $matchref = shift;
my $value = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 3, "param:$param");
logmsg (6, 3, "value:$value") if $value;
logmsg (3, 2, "$param, match count: ".keys(%{$matchref}) );
if (keys %{$matchref} == 0) {
# Check all rules as we haevn't had a match yet
foreach my $rule (keys %{$cfghashref->{rules} } ) {
checkrule($cfghashref, $param, $matchref, $rule, $value);
}
} else {
# As we've allready had a match on the rules, only check those that matched in earlier rounds
# key in %matches is the rule that matches
foreach my $rule (keys %{$matchref}) {
checkrule($cfghashref, $param, $matchref, $rule, $value);
}
}
}
sub checkrule {
my $cfghashref = shift;
my $param = shift;
my $matches = shift;
my $rule = shift; # key to %matches
my $value = shift;
logmsg(2, 1, "Checking rule ($rule) & param ($param) for matches against: $value");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $paramref = \@{ $$cfghashref{rules}{$rule}{$param} };
defaultregex($paramref); # This should be done when reading the config
foreach my $index (@{ $paramref } ) {
my $match = matchregex($index, $value);
if ($$index{negate} ) {
if ( $match) {
delete $$matches{$rule};
logmsg (5, 5, "matches $index->{regex} for param \'$param\', but negative rule is set, so removing rule $match from list.");
} else {
$$matches{$rule} = "match" if $match;
logmsg (5, 5, "Doesn't match for $index->{regex} for param \'$param\', but negative rule is set, so leaving rule $match on list.");
}
} elsif ($match) {
$$matches{$rule} = "match" if $match;
logmsg (5, 4, "matches $index->{regex} for param \'$param\', leaving rule $match on list.");
} else {
delete $$matches{$rule};
logmsg (5, 4, "doesn't match $index->{regex} for param \'$param\', removing rule $match from list.");
}
} # for each regex hash in the array
logmsg (3, 2, "matches ".keys (%{$matches})." matches after checking rules for $param");
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
if ($DEBUG >= $level) {
for my $i (0..$indent) {
print STDERR " ";
}
print STDERR whowasi."(): $msg\n";
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
|
mikeknox/LogParse | 2d844095938ff43003c59dbd25dbaf75caaa6caf | initial rewrite of action processing for count and sum finished. append still needs to be rewritten. then it's onto the report function. | diff --git a/logparse.conf b/logparse.conf
index 14c2ad9..385ab55 100644
--- a/logparse.conf
+++ b/logparse.conf
@@ -1,78 +1,78 @@
# Describe config file for log parse / summary engine
#
#
# FORMAT <name> {
# DELIMITER <xyz>
# FIELDS <x>
# FIELD<x> <name>
#}
FORMAT dummy {
DELIMITER \t
FIELDS 2
FIELD1 abc
FIELD2 def
}
# Need to redefine the language structure for the config file
# there are a lot of different commands, and the language needs to be formalised
# to make it easier to automate
# Current only support logical ops AND and NOT, need to add grouping and OR
# Also being able to use LASTLINE in rules would be neat, especially against HOSTS different to current
# Need to track which FIELD the lastline should be indexed against
# eg in consolidated logfiles, last line would be indexed on HOST
# also need to handle the scenario that last line is a continued line?
# Structure definition ...
#########
FORMAT syslog {
# FIELDS <field count> <delimiter>
# FIELDS <field count> <delimiter> [<parent field>]
# FIELD <field id #> <label>
# FIELD <parent field id#>-<child field id#> <label>
FIELDS 6 "\s+"
FIELD 1 MONTH
FIELD 2 DAY
FIELD 3 TIME
FIELD 4 HOST
FIELD 5 APP
FIELD 6 FULLMSG
FIELDS 6-2 /]\s+/
FIELD 6-1 FACILITY
FIELD 6-2 MSG default
LASTLINEINDEX HOST
# LASTLINE <field label> # field to be used as index for "last line", also need to track rule matches for last line
# default format to be used for log file analysis
DEFAULT
# ACTION <field> </regex/> <{matches}> sum <{sum field}>
- ACTION MSG /^message repeated (.*) times/ {1} sum {1}
+ #ACTION MSG /^message repeated (.*) times/ {1} sum {1}
# Apply {1} as {x} in the previously applied rule for HOST
- ACTION MSG /^message repeated$/ count
+ #ACTION MSG /^message repeated$/ count
}
RULE {
MSG /^message repeated (.*) times/ OR /^message repeated$/
ACTION MSG /^message repeated (.*) times/ {1} sum {1} append LASTLINE
# Apply {1} as {x} in the previously applied rule for HOST
ACTION MSG /^message repeated$/ count append LASTLINE
}
RULE sudo {
APP sudo
MSG /.* : .* ; PWD=/
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
}
#######################
#2
diff --git a/logparse.pl b/logparse.pl
index 4d50db1..160721e 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,1247 +1,1436 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=pod
=head1 logparse - syslog analysis tool
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
=head1 Config file language description
This is a complete redefine of the language from v0.1 and includes some major syntax changes.
It was originally envisioned that it would be backwards compatible, but it won't be due to new requirements
such as adding OR operations
=head3 Stanzas
The building block of this config file is the stanza which indicated by a pair of braces
<Type> [<label>] {
# if label isn't declared, integer ID which autoincrements
}
There are 2 top level stanza types ...
- FORMAT
- doesn't need to be named, but if using multiple formats you should.
- RULE
=head2 FORMAT stanza
=over
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=back
=cut
=head3 Parameters
[LASTLINE] <label> [<value>]
=item Parameters occur within stanza's.
=item labels are assumed to be field matches unless they are known commands
=item a parameter can have multiple values
=item the values for a parameter are whitespace delimited, but fields are contained by /<some text>/ or {<some text}
=item " ", / / & { } define a single field which may contain whitespace
=item any field matches are by default AND'd together
=item multiple ACTION commands are applied in sequence, but are independent
=item multiple REPORT commands are applied in sequence, but are independent
- LASTLINE
- Applies the field match or action to the previous line, rather than the current line
- This means it would be possible to create configs which double count entries, this wouldn't be a good idea.
=head4 Known commands
These are labels which have a specific meaning.
REPORT <title> <line>
ACTION <field> </regex/> <{matches}> <command> [<command specific fields>] [LASTLINE]
ACTION <field> </regex/> <{matches}> sum <{sum field}> [LASTLINE]
ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
=head4 Action commands
data for the actions are stored according to <{matches}>, so <{matches}> defines the unique combination of datapoints upon which any action is taken.
- Ignore
- Count - Increment the running total for the rule for the set of <{matches}> by 1.
- Sum - Add the value of the field <{sum field}> from the regex match to the running total for the set of <{matches}>
- Append - Add the set of values <{matches}> to the results for rule <rule> according to the field layout described by <{field transformation}>
- LASTLINE - Increment the {x} parameter (by <sum field> or 1) of the rules that were matched by the LASTLINE (LASTLINE is determined in the FORMAT stanza)
=head3 Conventions
regexes are written as / ... / or /! ... /
/! ... / implies a negative match to the regex
matches are written as { a, b, c } where a, b and c match to fields in the regex
=head1 Internal structures
=over
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=back
=head1 BUGS:
See http://github.com/mikeknox/LogParse/issues
=cut
# expects data on std in
use strict;
use Getopt::Std;
use Data::Dumper qw(Dumper);
# Globals
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my $CONFIGFILE="logparse.conf";
my %cfghash;
my %reshash;
my $UNMATCHEDLINES = 1;
my $SYSLOGFILE = "/var/log/messages";
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
getopt('cdl', \%opts);
$DEBUG = $opts{d} if $opts{d};
$CONFIGFILE = $opts{c} if $opts{c};
$SYSLOGFILE = $opts{l} if $opts{l};
loadcfg (\%cfghash, $CONFIGFILE);
print Dumper(\%cfghash);
processlogfile(\%cfghash, \%reshash, $SYSLOGFILE);
#report(\%cfghash, \%reshash);
#profilereport();
exit 0;
sub parselogline {
=head5 pareseline(\%cfghashref, $text, \%linehashref)
=cut
my $cfghashref = shift;
my $text = shift;
my $linehashref = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg(6, 4, "Text: $text");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
my @tmp;
logmsg (6, 4, "delimiter: $$cfghashref{delimiter}");
logmsg (6, 4, "totalfields: $$cfghashref{totalfields}");
+ logmsg (6, 4, "defaultfield: $$cfghashref{defaultfield} ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })") if exists ($$cfghashref{defaultfield});
# if delimiter is not present and default field is set
- # assign text to default field
- # else
- (@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
+ if ($text !~ /$$cfghashref{delimiter}/ and $$cfghashref{defaultfield}) {
+ logmsg (5, 4, "\$text doesnot contain $$cfghashref{delimiter} and default of field $$cfghashref{defaultfield} is set, so assigning all of \$text to that field ($$cfghashref{byindex}{ $$cfghashref{defaultfield} })");
+ $$linehashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } = $text;
+ if (exists($$cfghashref{ $$cfghashref{byindex}{ $$cfghashref{defaultfield} } } ) ) {
+ logmsg(9, 4, "Recurisive call for field ($$cfghashref{default}) with text $text");
+ parselogline(\%{ $$cfghashref{ $$cfghashref{defaultfield} } }, $text, $linehashref);
+ }
+ } else {
+ (@tmp) = split (/$$cfghashref{delimiter}/, $text, $$cfghashref{totalfields});
- logmsg (9, 4, "Got field values ... ".Dumper(@tmp));
- for (my $i = 0; $i <= $#tmp+1; $i++) {
- $$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
- logmsg(9, 4, "Checking field $i(".($i+1).")");
- if (exists($$cfghashref{$i + 1} ) ) {
- logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
- parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
+ logmsg (9, 4, "Got field values ... ".Dumper(@tmp));
+ for (my $i = 0; $i <= $#tmp+1; $i++) {
+ $$linehashref{ $$cfghashref{byindex}{$i} } = $tmp[$i];
+ logmsg(9, 4, "Checking field $i(".($i+1).")");
+ if (exists($$cfghashref{$i + 1} ) ) {
+ logmsg(9, 4, "Recurisive call for field $i(".($i+1).") with text $text");
+ parselogline(\%{ $$cfghashref{$i + 1} }, $tmp[$i], $linehashref);
+ }
}
}
logmsg (9, 4, "line results now ...".Dumper($linehashref));
}
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfile = shift;
my $format = $$cfghashref{FORMAT}{default}; # TODO - make dynamic
+ my %lastline;
logmsg(1, 0, "processing $logfile using format $format...");
logmsg(5, 1, " and I was called by ... ".&whowasi);
open (LOGFILE, "<$logfile") or die "Unable to open $SYSLOGFILE for reading...";
while (<LOGFILE>) {
my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
logmsg(5, 1, "Processing next line");
logmsg(9, 2, "Delimiter: $$cfghashref{FORMAT}{ $format }{fields}{delimiter}");
logmsg(9, 2, "totalfields: $$cfghashref{FORMAT}{$format}{fields}{totalfields}");
#@{$line{fields}} = split(/$$cfghashref{FORMAT}{ $format }{fields}{delimiter}/, $line{line}, $$cfghashref{FORMAT}{$format}{fields}{totalfields} );
parselogline(\%{ $$cfghashref{FORMAT}{$format}{fields} }, $line{line}, \%line);
#($line{mth}, $line{date}, $line{time}, $line{svr}, $line{app}, $line{msg}) = split (/\s+/, $line{line}, 6);
# logmsg(9, 2, "mth: $line{mth}, date: $line{date}, time: $line{time}, svr: $line{svr}, app: $line{app}, msg: $line{msg}");
logmsg(9, 1, "Checking line: $line{line}");
logmsg(9, 2, "Extracted Field contents ...\n".Dumper(@{$line{fields}}));
- #logmsg(9, 1, "Checking line: $line{line}");
- #logmsg(9, 1, "msg: $line{msg}");
-#TODO - add subfield functionality
-=replace
- if ($line{msg} =~ /^\[/) {
- ($line{facility}, $line{msg}) = split (/]\s+/, $line{msg}, 2);
- $line{facility} =~ s/\[//;
- logmsg(9, 1, "facility: $line{facility}");
- }
-=cut
-#TODO These need to be abstracted out per description in the FORMAT stanza
- my %matches;
-
+ my %rules = matchrules(\%{ $$cfghashref{RULE} }, \%line );
# my %matchregex = ("svrregex", "svr", "appregex", "app", "facregex", "facility", "msgregex", "line");
- for my $field (keys %{$$cfghashref{formats}{$format}{fields}{byname} }) {
- matchingrules($cfghashref, $field, \%matches, $line{ $field } );
- }
+# for my $field (keys %{$$cfghashref{formats}{$format}{fields}{byname} }) {
+# matchingrules($cfghashref, $field, \%matches, $line{ $field } );
+# }
###matchingrules($cfghashref, $param, \%matches, $line{ $matchregex{$param} } );
#}
- logmsg(9, 2, keys(%matches)." matches so far");
- $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} and next unless keys %matches > 0;
- logmsg(9,1,"Results hash ...");
- Dumper(%$reshashref);
+ logmsg(9, 2, keys (%rules)." matches so far");
+ $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} and next unless keys(%rules) > 0;
+ logmsg(9,1,"Results hash ...".Dumper(%$reshashref) );
#TODO Handle "Message repeated" type scenarios when we don't know which field should contatin the msg
#UP to here
# FORMAT stanza contains a substanza which describes repeat for the given format
# format{repeat}{cmd} - normally regex, not sure what other solutions would apply
# format{repeat}{regex} - array of regex's hashes
# format{repeat}{field} - the name of the field to apply the cmd (normally regex) to
#TODO describe matching of multiple fields ie in syslog we want to match regex and also ensure that HOST matches previous previousline
# Detect and count repeats
+=replace with repeat rule
if ( exists( $$cfghashref{formats}{$format}{repeat} ) ) {
my $repeatref = \%{$$cfghashref{formats}{$format}{repeat} };
if ($$repeatref{cmd} =~ /REGEX/ ) {
foreach my $i (@{$$repeatref{regex}}) {
if ($line{$$repeatref{field}} =~ /$$repeatref{regex}[$i]{regex}/) {
}
}
}
}
-
+
if ($line{msg} =~ /message repeated/ and exists $svrlastline{$line{svr} }{line}{msg} ) { # and keys %{$svrlastline{ $line{svr} }{rulematches}} ) {
logmsg (9, 2, "last message repeated and matching svr line");
my $numrepeats = 0;
if ($line{msg} =~ /message repeated (.*) times/) {
$numrepeats = $1;
}
logmsg(9, 2, "Last message repeated $numrepeats times");
for my $i (1..$numrepeats) {
for my $rule (keys %{$svrlastline{ $line{svr} }{rulematches} } ) {
logmsg (5, 3, "Applying cmd for rule $rule: $$cfghashref{rules}{$rule}{cmd} - as prelim regexs pass");
actionrule($cfghashref, $reshashref, $rule, \%{ $svrlastline{$line{svr} }{line} }); # if $actrule == 0;
}
}
+
} else {
logmsg (5, 2, "No recorded last line for $line{svr}") if $line{msg} =~ /message repeated/;
logmsg (9, 2, "msg: $line{msg}");
%{ $svrlastline{$line{svr} }{line} } = %line;
# track line
# track matching rule(s)
logmsg (3, 2, keys (%matches)." matches after checking all rules");
-
- if (keys %matches > 0) {
- logmsg (5, 2, "svr & app & fac & msg matched rules: ");
- logmsg (5, 2, "matched rules ".keys(%matches)." from line $line{line}");
+=cut
+ if (keys %rules > 0) {
+#dep logmsg (5, 2, "svr & app & fac & msg matched rules: ");
+ logmsg (5, 2, "matched ".keys(%rules)." rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
- my %tmpmatches = %matches;
- for my $rule (keys %tmpmatches) {
- my $result = actionrule($cfghashref, $reshashref, $rule, \%line);
- delete $matches{$rule} unless $result ;
- $actrule = $result unless $actrule;
- logmsg (5, 3, "Applying cmd from rule $rule: $$cfghashref{rules}{$rule}{cmd} as passed prelim regexes");
- logmsg (10, 4, "an action rule matched: $actrule");
+ my %tmprules = %rules;
+ for my $rule (keys %tmprules) {
+ logmsg (9, 3, "checking rule: $rule");
+ delete $rules{$rule} unless actionrule(\%{ $$cfghashref{RULE} }, $reshashref, $rule, \%line);
+ # TODO: update &actionrule();
+ #unless $result ;
+ #$actrule = $result unless $actrule;
+#dep logmsg (5, 3, "Applying cmds for rule $rule, as passed prelim regexes");
+#dep logmsg (10, 4, "an action rule matched: $actrule");
}
- logmsg (10, 4, "an action rule matched: $actrule");
- $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if $actrule == 0;
+#dep logmsg (10, 4, "an action rule matched: $actrule");
+ $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if keys(%rules) == 0;
+ # HERE
+ # lastline & repeat
+ } # rules > 0
+=dep
+# now handled in action rules
%{$svrlastline{$line{svr} }{rulematches}} = %matches unless ($line{msg} =~ /last message repeated d+ times/);
logmsg (5, 2, "setting lastline match for server: $line{svr} and line:\n$line{line}");
logmsg (5, 3, "added matches for $line{svr} for rules:");
for my $key (keys %{$svrlastline{$line{svr} }{rulematches}}) {
logmsg (5, 4, "$key");
}
- logmsg (5, 3, "rules from line $line{line}");
- } else {
+=cut
+#dep logmsg (5, 3, "rules from line $line{line}");
+ if (exists( $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } ) ) {
+ delete ($lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } });
+ }
+ $lastline{ $line{ $$cfghashref{FORMAT}{$format}{LASTLINEINDEX} } } = %line;
+
+ if ( keys(%rules) == 0) {
+ # Add new unmatched linescode
+ }
+=dep
+ #} else {
logmsg (5, 2, "No match: $line{line}");
if ($svrlastline{$line{svr} }{unmatchedline}{msg} eq $line{msg} ) {
$svrlastline{$line{svr} }{unmatchedline}{count}++;
logmsg (9, 3, "$svrlastline{$line{svr} }{unmatchedline}{count} instances of msg: $line{msg} on $line{svr}");
} else {
$svrlastline{$line{svr} }{unmatchedline}{count} = 0 unless exists $svrlastline{$line{svr} }{unmatchedline}{count};
if ($svrlastline{$line{svr} }{unmatchedline}{msg} and $svrlastline{$line{svr} }{unmatchedline}{count} >= 1) {
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = "$line{svr}: Last unmatched message repeated $svrlastline{$line{svr} }{unmatchedline}{count} timesn";
} else {
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line};
$svrlastline{$line{svr} }{unmatchedline}{msg} = $line{msg};
}
$svrlastline{$line{svr} }{unmatchedline}{count} = 0;
}
logmsg (5, 2, "set unmatched{ $line{svr} }{msg} to $svrlastline{$line{svr} }{unmatchedline}{msg} and count to: $svrlastline{$line{svr} }{unmatchedline}{count}");
}
}
+=cut
logmsg (5, 1, "finished processing line");
- }
-
+ }
+=does this segment need to be rewritten or depricated?
foreach my $server (keys %svrlastline) {
if ( $svrlastline{$server}{unmatchedline}{count} >= 1) {
logmsg (9, 2, "Added record #".( $#{$$reshashref{nomatch}} + 1 )." for unmatched results");
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = "$server: Last unmatched message repeated $svrlastline{$server }{unmatchedline}{count} timesn";
}
}
+=cut
logmsg (1, 0, "Finished processing $logfile.");
}
sub getparameter {
=head6 getparamter($line)
returns array of line elements
lines are whitespace delimited, except when contained within " ", {} or //
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
chomp $line;
logmsg (9, 5, "passed $line");
my @A;
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line =~ s/#.*$//; # strip anything after #
#$line =~ s/{.*?$//; # strip trail {, it was required in old format
@A = $line =~ /(\/.+?\/|\{.+?\}|".+?"|\S+)/g;
}
for (my $i = 0; $i <= $#A; $i++ ) {
logmsg (9, 5, "\$A[$i] is $A[$i]");
# Strip any leading or trailing //, {}, or "" from the fields
$A[$i] =~ s/^(\"|\/|{)//;
$A[$i] =~ s/(\"|\/|})$//;
logmsg (9, 5, "$A[$i] has had the leading \" removed");
}
logmsg (9, 5, "returning @A");
return @A;
}
sub parsecfgline {
=head6 parsecfgline($line)
Depricated, use getparameter()
takes line as arg, and returns array of cmd and value (arg)
=cut
my $line = shift;
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|^\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
sub loadcfg {
=head6 loadcfg(<cfghashref>, <cfgfile name>)
Load cfg loads the config file into the config hash, which it is passed as a ref.
loop through the logfile
- skip any lines that only contain comments or whitespace
- strip any comments and whitespace off the ends of lines
- if a RULE or FORMAT stanza starts, determine the name
- if in a RULE or FORMAT stanza pass any subsequent lines to the relevant parsing subroutine.
- brace counts are used to determine whether we've finished a stanza
=cut
my $cfghashref = shift;
my $cfgfile = shift;
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rulename = -1;
my $ruleid = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "stanzatype:$stanzatype ruleid:$ruleid rulename:$rulename");
my @args = getparameter($line);
next unless $args[0];
logmsg(6, 2, "line parameters: @args");
for ($args[0]) {
if (/RULE|FORMAT/) {
$stanzatype=$args[0];
if ($args[1] and $args[1] !~ /\{/) {
$rulename = $args[1];
logmsg(9, 3, "rule (if) is now: $rulename");
} else {
$rulename = $ruleid++;
logmsg(9, 3, "rule (else) is now: $rulename");
} # if arg
$$cfghashref{$stanzatype}{$rulename}{name}=$rulename; # setting so we can get name later from the sub hash
unless (exists $$cfghashref{FORMAT}) {
logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
exit 2;
}
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rulename");
} elsif (/FIELDS/) {
fieldbasics(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/FIELD$/) {
fieldindex(\%{ $$cfghashref{$stanzatype}{$rulename}{fields} }, \@args);
} elsif (/DEFAULT/) {
$$cfghashref{$stanzatype}{$rulename}{default} = 1;
$$cfghashref{$stanzatype}{default} = $rulename;
} elsif (/LASTLINEINDEX/) {
$$cfghashref{$stanzatype}{$rulename}{LASTLINEINDEX} = $args[1];
} elsif (/ACTION/) {
logmsg(9, 5, "stanzatype: $stanzatype rulename:$rulename");
setaction(\@{ $$cfghashref{$stanzatype}{$rulename}{actions} }, \@args);
} elsif (/REPORT/) {
setreport(\@{ $$cfghashref{$stanzatype}{$rulename}{reports} }, \@args);
} else {
- # Assume to be a match
+ # Assume to be a match
+ $$cfghashref{$stanzatype}{$rulename}{fields}{$args[0]} = $args[1];
}# if cmd
} # for cmd
} # while
close CFGFILE;
logmsg (5, 1, "Config Hash contents:");
&Dumper( %$cfghashref );
logmsg (1, 0, "finished processing cfg: $cfgfile");
} # sub loadcfg
sub setaction {
=head6 setaction ($cfghasref, @args)
where cfghashref should be a reference to the action entry for the rule
sample
ACTION MSG /(.*): TTY=(.*) ; PWD=(.*); USER=(.*); COMMAND=(.*)/ {HOST, 1, 4, 5} count
=cut
my $actionref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "args: $$argsref[2]");
unless (exists ${@$actionref}[0] ) {
logmsg(9, 3, "actions array, doesn't exist, initialising");
@$actionref = ();
}
my $actionindex = $#{ @$actionref } + 1;
logmsg(9, 3, "actionindex: $actionindex");
# ACTION formats:
#ACTION <field> </regex/> [<{matches}>] <command> [<command specific fields>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> <sum|count> [<{sum field}>] [LASTLINE]
#ACTION <field> </regex/> <{matches}> append <rule> <{field transformation}> [LASTLINE]
# count - 4 or 5
# sum - 5 or 6
# append - 6 or 7
$$actionref[$actionindex]{field} = $$argsref[1];
$$actionref[$actionindex]{regex} = $$argsref[2];
if ($$argsref[3] =~ /count/i) {
$$actionref[$actionindex]{cmd} = $$argsref[3];
} else {
$$actionref[$actionindex]{matches} = $$argsref[3];
$$actionref[$actionindex]{cmd} = $$argsref[4];
}
for ($$argsref[4]) {
if (/^sum$/i) {
$$actionref[$actionindex]{sourcefield} = $$argsref[5];
} elsif (/^append$/i) {
$$actionref[$actionindex]{appendtorule} = $$argsref[5];
$$actionref[$actionindex]{fieldmap} = $$argsref[6];
} else {
logmsg (1,0, "WARNING, unrecognised command ($$argsref[4]) in ACTION command");
}
}
my @tmp = grep /^LASTLINE$/i, @$argsref;
if ($#tmp) {
$$actionref[$actionindex]{lastline} = 1;
}
$$actionref[$actionindex]{cmd} = $$argsref[4];
}
sub setreport {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
REPORT "Sudo Usage" "{2} ran {4} as {3} on {1}: {x} times"
=cut
my $reportref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "args: $$argsref[2]");
unless (exists ${@$reportref}[0] ) {
logmsg(9, 3, "report array, doesn't exist, initialising");
@$reportref = ();
}
my $reportindex = $#{ @$reportref } + 1;
logmsg(9, 3, "reportindex: $reportindex");
$$reportref[$reportindex]{title} = $$argsref[1];
$$reportref[$reportindex]{line} = $$argsref[2];
}
sub fieldbasics {
=head6 fieldbasics ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
format
FIELDS 6-2 /]\s+/
or
FIELDS 6 /\w+/
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
logmsg (9, 5, "fieldcount: $$argsref[1]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
logmsg (9, 5, "Updated fieldcount to: $$argsref[1]");
logmsg (9, 5, "Calling myself again using hashref{fields}{$1}");
fieldbasics(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{delimiter} = $$argsref[2];
$$cfghashref{totalfields} = $$argsref[1];
for my $i(0..$$cfghashref{totalfields} - 1 ) {
$$cfghashref{byindex}{$i} = "$i"; # map index to name
$$cfghashref{byname}{$i} = "$i"; # map name to index
}
}
}
sub fieldindex {
=head6 fieldindex ($cfghasref, @args)
where cfghashref should be a reference to the fields entry for the rule
Creates the recursive index listing for fields
Passed @args - array of entires for config line
=cut
my $cfghashref = shift;
my $argsref = shift;
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (6, 5, "args: ".Dumper(@$argsref));
logmsg (9, 5, "fieldindex: $$argsref[1] fieldname $$argsref[2]");
if ($$argsref[1] =~ /^(\d+)-(.*)$/ ) {
# this is an infinite loop, need to rectify
logmsg (6, 5, "recursive call using $1");
$$argsref[1] = $2;
fieldindex(\%{ $$cfghashref{$1} }, $argsref);
} else {
$$cfghashref{byindex}{$$argsref[1]-1} = $$argsref[2]; # map index to name
$$cfghashref{byname}{$$argsref[2]} = $$argsref[1]-1; # map name to index
if (exists( $$cfghashref{byname}{$$argsref[1]-1} ) ) {
delete( $$cfghashref{byname}{$$argsref[1]-1} );
}
}
my @tmp = grep /^DEFAULT$/i, @$argsref;
if ($#tmp) {
$$cfghashref{defaultfield} = $$argsref[1];
}
}
=obsolete
sub processformat {
my $cfghashref = shift;
my $rule = shift; # name of the rule to be processed
my $cmd = shift;
my $arg = shift;
#profile( whoami(), whowasi() );
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (5, 4, "Processing rule: $rule");
logmsg(9, 5, "passed cmd: $cmd");
logmsg(9, 5, "passed arg: $arg");
next unless $cmd;
for ($cmd) {
if (/DELIMITER/) {
$$cfghashref{delimiter} = $arg;
logmsg (5, 1, "Config Hash contents:");
&Dumper( %$cfghashref ) if $DEBUG >= 9;
} elsif (/FIELDS/) {
$$cfghashref{totalfields} = $arg;
for my $i(1..$$cfghashref{totalfields}) {
$$cfghashref{fields}{byindex}{$i} = "$i"; # map index to name
$$cfghashref{fields}{byname}{$i} = "$i"; # map name to index
}
} elsif (/FIELD(\d+)/) {
logmsg(6, 6, "FIELD#: $1 arg:$arg");
$$cfghashref{fields}{byindex}{$1} = "$arg"; # map index to name
$$cfghashref{fields}{byname}{$arg} = "$1"; # map name to index
if (exists($$cfghashref{fields}{byname}{$1}) ) {
delete($$cfghashref{fields}{byname}{$1});
}
} elsif (/DEFAULT/) {
$$cfghashref{default} = 1;
#} elsif (/REPEAT/) {
#TODO Define sub stanzas, it's currently hacked in
# extractcmd(\%{$$cfghashref{repeat}}, $cmd, "repeat", $arg);0
} elsif (/REGEX/) {
extractcmd(\%{$$cfghashref{repeat}}, $cmd, "regex", $arg);
} elsif (/FIELD/) {
$$cfghashref{repeat}{field} = $arg;
} elsif (/^\}$/) {
} elsif (/^\{$/) {
} else {
print "Error: $cmd didn't match any known fields\n\n";
} # if cmd
} # for cmd
logmsg (5, 4, "Finished processing rule: $rule");
} # sub processformat
sub processrule {
my $cfghashref = shift;
my $forhashref = shift; # ref to log format hash
my $cmd = shift;
my $arg = shift;
#profile( whoami(), whowasi() );
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (5, 4, "Processing $$cfghashref{name} with cmd: $cmd and arg: $arg");
logmsg (5, 5, "Format hash ...".Dumper(%$forhashref) );
next unless $cmd;
for ($cmd) {
# Static parameters
if (/FORMAT/){
# This really should be the first entry in a rule stanza if it's set
$$cfghashref{format} = $arg;
} elsif (/CMD/) {
extractcmd($cfghashref, $cmd, "cmd", $arg);
} elsif (/^REGEX/) {
extractcmd($cfghashref, $cmd, "regex", $arg);
} elsif (/MATCH/) {
extractcmd($cfghashref, $cmd, "matrix", $arg);
} elsif (/IGNORE/) {
extractcmd(\%{$$cfghashref{CMD}}, $cmd, "", $arg);
} elsif (/COUNT/) {
extractcmd(\%{$$cfghashref{CMD}}, $cmd, "", $arg);
} elsif (/SUM/) {
extractcmd(\%{$$cfghashref{CMD}}, $cmd, "targetfield", $arg);
} elsif (/AVG/) {
extractcmd(\%{$$cfghashref{CMD}}, $cmd, "targetfield", $arg);
} elsif (/TITLE/) {
$$cfghashref{RPT}{title} = $arg;
$$cfghashref{RPT}{title} = $1 if $$cfghashref{RPT}{title} =~ /^\"(.*)\"$/;
} elsif (/LINE/) {
$$cfghashref{RPT}{line} = $arg;
$$cfghashref{RPT}{line} = $1 if $$cfghashref{RPT}{line} =~ /\^"(.*)\"$/;
} elsif (/APPEND/) {
$$cfghashref{RPT}{appendrule} = $arg;
logmsg (1, 0, "*** Setting append for $$cfghashref{name} to $arg");
} elsif (/REPORT/) {
} elsif (/^\}$/) {
} elsif (/^\{$/) {
# Dynamic parameters (defined in FORMAT stanza)
} elsif (exists($$forhashref{fields}{byname}{$cmd} ) ) {
extractregex (\%{$$cfghashref{fields} }, $cmd, $arg);
# End Dynamic parameters
} else {
print "Error: $cmd didn't match any known fields\n\n";
}
} # for
logmsg (5, 1, "Finished processing rule: $$cfghashref{name}");
logmsg (9, 1, "Config hash after running processrule");
Dumper(%$cfghashref);
} # sub processrule
=cut
-
+=obsolete?
sub extractcmd {
my $cfghashref = shift;
my $cmd = shift;
my $param = shift; # The activity associated with cmd
my $arg = shift; # The value for param
if ($param) {
extractregex ($cfghashref, "$param", $arg);
$$cfghashref{$param} =~ s/\s+//g; # strip all whitespace
}
$$cfghashref{cmd} = $cmd;
}
sub extractregexold {
# Keep the old behaviour
my $cfghashref = shift;
my $param = shift;
my $arg = shift;
# profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $paramnegat = $param."negate";
logmsg (5, 1, "rule: $$cfghashref{name} param: $param arg: $arg");
if ($arg =~ /^!/) {
$arg =~ s/^!//g;
$$cfghashref{$paramnegat} = 1;
} else {
$$cfghashref{$paramnegat} = 0;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^\{//;
$arg =~ s/\}$//;
$$cfghashref{$param} = $arg;
logmsg (5, 2, "$param = $$cfghashref{$param}");
}
sub extractregex {
# Put the matches into an array, but would need to change how we handle negates
# Currently the negate is assigned to match group (ie facility or host) or rather than
# an indivudal regex, not an issue immediately because we only support 1 regex
# Need to assign the negate to the regex
# Make the structure ...
# $$cfghashref{rules}{$rule}{$param}[$index] is a hash with {regex} and {negate}
my $cfghashref = shift;
my $param = shift;
my $arg = shift;
my $index = 0;
# profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
logmsg (1, 3, " rule: $$cfghashref{name} for param $param with arg $arg ");
#TODO {name} is null when called for sub stanzas such as CMD or REPEAT, causes an "uninitialised value" warning
if (exists $$cfghashref{$param}[0] ) {
$index = @{$$cfghashref{$param}};
} else {
$$cfghashref{$param} = ();
}
my $regex = \%{$$cfghashref{$param}[$index]};
$$regex{negate} = 0;
logmsg (5, 1, "$param $arg");
if ($arg =~ /^!/) {
$arg =~ s/^!//g;
$$regex{negate} = 1;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^{//;
$arg =~ s/}$//;
$$regex{regex} = $arg;
logmsg (9, 3, "$regex\{regex\} = $$regex{regex} & \$regex\{negate\} = $$regex{negate}");
logmsg (5,2, "$index = $index");
logmsg (5, 2, "$param \[$index\]\{regex\} = $$cfghashref{$param}[$index]{regex}");
logmsg (5, 2, "$param \[$index\]\{negate\} = $$cfghashref{$param}[$index]{negate}");
for (my $i=0; $i<=$index; $i++)
{
logmsg (5,1, "index: $i");
foreach my $key (keys %{$$cfghashref{$param}[$i]}) {
logmsg (5, 2, "$param \[$i\]\{$key\} = $$cfghashref{$param}[$i]{$key}");
}
}
}
-
+=cut
sub report {
my $cfghashref = shift;
my $reshashref = shift;
my $rpthashref = shift;
logmsg(1, 0, "Ruuning report");
# profile( whoami(), whowasi() );
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...");
Dumper(%$reshashref) if $DEBUG >= 5;
print "\n\nNo match for lines:\n";
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
print "\n\nSummaries:\n";
for my $rule (sort keys %$reshashref) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{rules}{$rule}{rpttitle})) {
print "$$cfghashref{rules}{$rule}{rpttitle}\n";
} else {
logmsg (4, 2, "Rule: $rule");
}
for my $key (keys %{$$reshashref{$rule}} ) {
if (exists ($$cfghashref{rules}{$rule}{rptline})) {
print "\t".rptline($cfghashref, $reshashref, $rpthashref, $rule, $key)."\n";
} else {
print "\t$$rpthashref{$rule}{$key}: $key\n";
}
}
print "\n";
}
}
sub rptline {
my $cfghashref = shift;
my $reshashref = shift;
my $rpthashref = shift;
my $rule = shift;
my $key = shift;
my $line = $$cfghashref{rules}{$rule}{rptline};
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
# profile( whoami(), whowasi() );
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (3, 2, "Starting with rule:$rule");
logmsg (9, 3, "key: $key");
my @fields = split /:/, $key;
logmsg (9, 3, "line: $line");
logmsg(9, 3, "subsituting {x} with $$rpthashref{$rule}{$key}{count}");
$line =~ s/\{x\}/$$rpthashref{$rule}{$key}{count}/;
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM") {
$line =~ s/\{s\}/$$rpthashref{$rule}{$key}{sum}/;
}
if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
my $avg = $$rpthashref{$rule}{$key}{sum} / $$reshashref{$rule}{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{a\}/$avg/;
}
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "$fields[$field] = $fields[$i]");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
return $line;
}
+sub getmatchlist {
+ # given a match field, return 2 lists
+ # list 1: all fields in that list
+ # list 2: only numeric fields in the list
+
+ my $matchlist = shift;
+ my $numericonly = shift;
+
+ my @matrix = split (/,/, $matchlist);
+ if ($matchlist !~ /,/) {
+ push @matrix, $matchlist;
+ }
+ my @tmpmatrix = ();
+ for my $i (0 .. $#matrix) {
+ $matrix[$i] =~ s/\s+//g;
+ if ($matrix[$i] =~ /\d+/) {
+ push @tmpmatrix, $matrix[$i];
+ }
+ }
+
+ if ($numericonly) {
+ return @tmpmatrix;
+ } else {
+ return @matrix;
+ }
+}
sub actionrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
+ # returns 0 if unable to apply rule, else returns 1 (success)
+ # use ... actionrule($cfghashref{RULE}, $reshashref, $rule, \%line);
+ my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{RULES}{$rule} but would break append
+ my $reshashref = shift;
+ my $rule = shift;
+ my $line = shift; # hash passed by ref, DO NOT mod
+# my $retvalue;
+ my $retval = 0;
+ #my $resultsrule;
+
+ logmsg (5, 1, " and I was called by ... ".&whowasi);
+ logmsg (6, 2, "rule: $rule called for $$line{line}");
+
+ logmsg (9, 3, ($#{ $$cfghashref{$rule}{actions} } + 1)." actions for rule: $rule");
+ for my $actionid ( 0 .. $#{ $$cfghashref{$rule}{actions} } ) {
+ logmsg (6, 2, "Actionid: $actionid");
+ # actionid needs to recorded in resultsref as well as ruleid
+
+ my @matrix = getmatchlist($$cfghashref{$rule}{actions}[$actionid]{matches}, 0);
+ my @tmpmatrix = getmatchlist($$cfghashref{$rule}{actions}[$actionid]{matches}, 1);
+
+ logmsg (9, 4, ($#tmpmatrix + 1)." entries for matching, using list @tmpmatrix");
+ my $matchid;
+ my @resmatrix = ();
+ no strict;
+ if ($$cfghashref{$rule}{actions}[$actionid]{regex} =~ /^\!/) {
+ my $regex = $$cfghashref{$rule}{actions}[$actionid]{regex};
+ $regex =~ s/^!//;
+ if ($$line{ $$cfghashref{$rule}{actions}[$actionid]{field} } !~ /$regex/ ) {
+ for my $val (@tmpmatrix) {
+ push @resmatrix, ${$val};
+ logmsg (9,5, "Adding ${$val} (from match: $val) to matrix");
+ }
+ $matchid = populatematrix(\@resmatrix, $$cfghashref{$rule}{actions}[$actionid]{matches}, $line);
+ $retvalue = 1;
+ }
+ } else {
+ if ($$line{ $$cfghashref{$rule}{actions}[$actionid]{field} } =~ /$$cfghashref{$rule}{actions}[$actionid]{regex}/ ) {
+ for my $val (@tmpmatrix) {
+ push @resmatrix, ${$val};
+ logmsg (9,5, "Adding ${$val} (from match: $val) to matrix");
+ }
+ $matchid = populatematrix(\@resmatrix, $$cfghashref{$rule}{actions}[$actionid]{matches}, $line);
+ $retval = 1;
+ }
+ logmsg(6, 3, "matrix for $rule & actionid $actionid: @matrix & matchid $matchid");
+ }
+ use strict;
+ if ($matchid) {
+ for ($$cfghashref{$rule}{actions}[$actionid]{cmd}) {
+ if (/sum/) {
+ $$reshashref{$rule}{$actionid}{$matchid} += $resmatrix[ $$cfghashref{$rule}{actions}[$actionid]{sourcefield} ];
+ } elsif (/count/) {
+ $$reshashref{$rule}{$actionid}{$matchid}++;
+ } elsif (/append/) {
+
+ } else {
+ logmsg (1, 0, "Warning: unfrecognized cmd ($$cfghashref{$rule}{actions}[$actionid]{cmd}) in action ($actionid) for rule: $rule");
+ }
+ }
+ }
+ }
+ logmsg (7, 5, "\%reshash ...".Dumper($reshashref));
+
+ return $retval;
+}
+
+sub populatematrix {
+ #my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{RULES}{$rule} but would break append
+ #my $reshashref = shift;
+ my $resmatrixref = shift;
+ my $matchlist = shift;
+ my $lineref = shift; # hash passed by ref, DO NOT mod
+ my $matchid;
+
+ logmsg (9, 5, "\@resmatrix ... ".Dumper($resmatrixref) );
+
+ my @matrix = getmatchlist($matchlist, 0);
+ my @tmpmatrix = getmatchlist($matchlist, 1);
+ logmsg (9, 6, "\@matrix ..".Dumper(@matrix));
+ logmsg (9, 6, "\@tmpmatrix ..".Dumper(@tmpmatrix));
+
+ my $tmpcount = 0;
+ for my $i (0 .. $#matrix) {
+ logmsg (9, 5, "Getting value for field \@matrix[$i] ... $matrix[$i]");
+ if ($matrix[$i] =~ /\d+/) {
+ #$matrix[$i] =~ s/\s+$//;
+ $matchid .= ":".$$resmatrixref[$tmpcount];
+ $matchid =~ s/\s+$//g;
+ logmsg (9, 6, "Adding \@resmatrix[$tmpcount] which is $$resmatrixref[$tmpcount]");
+ $tmpcount++;
+ } else {
+ $matchid .= ":".$$lineref{ $matrix[$i] };
+ logmsg (9, 6, "Adding \%lineref{ $matrix[$i]} which is $$lineref{$matrix[$i]}");
+ }
+ }
+ $matchid =~ s/^://; # remove leading :
+ logmsg (6, 4, "Got matchid: $matchid");
+
+ return $matchid;
+}
+
+=depricate
+sub actionrule {
+ # Collect data for rule $rule as defined in the ACTIONS section of %config
+ # returns 0 if unable to apply rule, else returns 1 (success)
my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{rules}{$rule} but would break append
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $value;
my $retval = 0; my $resultsrule;
# profile( whoami(), whowasi() );
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg (9, 2, "rule: $rule");
if (exists ($$cfghashref{rules}{$rule}{appendrule})) {
$resultsrule = $$cfghashref{rules}{$rule}{appendrule};
} else {
$resultsrule = $rule;
}
unless ($$cfghashref{rules}{cmdregex}) {
$$cfghashref{rules}{cmdregex} = "";
}
logmsg (5, 3, "rule: $rule");
logmsg (5, 4, "results goto: $resultsrule");
logmsg (5, 4, "cmdregex: $$cfghashref{rules}{cmdregex}");
logmsg (5, 4, "CMD negative regex: $$cfghashref{rules}{$rule}{cmdregexnegat}");
logmsg (5, 4, "line: $$line{line}");
if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /IGNORE/) {
if (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "rule $rule does matches and is a positive IGNORE rule");
}
} else {
logmsg (5, 4, "rule $rule matches and is an IGNORE rule");
$retval = 1;
}
} elsif (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
if ( not $$cfghashref{rules}{$rule}{cmdregexnegat} ) {
if ( $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "Positive match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
} elsif ($$cfghashref{rules}{$rule}{cmdregexnegat}) {
if ( $$line{line} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "Negative match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
}
} else {
logmsg (5, 4, "No cmd regex, implicit match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
if ($retval == 0) {
logmsg (5, 4, "line does not match cmdregex for rule: $rule");
}
return $retval;
}
+=cut
+=depricate
sub actionrulecmd
{
my $cfghashref = shift;
my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift;
my $resultsrule = shift;
#3 profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
logmsg (2, 2, "actioning rule $rule for line: $$line{line}");
# This sub contains the first half of the black magic
# The results from the regex's that are applied later
# are used in actioncmdmatrix()
#
# create a matrix that can be used for matching for the black magic happens
# Instead of the string cmdmatrix
# make a hash of matchmatrix{<match field#>} = <cmdregex field #>
# 2 arrays ...
# fieldnums ... the <match field #'s> of matchmatrix{}
# fieldnames ... the named matches of matchmatrix{}, these match back to the names of the fields
# from the file FORMAT
#
my @tmpmatrix = split (/,/, $$cfghashref{rules}{$rule}{cmdmatrix});
my @matrix = ();
for my $val (@tmpmatrix) {
if ($val =~ /(\d+)/ ) {
push @matrix, $val;
} else {
logmsg(3,3, "Not adding val:$val to matrix");
}
}
logmsg(3, 3, "matrix: @matrix");
#
if (not $$cfghashref{rules}{$rule}{cmdregex}) {
$$cfghashref{rules}{$rule}{cmdregex} = "(.*)";
logmsg (5, 3, "rule did not define cmdregex, replacing with global match");
}
if ( exists $$cfghashref{rules}{$rule}{cmd}) {
logmsg (5, 3, "Collecting data from cmd $$cfghashref{rules}{$rule}{cmd}");
logmsg (5, 3, "rule $rule matches cmd") if $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/;
}
if (not exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
logmsg (5, 3, "No cmd regex, calling actioncmdmatrix");
actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
} elsif ($$cfghashref{rules}{$rule}{cmdregexnegat} ) {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 3, "Negative match, calling actioncmdmatrix");
actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
}
} else {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 3, "Positive match, calling actioncmdmatrixnline hash:");
print Dumper($line) if $DEBUG >= 5;
actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
}
}
}
sub printhash
{
# profile( whoami(), whowasi() );
my $line = shift; # hash passed by ref, DO NOT mod
foreach my $key (keys %{ $line} )
{
logmsg (9, 5, "$key: $$line{$key}");
}
}
sub actioncmdmatrix
{
my $cfghashref = shift;
my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift; # Name or ID of rule thats been matched
my $resultsrule = shift; # Name or ID of rule which contains the result set to be updated
my $matrixref = shift; # arrayref
logmsg(5, 4, " ... actioning resultsrule = $rule");
logmsg(5, 5, " and I was called by ... ".&whowasi);
logmsg(9, 5, "Line hash ...");
print Dumper(%$line);
#profile( whoami(), whowasi() );
my $cmdmatrix = $$cfghashref{rules}{$rule}{cmdmatrix};
#my @matrix = shift; #split (/,/, $cmdmatrix);
my $fieldhash;
my $cmdfield;
# @matrix - array of parameters that are used in results
if ( exists ($$cfghashref{rules}{$rule}{cmdfield}) ) {
$cmdfield = ${$$cfghashref{rules}{$rule}{cmdfield}};
}
if ( exists $$cfghashref{rules}{$rule}{cmdmatrix}) {
logmsg (5, 5, "Collecting data for matrix $$cfghashref{rules}{$rule}{cmdmatrix}");
print Dumper(@$matrixref);
logmsg (5, 5, "Using matrix @$matrixref");
# this is where "strict refs" breaks things
# sample: @matrix = svr,1,4,5
# error ... can't use string ("svr") as a SCALAR ref while "strict refs" in use
#
# soln: create a temp array which only has the field #'s and match that
# might need a hash to match
no strict 'refs'; # turn strict refs off just for this section
foreach my $field (@$matrixref) {
# This is were the black magic occurs, ${$field} causes becomes $1 or $2 etc
# and hence contains the various matches from the previous regex match
# which occured just before this function was called
logmsg (9, 5, "matrix field $field has value ${$field}");
if (exists $$line{$field}) {
if ($fieldhash) {
$fieldhash = "$fieldhash:$$line{$field}";
} else {
$fieldhash = "$$line{$field}";
}
} else {
if ($fieldhash) {
$fieldhash = "$fieldhash:${$field}";
} else {
if ( ${$field} ) {
$fieldhash = "${$field}";
} else {
logmsg (1, 6, "$field not found in \"$$line{line}\" with regex $$cfghashref{rules}{$rule}{cmdregex}");
logmsg (1, 6, "line hash:");
print Dumper(%$line) if $DEBUG >= 1;
}
}
}
}
use strict 'refs';
if ($$cfghashref{rules}{$rule}{targetfield}) {
logmsg (1, 5, "Setting cmdfield (field $$cfghashref{rules}{$rule}{targetfield}) to ${$$cfghashref{rules}{$rule}{targetfield}}");
$cmdfield = ${$$cfghashref{rules}{$rule}{targetfield}};
}
#if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
$$reshashref{$resultsrule}{$fieldhash}{count}++;
logmsg (5, 5, "$$reshashref{$resultsrule}{$fieldhash}{count} matches for rule $rule so far from $fieldhash");
#} els
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
$$reshashref{$resultsrule}{$fieldhash}{sum} = $$reshashref{$resultsrule}{$fieldhash}{sum} + $cmdfield;
logmsg (5, 5, "Adding $cmdfield to total (now $$reshashref{$resultsrule}{$fieldhash}{sum}) for rule $rule so far from $fieldhash");
if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
logmsg (5, 5, "Average is ".$$reshashref{$resultsrule}{$fieldhash}{sum} / $$reshashref{$resultsrule}{$fieldhash}{count}." for rule $rule so far from $fieldhash");
}
}
for my $key (keys %{$$reshashref{$resultsrule}}) {
logmsg (5, 5, "key $key for rule:$rule with $$reshashref{$resultsrule}{$key}{count} matches");
}
logmsg (5, 5, "$fieldhash matches for rule $rule so far from matrix: $$cfghashref{rules}{$rule}{cmdmatrix}");
} else {
logmsg (5, 5, "cmdmatrix is not set for $rule");
#if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
$$reshashref{$resultsrule}{count}++;
logmsg (5, 5, "$$reshashref{$resultsrule}{count} lines match rule $rule so far");
# } els
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
$$reshashref{$resultsrule}{sum} = $$reshashref{$resultsrule}{sum} + $cmdfield;
logmsg (5, 5, "$$reshashref{$resultsrule}{sum} lines match rule $rule so far");
}
}
logmsg(5, 4, " ... Finished actioning resultsrule = $rule");
}
+=cut
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
# An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
if ($value) {
if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
} else {
logmsg(7, 5, "\$value is null, no match");
}
}
+sub matchrules {
+ my $cfghashref = shift;
+ my $linehashref = shift;
+ # loops through the rules and calls matchfield for each rule
+ # assumes cfghashref{RULE} has been passed
+ # returns a list of matching rules
+
+ my %rules;
+ for my $rule (keys %{ $cfghashref } ) {
+ $rules{$rule} = $rule if matchfields(\%{ $$cfghashref{$rule}{fields} } , $linehashref);
+ }
+
+ return %rules;
+}
+
+sub matchfields {
+ my $cfghashref = shift; # expects to be passed $$cfghashref{RULES}{$rule}{fields}
+ my $linehashref = shift;
+
+ my $ret = 1;
+ # Assume fields match.
+ # Only fail if a field doesn't match.
+ # Passed a cfghashref to a rule
+
+ foreach my $field (keys (%{ $cfghashref } ) ) {
+ if ($$cfghashref{fields}{$field} =~ /^!/) {
+ my $exp = $$cfghashref{fields}{$field};
+ $exp =~ s/^\!//;
+ $ret = 0 unless ($$linehashref{ $field } !~ /$exp/);
+ } else {
+ $ret = 0 unless ($$linehashref{ $field } =~ /$$cfghashref{fields}{$field}/);
+ }
+ }
+ return $ret;
+}
+
sub matchingrules {
my $cfghashref = shift;
my $param = shift;
my $matchref = shift;
my $value = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 3, "param:$param");
logmsg (6, 3, "value:$value") if $value;
logmsg (3, 2, "$param, match count: ".keys(%{$matchref}) );
if (keys %{$matchref} == 0) {
# Check all rules as we haevn't had a match yet
foreach my $rule (keys %{$cfghashref->{rules} } ) {
checkrule($cfghashref, $param, $matchref, $rule, $value);
}
} else {
# As we've allready had a match on the rules, only check those that matched in earlier rounds
# key in %matches is the rule that matches
foreach my $rule (keys %{$matchref}) {
checkrule($cfghashref, $param, $matchref, $rule, $value);
}
}
}
sub checkrule {
my $cfghashref = shift;
my $param = shift;
my $matches = shift;
my $rule = shift; # key to %matches
my $value = shift;
logmsg(2, 1, "Checking rule ($rule) & param ($param) for matches against: $value");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $paramref = \@{ $$cfghashref{rules}{$rule}{$param} };
defaultregex($paramref); # This should be done when reading the config
foreach my $index (@{ $paramref } ) {
my $match = matchregex($index, $value);
if ($$index{negate} ) {
if ( $match) {
delete $$matches{$rule};
logmsg (5, 5, "matches $index->{regex} for param \'$param\', but negative rule is set, so removing rule $match from list.");
} else {
$$matches{$rule} = "match" if $match;
logmsg (5, 5, "Doesn't match for $index->{regex} for param \'$param\', but negative rule is set, so leaving rule $match on list.");
}
} elsif ($match) {
$$matches{$rule} = "match" if $match;
logmsg (5, 4, "matches $index->{regex} for param \'$param\', leaving rule $match on list.");
} else {
delete $$matches{$rule};
logmsg (5, 4, "doesn't match $index->{regex} for param \'$param\', removing rule $match from list.");
}
} # for each regex hash in the array
logmsg (3, 2, "matches ".keys (%{$matches})." matches after checking rules for $param");
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
if ($DEBUG >= $level) {
for my $i (0..$indent) {
print STDERR " ";
}
print STDERR whowasi."(): $msg\n";
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
|
mikeknox/LogParse | 6404490115899bac615eb0cdd282db99b41108a1 | Added a lot of description into logparse.pl about the new language definitions. Also updated some documention in logparse.conf Many of the rules will need to be updated and added back in to logparse.conf | diff --git a/logparse.pl b/logparse.pl
old mode 100644
new mode 100755
|
mikeknox/LogParse | 63b6f533281f2feaf234feb09a1924cdae36b857 | Imported changes from MBP Loading works, hit a snag with processing duplicate entires ... The conf language currently only supports NOT and AND as logical operators, it needs to be extended to support OR | diff --git a/logparse.pl b/logparse.pl
old mode 100644
new mode 100755
index a87ec99..fbe3b4d
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,965 +1,982 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=head1 NAME
logparse - syslog analysis tool
=cut
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
Describe config file for log parse / summary engine
Input fields from syslog:
Date, time, server, application, facility, ID, message
=head3 Config line
/server regex/, /app regex/, /facility regex/, /msg regex/, $ACTIONS
Summaries are required at various levels, from total instances to total sizes to server summaries.
=head2 ACTIONS
COUNT - Just list the total number of matches
SUM[x] - Report the sum of field x of all matches
SUM[x], /regex/ - Apply regex to msg field of matches and report the sum of field x from that regex
SUM[x], /regex/, {y,z} - Apply regex to msg field of matches and report the sum of field x from that regex for fields y & z
AVG[x], /regex/, {y,z} - Apply regex to msg field of matches and report the avg of field x from that regex for fields y & z
COUNT[x], /regex/, {y,z} - Apply regex to msg field of matches and report the count of field x from that regex for matching fields y & z
Each entry can test or regex, if text interpret as regex /^string$/
Sample entry...
*, /rshd/, *, *, COUNT /connect from (.*)/, {1}
=head2 BUGS:
See http://github.com/mikeknox/LogParse/issues
=head2 FORMAT stanza
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=head2 TODO:
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=cut
# expects data on std in
use strict;
use Getopt::Std;
#no strict 'refs';
-#use Data::Dump qw(pp);
-use Data::Dumper qw(Dumper);
+use Data::Dump qw(pp);
+use Data::Dumper;
-#use utils;
-#use logparse;
+use utils;
+use logparse;
# Globals
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my $CONFIGFILE="logparse.conf";
my %cfghash;
my %reshash;
my $cmdcount = 0;
my $UNMATCHEDLINES = 1;
my $SYSLOGFILE = "/var/log/messages";
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
getopt('cdl', \%opts);
$DEBUG = $opts{d} if $opts{d};
$CONFIGFILE = $opts{c} if $opts{c};
$SYSLOGFILE = $opts{l} if $opts{l};
loadcfg (\%cfghash, $CONFIGFILE, $cmdcount);
-print Dumper(%cfghash);
-#processlogfile(\%cfghash, \%reshash, $SYSLOGFILE);
-#report(\%cfghash, \%reshash);
-#profilereport();
+processlogfile(\%cfghash, \%reshash, $SYSLOGFILE);
+
+report(\%cfghash, \%reshash);
+
+profilereport();
exit 0;
+
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfile = shift;
- logmsg(1, 0, "processing $logfile ...");
- logmsg(5, 1, " and I was called by ... ".&whowasi);
+ profile( whoami, whowasi );
+ logmsg (1, 0, "processing $logfile ...");
open (LOGFILE, "<$logfile") or die "Unable to open $SYSLOGFILE for reading...";
while (<LOGFILE>) {
- my $facility = "";
+ my $facility;
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
- logmsg(5, 1, "Processing next line");
+ logmsg (5, 1, "Processing next line");
($line{mth}, $line{date}, $line{time}, $line{svr}, $line{app}, $line{msg}) = split (/\s+/, $line{line}, 6);
- logmsg(9, 2, "mth: $line{mth}, date: $line{date}, time: $line{time}, svr: $line{svr}, app: $line{app}, msg: $line{msg}");
- logmsg(9, 1, "Checking line: $line{line}");
- logmsg(9, 1, "msg: $line{msg}");
-
+ logmsg (9, 2, "mth: $line{mth}, date: $line{date}, time: $line{time}, svr: $line{svr}, app: $line{app}, msg: $line{msg}");
+
if ($line{msg} =~ /^\[/) {
($line{facility}, $line{msg}) = split (/]\s+/, $line{msg}, 2);
$line{facility} =~ s/\[//;
- logmsg(9, 1, "facility: $line{facility}");
}
-# These need to be abstracted out per description in the FORMAT stanza
+ logmsg (9, 1, "Checking line: $line{line}");
+ logmsg (9, 1, "facility: $line{facility}");
+ logmsg (9, 1, "msg: $line{msg}");
+
my %matches;
my %matchregex = ("svrregex", "svr", "appregex", "app", "facregex", "facility", "msgregex", "line");
for my $param ("appregex", "facregex", "msgregex", "svrregex") {
- $line{ $matchregex{$param} } = "" unless $line{ $matchregex{$param} }; # this really should be elsewhere, it's a hack
matchingrules($cfghashref, $param, \%matches, $line{ $matchregex{$param} } );
}
logmsg(9, 2, keys(%matches)." matches so far");
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} and next unless keys %matches > 0;
logmsg(9,1,"Results hash ...");
- Dumper(%$reshashref);
+ pp(%$reshashref);
if ($line{msg} =~ /message repeated/ and exists $svrlastline{$line{svr} }{line}{msg} ) { # and keys %{$svrlastline{ $line{svr} }{rulematches}} ) {
logmsg (9, 2, "last message repeated and matching svr line");
my $numrepeats = 0;
if ($line{msg} =~ /message repeated (.*) times/) {
$numrepeats = $1;
}
logmsg(9, 2, "Last message repeated $numrepeats times");
for my $i (1..$numrepeats) {
for my $rule (keys %{$svrlastline{ $line{svr} }{rulematches} } ) {
logmsg (5, 3, "Applying cmd for rule $rule: $$cfghashref{rules}{$rule}{cmd} - as prelim regexs pass");
actionrule($cfghashref, $reshashref, $rule, \%{ $svrlastline{$line{svr} }{line} }); # if $actrule == 0;
}
}
} else {
logmsg (5, 2, "No recorded last line for $line{svr}") if $line{msg} =~ /message repeated/;
logmsg (9, 2, "msg: $line{msg}");
%{ $svrlastline{$line{svr} }{line} } = %line;
# track line
# track matching rule(s)
logmsg (3, 2, keys (%matches)." matches after checking all rules");
if (keys %matches > 0) {
logmsg (5, 2, "svr & app & fac & msg matched rules: ");
logmsg (5, 2, "matched rules ".keys(%matches)." from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmpmatches = %matches;
for my $rule (keys %tmpmatches) {
my $result = actionrule($cfghashref, $reshashref, $rule, \%line);
delete $matches{$rule} unless $result ;
$actrule = $result unless $actrule;
logmsg (5, 3, "Applying cmd from rule $rule: $$cfghashref{rules}{$rule}{cmd} as passed prelim regexes");
logmsg (10, 4, "an action rule matched: $actrule");
}
logmsg (10, 4, "an action rule matched: $actrule");
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if $actrule == 0;
%{$svrlastline{$line{svr} }{rulematches}} = %matches unless ($line{msg} =~ /last message repeated d+ times/);
- logmsg (5, 2, "setting lastline match for server: $line{svr} and line:\n$line{line}");
+ logmsg (5, 2, "setting lastline match for server: $line{svr} and line:n$line{line}");
logmsg (5, 3, "added matches for $line{svr} for rules:");
for my $key (keys %{$svrlastline{$line{svr} }{rulematches}}) {
logmsg (5, 4, "$key");
}
logmsg (5, 3, "rules from line $line{line}");
} else {
logmsg (5, 2, "No match: $line{line}");
if ($svrlastline{$line{svr} }{unmatchedline}{msg} eq $line{msg} ) {
$svrlastline{$line{svr} }{unmatchedline}{count}++;
logmsg (9, 3, "$svrlastline{$line{svr} }{unmatchedline}{count} instances of msg: $line{msg} on $line{svr}");
} else {
$svrlastline{$line{svr} }{unmatchedline}{count} = 0 unless exists $svrlastline{$line{svr} }{unmatchedline}{count};
if ($svrlastline{$line{svr} }{unmatchedline}{msg} and $svrlastline{$line{svr} }{unmatchedline}{count} >= 1) {
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = "$line{svr}: Last unmatched message repeated $svrlastline{$line{svr} }{unmatchedline}{count} timesn";
} else {
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line};
$svrlastline{$line{svr} }{unmatchedline}{msg} = $line{msg};
}
$svrlastline{$line{svr} }{unmatchedline}{count} = 0;
}
logmsg (5, 2, "set unmatched{ $line{svr} }{msg} to $svrlastline{$line{svr} }{unmatchedline}{msg} and count to: $svrlastline{$line{svr} }{unmatchedline}{count}");
}
}
logmsg (5, 1, "finished processing line");
}
foreach my $server (keys %svrlastline) {
if ( $svrlastline{$server}{unmatchedline}{count} >= 1) {
logmsg (9, 2, "Added record #".( $#{$$reshashref{nomatch}} + 1 )." for unmatched results");
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = "$server: Last unmatched message repeated $svrlastline{$server }{unmatchedline}{count} timesn";
}
}
logmsg (1, 0, "Finished processing $logfile.");
}
sub parsecfgline {
my $line = shift;
- #profile( whoami(), whowasi() );
- logmsg (5, 3, " and I was called by ... ".&whowasi);
- my $cmd = "";
- my $arg = "";
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
+ my $cmd; my $arg;
chomp $line;
- logmsg(5, 3, " and I was called by ... ".&whowasi);
- logmsg (6, 4, "line: ${line}");
+ logmsg (6, 4, "line: $line");
- if ($line =~ /^#|\s+#/ ) {
- logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
- } elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
- logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
- } else {
+ unless ($line =~ /^#|\s+#/ ) {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
- $arg = "" unless $arg;
- $cmd = "" unless $cmd;
+ } else {
+ logmsg(9, 5, "comment line, skipping");
}
-
- logmsg (6, 3, "returning cmd: $cmd arg: $arg");
+
+ logmsg (6, 4, "returning cmd: $cmd arg: $arg");
+
return ($cmd, $arg);
}
sub loadcfg {
my $cfghashref = shift;
my $cfgfile = shift;
my $cmdcount = shift;
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
- logmsg(5, 3, " and I was called by ... ".&whowasi);
-
- my $rule = -1;
- my $bracecount = 0;
- my $stanzatype = "";
+
+ my $rule;
+ my $bracecount;
+ my $stanzatype;
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "bracecount:$bracecount");
logmsg(6, 2, "stanzatype:$stanzatype");
my $cmd; my $arg;
($cmd, $arg) = parsecfgline($line);
next unless $cmd;
- logmsg(6, 2, "rule:$rule");
- logmsg(6, 2, "cmdcount:$cmdcount");
- logmsg(6, 2, "cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
+ logmsg (6, 2, "cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
if ($bracecount == 0 ) {
for ($cmd) {
if (/RULE/) {
if ($arg =~ /(.*)\s+\{/) {
$rule = $1;
- logmsg(9, 3, "rule (if) is now: $rule");
+ logmsg (9, 3, "rule (if) is now: $rule");
} else {
$rule = $cmdcount++;
- logmsg(9, 3, "rule (else) is now: $rule");
+ logmsg (9, 3, "rule (else) is now: $rule");
} # if arg
$stanzatype = "rule";
- unless (exists $$cfghashref{formats}) {
- logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
- exit 2;
- }
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rule");
} elsif (/FORMAT/) {
if ($arg =~ /(.*)\s+\{/) {
$rule = $1;
} # if arg
$stanzatype = "format";
logmsg(6, 2, "stanzatype updated to: $stanzatype");
} elsif (/\}/) {
# if bracecount = 0, cmd may == "}", so ignore
} else {
print STDERR "Error: $cmd didn't match any stanzasn\n";
} # if cmd
} # for cmd
} # bracecount == 0
if ($cmd =~ /\{/ or $arg =~ /\{/) {
$bracecount++;
} elsif ($cmd =~ /\}/ or $arg =~ /\}/) {
$bracecount--;
} # if cmd or arg
if ($bracecount > 0) { # else bracecount
for ($stanzatype) {
if (/rule/) {
logmsg (6, 2, "About to call processrule ... cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
- processrule( \%{ $$cfghashref{rules}{$rule} }, $rule, $cmd, $arg);
+ processrule( %{ $$cfghashref{rules}{$rule} }, $rule, $cmd, $arg);
} elsif (/format/) {
- logmsg (6, 2, "About to call processformat ... cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
- processformat( \%{$$cfghashref{formats}{$rule}} , $rule, $cmd, $arg);
+ processformat( %{ $$cfghashref{formats}{$rule} } , $rule, $cmd, $arg);
} # if stanzatype
} #if stanzatype
} else {# else bracecount
logmsg (1, 2, "ERROR: bracecount: $bracecount. How did it go negative??");
} # bracecount
} # while
close CFGFILE;
logmsg (5, 1, "Config Hash contents:");
- &Dumper( %$cfghashref );
+ &pp( %$cfghashref );
logmsg (1, 0, "finished processing cfg: $cfgfile");
} # sub loadcfg
sub processformat {
my $cfghashref = shift;
my $rule = shift; # name of the rule to be processed
my $cmd = shift;
my $arg = shift;
- #profile( whoami(), whowasi() );
- logmsg (5, 4, " and I was called by ... ".&whowasi);
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
logmsg (5, 4, "Processing rule: $rule");
- logmsg(9, 5, "passed cmd: $cmd");
- logmsg(9, 5, "passed arg: $arg");
- next unless $cmd;
+ logmsg(9, 5, "extracted cmd: $cmd and arg:$arg");
+ next unless $cmd;
for ($cmd) {
if (/DELIMITER/) {
$$cfghashref{delimiter} = $arg;
logmsg (5, 1, "Config Hash contents:");
- &Dumper( %$cfghashref ) if $DEBUG >= 9;
+ &pp( %$cfghashref );
} elsif (/FIELDS/) {
- $$cfghashref{totalfields} = $arg;
- for my $i(1..$$cfghashref{totalfields}) {
- $$cfghashref{fields}{byindex}{$i} = "$i"; # map index to name
- $$cfghashref{fields}{byname}{$i} = "$i"; # map name to index
- }
- } elsif (/FIELD(\d+)/) {
+ $$cfghashref{fields} = $arg;
+ } elsif (/FIELD(d)/) {
logmsg(6, 6, "FIELD#: $1 arg:$arg");
- $$cfghashref{fields}{byindex}{$1} = "$arg"; # map index to name
- $$cfghashref{fields}{byname}{$arg} = "$1"; # map name to index
- if (exists($$cfghashref{fields}{byname}{$1}) ) {
- delete($$cfghashref{fields}{byname}{$1});
- }
} elsif (/^\}$/) {
} elsif (/^\{$/) {
} else {
print "Error: $cmd didn't match any known fields\n\n";
} # if cmd
} # for cmd
logmsg (5, 4, "Finished processing rule: $rule");
} # sub processformat
sub processrule {
my $cfghashref = shift;
my $rule = shift; # name of the rule to be processed
my $cmd = shift;
my $arg = shift;
- #profile( whoami(), whowasi() );
- logmsg (5, 4, " and I was called by ... ".&whowasi);
+ profile( whoami(), whowasi() );
+ logmsg (5, 4, " and I was called by ... ".whowasi);
logmsg (5, 4, "Processing $rule with cmd: $cmd and arg: $arg");
next unless $cmd;
for ($cmd) {
if (/HOST/) {
# fields
extractregex ($cfghashref, "svrregex", $arg, $rule);
} elsif (/APP($|\s+)/) {
extractregex ($cfghashref, "appregex", $arg, $rule);
} elsif (/FACILITY/) {
extractregex ($cfghashref, "facregex", $arg, $rule);
} elsif (/MSG/) {
extractregex ($cfghashref, "msgregex", $arg, $rule);
} elsif (/CMD/) {
extractregex ($cfghashref, "cmd", $arg, $rule) unless $arg =~ /\{/;
} elsif (/^REGEX/) {
extractregexold ($cfghashref, "cmdregex", $arg, $rule);
} elsif (/MATCH/) {
extractregexold ($cfghashref, "cmdmatrix", $arg, $rule);
$$cfghashref{cmdmatrix} =~ s/\s+//g; # strip all whitespace
} elsif (/IGNORE/) {
$$cfghashref{cmd} = $cmd;
} elsif (/COUNT/) {
$$cfghashref{cmd} = $cmd;
} elsif (/SUM/) {
extractregex ($cfghashref, "targetfield", $arg, $rule);
$$cfghashref{targetfield} =~ s/\s+//g; # strip all whitespace
$$cfghashref{cmd} = $cmd;
} elsif (/AVG/) {
extractregex ($cfghashref, "targetfield", $arg, $rule);
$$cfghashref{targetfield} =~ s/\s+//g; # strip all whitespace
$$cfghashref{cmd} = $cmd;
} elsif (/TITLE/) {
$$cfghashref{rpttitle} = $arg;
$$cfghashref{rpttitle} = $1 if $$cfghashref{rpttitle} =~ /^\"(.*)\"$/;
} elsif (/LINE/) {
$$cfghashref{rptline} = $arg;
$$cfghashref{rptline} = $1 if $$cfghashref{rptline} =~ /\^"(.*)\"$/;
} elsif (/APPEND/) {
$$cfghashref{appendrule} = $arg;
logmsg (1, 0, "*** Setting append for $rule to $arg");
} elsif (/REPORT/) {
} elsif (/^\}$/) {
# $bracecount{closed}++;
} elsif (/^\{$/) {
# $bracecount{open}++;
} else {
print "Error: $cmd didn't match any known fields\n\n";
}
} # for
logmsg (5, 1, "Finished processing rule: $rule");
logmsg (9, 1, "Config hash after running processrule");
- Dumper(%$cfghashref);
+ &pp(%$cfghashref);
} # sub processrule
sub extractregexold {
# Keep the old behaviour
my $cfghashref = shift;
my $param = shift;
my $arg = shift;
my $rule = shift;
-# profile( whoami(), whowasi() );
- logmsg (5, 3, " and I was called by ... ".&whowasi);
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
my $paramnegat = $param."negate";
logmsg (5, 1, "rule: $rule param: $param arg: $arg");
if ($arg =~ /^!/) {
$arg =~ s/^!//g;
$$cfghashref{$paramnegat} = 1;
} else {
$$cfghashref{$paramnegat} = 0;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^\{//;
$arg =~ s/\}$//;
$$cfghashref{$param} = $arg;
logmsg (5, 2, "$param = $$cfghashref{$param}");
}
sub extractregex {
# Put the matches into an array, but would need to change how we handle negates
# Currently the negate is assigned to match group (ie facility or host) or rather than
# an indivudal regex, not an issue immediately because we only support 1 regex
# Need to assign the negate to the regex
# Make the structure ...
# $$cfghashref{rules}{$rule}{$param}[$index] is a hash with {regex} and {negate}
my $cfghashref = shift;
my $param = shift;
my $arg = shift;
my $rule = shift;
my $index = 0;
-# profile( whoami(), whowasi() );
- logmsg (5, 3, " and I was called by ... ".&whowasi);
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
logmsg (1, 3, " rule: $rule for param $param with arg $arg ");
if (exists $$cfghashref{$param}[0] ) {
$index = @{$$cfghashref{$param}};
} else {
$$cfghashref{$param} = ();
}
- my $regex = \%{$$cfghashref{$param}[$index]};
+ my $regex = %{$$cfghashref{$param}[$index]};
$$regex{negate} = 0;
logmsg (5, 1, "$param $arg");
if ($arg =~ /^!/) {
$arg =~ s/^!//g;
$$regex{negate} = 1;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^{//;
$arg =~ s/}$//;
$$regex{regex} = $arg;
logmsg (9, 3, "$regex\{regex\} = $$regex{regex} & \$regex\{negate\} = $$regex{negate}");
logmsg (5,2, "$index = $index");
- logmsg (5, 2, "$param \[$index\]\{regex\} = $$cfghashref{$param}[$index]{regex}");
- logmsg (5, 2, "$param \[$index\]\{negate\} = $$cfghashref{$param}[$index]{negate}");
+ logmsg (5, 2, "$param [$index\]\{regex\} = $$cfghashref{$param}[$index]{regex}");
+ logmsg (5, 2, "$param [$index\]\{negate\} = $$cfghashref{$param}[$index]{negate}");
for (my $i=0; $i<=$index; $i++)
{
logmsg (5,1, "index: $i");
foreach my $key (keys %{$$cfghashref{$param}[$i]}) {
- logmsg (5, 2, "$param \[$i\]\{$key\} = $$cfghashref{$param}[$i]{$key}");
+ logmsg (5, 2, "$param [$i\]\{$key\} = $$cfghashref{$param}[$i]{$key}");
}
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
my $rpthashref = shift;
logmsg(1, 0, "Ruuning report");
-# profile( whoami(), whowasi() );
- logmsg (5, 0, " and I was called by ... ".&whowasi);
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
logmsg(5, 1, "Dump of results hash ...");
- Dumper(%$reshashref) if $DEBUG >= 5;
+ pp(%$reshashref) if $DEBUG >= 5;
- print "\n\nNo match for lines:\n";
- foreach my $line (@{@$reshashref{nomatch}}) {
- print "\t$line";
+ print "n\nNo match for lines:\n";
+ foreach my $line (@{@$rpthashref{nomatch}}) {
+ print "t$line";
}
- print "\n\nSummaries:\n";
- for my $rule (sort keys %$reshashref) {
+ print "n\nSummaries:\n";
+ for my $rule (sort keys %$rpthashref) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{rules}{$rule}{rpttitle})) {
- print "$$cfghashref{rules}{$rule}{rpttitle}\n";
+ print "$$cfghashref{rules}{$rule}{rpttitle}:n";
} else {
- logmsg (4, 2, "Rule: $rule");
+ logmsg (4, 2, "Rule: $rule:");
}
- for my $key (keys %{$$reshashref{$rule}} ) {
+ for my $key (keys %{$$rpthashref{$rule}} ) {
if (exists ($$cfghashref{rules}{$rule}{rptline})) {
- print "\t".rptline($cfghashref, $reshashref, $rpthashref, $rule, $key)."\n";
+ print "t".rptline($cfghashref, $reshashref, $rpthashref, $rule, $key)."\n";
} else {
- print "\t$$rpthashref{$rule}{$key}: $key\n";
+ print "t$$rpthashref{$rule}{$key}: $key\n";
}
}
- print "\n";
+ print "n";
}
}
sub rptline {
my $cfghashref = shift;
my $reshashref = shift;
my $rpthashref = shift;
my $rule = shift;
my $key = shift;
my $line = $$cfghashref{rules}{$rule}{rptline};
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
-# profile( whoami(), whowasi() );
- logmsg (5, 2, " and I was called by ... ".&whowasi);
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
logmsg (3, 2, "Starting with rule:$rule");
logmsg (9, 3, "key: $key");
my @fields = split /:/, $key;
logmsg (9, 3, "line: $line");
- logmsg(9, 3, "subsituting {x} with $$rpthashref{$rule}{$key}{count}");
$line =~ s/\{x\}/$$rpthashref{$rule}{$key}{count}/;
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM") {
$line =~ s/\{s\}/$$rpthashref{$rule}{$key}{sum}/;
}
if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
my $avg = $$rpthashref{$rule}{$key}{sum} / $$reshashref{$rule}{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{a\}/$avg/;
}
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "$fields[$field] = $fields[$i]");
- if ($line =~ /\{$field\}/) {
- $line =~ s/\{$field\}/$fields[$i]/;
+ if ($line =~ /{$field\}/) {
+ $line =~ s/{$field\}/$fields[$i]/;
}
}
return $line;
}
sub actionrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{rules}{$rule} but would break append
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $value;
my $retval = 0; my $resultsrule;
-# profile( whoami(), whowasi() );
- logmsg (5, 0, " and I was called by ... ".&whowasi);
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
logmsg (9, 2, "rule: $rule");
if (exists ($$cfghashref{rules}{$rule}{appendrule})) {
$resultsrule = $$cfghashref{rules}{$rule}{appendrule};
} else {
$resultsrule = $rule;
}
-
- unless ($$cfghashref{rules}{cmdregex}) {
- $$cfghashref{rules}{cmdregex} = "";
- }
logmsg (5, 3, "rule: $rule");
logmsg (5, 4, "results goto: $resultsrule");
- logmsg (5, 4, "cmdregex: $$cfghashref{rules}{cmdregex}");
+ logmsg (5, 4, "cmdregex: $}{cmdregex}");
logmsg (5, 4, "CMD negative regex: $$cfghashref{rules}{$rule}{cmdregexnegat}");
logmsg (5, 4, "line: $$line{line}");
if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /IGNORE/) {
if (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "rule $rule does matches and is a positive IGNORE rule");
}
} else {
logmsg (5, 4, "rule $rule matches and is an IGNORE rule");
$retval = 1;
}
} elsif (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
if ( not $$cfghashref{rules}{$rule}{cmdregexnegat} ) {
if ( $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "Positive match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
} elsif ($$cfghashref{rules}{$rule}{cmdregexnegat}) {
if ( $$line{line} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "Negative match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
}
} else {
logmsg (5, 4, "No cmd regex, implicit match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
if ($retval == 0) {
logmsg (5, 4, "line does not match cmdregex for rule: $rule");
}
return $retval;
}
sub actionrulecmd
{
my $cfghashref = shift;
my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift;
my $resultsrule = shift;
-#3 profile( whoami(), whowasi() );
- logmsg (5, 3, " and I was called by ... ".&whowasi);
+ profile( whoami(), whowasi() );
logmsg (2, 2, "actioning rule $rule for line: $$line{line}");
# This sub contains the first half of the black magic
# The results from the regex's that are applied later
# are used in actioncmdmatrix()
#
# create a matrix that can be used for matching for the black magic happens
# Instead of the string cmdmatrix
# make a hash of matchmatrix{<match field#>} = <cmdregex field #>
# 2 arrays ...
# fieldnums ... the <match field #'s> of matchmatrix{}
# fieldnames ... the named matches of matchmatrix{}, these match back to the names of the fields
# from the file FORMAT
#
my @tmpmatrix = split (/,/, $$cfghashref{rules}{$rule}{cmdmatrix});
my @matrix = ();
for my $val (@tmpmatrix) {
if ($val =~ /(\d+)/ ) {
push @matrix, $val;
} else {
logmsg(3,3, "Not adding val:$val to matrix");
}
}
logmsg(3, 3, "matrix: @matrix");
#
if (not $$cfghashref{rules}{$rule}{cmdregex}) {
$$cfghashref{rules}{$rule}{cmdregex} = "(.*)";
logmsg (5, 3, "rule did not define cmdregex, replacing with global match");
}
if ( exists $$cfghashref{rules}{$rule}{cmd}) {
logmsg (5, 3, "Collecting data from cmd $$cfghashref{rules}{$rule}{cmd}");
logmsg (5, 3, "rule $rule matches cmd") if $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/;
}
if (not exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
logmsg (5, 3, "No cmd regex, calling actioncmdmatrix");
- actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
+ actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, @matrix);
} elsif ($$cfghashref{rules}{$rule}{cmdregexnegat} ) {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 3, "Negative match, calling actioncmdmatrix");
- actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
+ actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, @matrix);
}
} else {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 3, "Positive match, calling actioncmdmatrixnline hash:");
- print Dumper($line) if $DEBUG >= 5;
- actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
+ &pp($line) if $DEBUG >= 5;
+ actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, @matrix);
}
}
}
sub printhash
{
-# profile( whoami(), whowasi() );
+ profile( whoami(), whowasi() );
my $line = shift; # hash passed by ref, DO NOT mod
foreach my $key (keys %{ $line} )
{
logmsg (9, 5, "$key: $$line{$key}");
}
}
sub actioncmdmatrix
{
my $cfghashref = shift;
my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift; # Name or ID of rule thats been matched
my $resultsrule = shift; # Name or ID of rule which contains the result set to be updated
my $matrixref = shift; # arrayref
- logmsg(5, 4, " ... actioning resultsrule = $rule");
- logmsg(5, 5, " and I was called by ... ".&whowasi);
- logmsg(9, 5, "Line hash ...");
- print Dumper(%$line);
- #profile( whoami(), whowasi() );
+ profile( whoami(), whowasi() );
my $cmdmatrix = $$cfghashref{rules}{$rule}{cmdmatrix};
#my @matrix = shift; #split (/,/, $cmdmatrix);
my $fieldhash;
my $cmdfield;
# @matrix - array of parameters that are used in results
if ( exists ($$cfghashref{rules}{$rule}{cmdfield}) ) {
$cmdfield = ${$$cfghashref{rules}{$rule}{cmdfield}};
}
+
+ logmsg(5, 2, " ... actioning resultsrule = $rule");
if ( exists $$cfghashref{rules}{$rule}{cmdmatrix}) {
- logmsg (5, 5, "Collecting data for matrix $$cfghashref{rules}{$rule}{cmdmatrix}");
- print Dumper(@$matrixref);
- logmsg (5, 5, "Using matrix @$matrixref");
+ logmsg (5, 3, "Collecting data for matrix $$cfghashref{rules}{$rule}{cmdmatrix}");
+ logmsg (5, 3, "Using matrix @$matrixref");
# this is where "strict refs" breaks things
# sample: @matrix = svr,1,4,5
# error ... can't use string ("svr") as a SCALAR ref while "strict refs" in use
#
# soln: create a temp array which only has the field #'s and match that
# might need a hash to match
no strict 'refs'; # turn strict refs off just for this section
foreach my $field (@$matrixref) {
# This is were the black magic occurs, ${$field} causes becomes $1 or $2 etc
# and hence contains the various matches from the previous regex match
# which occured just before this function was called
- logmsg (9, 5, "matrix field $field has value ${$field}");
+ logmsg (9, 4, "matrix field $field has value ${$field}");
if (exists $$line{$field}) {
if ($fieldhash) {
$fieldhash = "$fieldhash:$$line{$field}";
} else {
$fieldhash = "$$line{$field}";
}
} else {
if ($fieldhash) {
$fieldhash = "$fieldhash:${$field}";
} else {
if ( ${$field} ) {
$fieldhash = "${$field}";
} else {
- logmsg (1, 6, "$field not found in \"$$line{line}\" with regex $$cfghashref{rules}{$rule}{cmdregex}");
- logmsg (1, 6, "line hash:");
- print Dumper(%$line) if $DEBUG >= 1;
+ logmsg (1, 4, "$field not found in \"$$line{line}\" with regex $$cfghashref{rules}{$rule}{cmdregex}");
+ logmsg (1, 4, "line hash:");
+ printhash($line) if $DEBUG >= 1;
}
}
}
}
use strict 'refs';
if ($$cfghashref{rules}{$rule}{targetfield}) {
- logmsg (1, 5, "Setting cmdfield (field $$cfghashref{rules}{$rule}{targetfield}) to ${$$cfghashref{rules}{$rule}{targetfield}}");
+ logmsg (1, 4, "Setting cmdfield (field $$cfghashref{rules}{$rule}{targetfield}) to ${$$cfghashref{rules}{$rule}{targetfield}}");
$cmdfield = ${$$cfghashref{rules}{$rule}{targetfield}};
}
#if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
$$reshashref{$resultsrule}{$fieldhash}{count}++;
- logmsg (5, 5, "$$reshashref{$resultsrule}{$fieldhash}{count} matches for rule $rule so far from $fieldhash");
+ logmsg (5, 4, "$$reshashref{$resultsrule}{$fieldhash}{count} matches for rule $rule so far from $fieldhash");
#} els
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
$$reshashref{$resultsrule}{$fieldhash}{sum} = $$reshashref{$resultsrule}{$fieldhash}{sum} + $cmdfield;
- logmsg (5, 5, "Adding $cmdfield to total (now $$reshashref{$resultsrule}{$fieldhash}{sum}) for rule $rule so far from $fieldhash");
+ logmsg (5, 4, "Adding $cmdfield to total (now $$reshashref{$resultsrule}{$fieldhash}{sum}) for rule $rule so far from $fieldhash");
if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
- logmsg (5, 5, "Average is ".$$reshashref{$resultsrule}{$fieldhash}{sum} / $$reshashref{$resultsrule}{$fieldhash}{count}." for rule $rule so far from $fieldhash");
+ logmsg (5, 4, "Average is ".$$reshashref{$resultsrule}{$fieldhash}{sum} / $$reshashref{$resultsrule}{$fieldhash}{count}." for rule $rule so far from $fieldhash");
}
}
for my $key (keys %{$$reshashref{$resultsrule}}) {
- logmsg (5, 5, "key $key for rule:$rule with $$reshashref{$resultsrule}{$key}{count} matches");
+ logmsg (5, 3, "key $key for rule:$rule with $$reshashref{$resultsrule}{$key}{count} matches");
}
- logmsg (5, 5, "$fieldhash matches for rule $rule so far from matrix: $$cfghashref{rules}{$rule}{cmdmatrix}");
+ logmsg (5, 2, "$fieldhash matches for rule $rule so far from matrix: $$cfghashref{rules}{$rule}{cmdmatrix}");
} else {
- logmsg (5, 5, "cmdmatrix is not set for $rule");
+ logmsg (5, 2, "cmdmatrix is not set for $rule");
#if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
$$reshashref{$resultsrule}{count}++;
- logmsg (5, 5, "$$reshashref{$resultsrule}{count} lines match rule $rule so far");
+ logmsg (5, 3, "$$reshashref{$resultsrule}{count} lines match rule $rule so far");
# } els
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
$$reshashref{$resultsrule}{sum} = $$reshashref{$resultsrule}{sum} + $cmdfield;
- logmsg (5, 5, "$$reshashref{$resultsrule}{sum} lines match rule $rule so far");
+ logmsg (5, 3, "$$reshashref{$resultsrule}{sum} lines match rule $rule so far");
}
}
- logmsg(5, 4, " ... Finished actioning resultsrule = $rule");
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
- logmsg(5, 4, " and I was called by ... ".&whowasi);
-# profile( whoami(), whowasi() );
+
+ profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
-
- # An empty or null $value = no match
- logmsg(5, 3, " and I was called by ... ".&whowasi);
-# profile( whoami(), whowasi() );
- logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
- if ($value) {
- if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
- logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
- $match = 1;
- } else {
- logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
- }
+
+ profile( whoami(), whowasi() );
+ if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^*$/ ) {
+ logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
+ $match = 1;
} else {
- logmsg(7, 5, "\$value is null, no match");
+ logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
}
sub matchingrules {
my $cfghashref = shift;
my $param = shift;
my $matchref = shift;
my $value = shift;
- logmsg(5, 3, " and I was called by ... ".&whowasi);
- logmsg (6, 3, "param:$param");
- logmsg (6, 3, "value:$value") if $value;
- logmsg (3, 2, "$param, match count: ".keys(%{$matchref}) );
+ profile( whoami(), whowasi() );
+
+ logmsg (6, 3, "param:$param ");
+ logmsg (6,3, "value:$value");
+ logmsg (3, 2, " $param, match count: ".keys(%{$matchref})." value: $value");
if (keys %{$matchref} == 0) {
# Check all rules as we haevn't had a match yet
foreach my $rule (keys %{$cfghashref->{rules} } ) {
checkrule($cfghashref, $param, $matchref, $rule, $value);
}
} else {
# As we've allready had a match on the rules, only check those that matched in earlier rounds
# key in %matches is the rule that matches
foreach my $rule (keys %{$matchref}) {
checkrule($cfghashref, $param, $matchref, $rule, $value);
}
}
}
sub checkrule {
my $cfghashref = shift;
my $param = shift;
my $matches = shift;
my $rule = shift; # key to %matches
my $value = shift;
+ profile( whoami(), whowasi() );
logmsg(2, 1, "Checking rule ($rule) & param ($param) for matches against: $value");
- logmsg(5, 3, " and I was called by ... ".&whowasi);
+
my $paramref = \@{ $$cfghashref{rules}{$rule}{$param} };
defaultregex($paramref); # This should be done when reading the config
foreach my $index (@{ $paramref } ) {
my $match = matchregex($index, $value);
if ($$index{negate} ) {
if ( $match) {
delete $$matches{$rule};
- logmsg (5, 5, "matches $index->{regex} for param \'$param\', but negative rule is set, so removing rule $match from list.");
+ logmsg (5, 5, "matches $index->{regex} for param '$param\', but negative rule is set, so removing rule $match from list.");
} else {
$$matches{$rule} = "match" if $match;
- logmsg (5, 5, "Doesn't match for $index->{regex} for param \'$param\', but negative rule is set, so leaving rule $match on list.");
+ logmsg (5, 5, "Doesn't match for $index->{regex} for param '$param\', but negative rule is set, so leaving rule $match on list.");
}
} elsif ($match) {
$$matches{$rule} = "match" if $match;
- logmsg (5, 4, "matches $index->{regex} for param \'$param\', leaving rule $match on list.");
+ logmsg (5, 4, "matches $index->{regex} for param '$param\', leaving rule $match on list.");
} else {
delete $$matches{$rule};
- logmsg (5, 4, "doesn't match $index->{regex} for param \'$param\', removing rule $match from list.");
+ logmsg (5, 4, "doesn't match $index->{regex} for param '$param\', removing rule $match from list.");
}
} # for each regex hash in the array
logmsg (3, 2, "matches ".keys (%{$matches})." matches after checking rules for $param");
}
-sub whoami { (caller(1) )[3] }
-sub whowasi { (caller(2) )[3] }
+=oldcode
+sub matchingrules {
+ my $cfghashref = shift;
+ my $param = shift;
+ my $matches = shift;
+ my $value = shift;
+
+ profile( whoami(), whowasi() );
+ logmsg (3, 2, "param: $param, matches: $matches, value: $value");
+ if (keys %{$matches} == 0) {
+ # Check all rules as we haevn't had a match yet
+ foreach my $rule (keys %config) {
+ $$cfghashref{rules}{$rule}{$param} = "(.*)" unless exists ($$cfghashref{rules}{$rule}{$param});
+ logmsg (5, 3, "Does $value match /$$cfghashref{rules}{$rule}{$param}/ ??");
+ if ($value =~ /$$cfghashref{rules}{$rule}{$param}/ or $$cfghashref{rules}{$rule}{$param} =~ /^*$/ ) {
+ logmsg (5, 4, "Matches rule: $rule");
+ $$matches{$rule} = "match";
+ }
+ }
+ } else {
+ # As we've allready had a match on the rules, only check those that matched in earlier rounds
+ foreach my $match (keys %{$matches}) {
+ if (exists ($$cfghashref{rules}{$match}{$param}) ) {
+ logmsg (5, 4, "Does value: "$value\" match \'$$cfghashref{rules}{$match}{$param}\' for param $param ??");
+ if ($$cfghashref{rules}{$match}{"${param}negat"}) {
+ logmsg (5, 5, "Doing a negative match");
+ }
+ } else {
+ logmsg (5, 3, "No rule for value: "$value\" in rule $match, leaving on match list.");
+ $$cfghashref{rules}{$match}{$param} = "(.*)";
+ }
+ if ($$cfghashref{rules}{$match}{"${param}negat"}) {
+ if ($value =~ /$$cfghashref{rules}{$match}{$param}/ or $$cfghashref{rules}{$match}{$param} =~ /^*$/ ) {
+ delete $$matches{$match};
+ logmsg (5, 5, "matches $$cfghashref{rules}{$match}{$param} for param '$param\', but negative rule is set, so removing rule $match from list.");
+ } else {
+ logmsg (5, 5, "Doesn't match for $$cfghashref{rules}{$match}{$param} for param '$param\', but negative rule is set, so leaving rule $match on list.");
+ }
+ } elsif ($value =~ /$$cfghashref{rules}{$match}{$param}/ or $$cfghashref{rules}{$match}{$param} =~ /^*$/ ) {
+ logmsg (5, 4, "matches $$cfghashref{rules}{$match}{$param} for param '$param\', leaving rule $match on list.");
+ } else {
+ delete $$matches{$match};
+ logmsg (5, 4, "doesn't match $$cfghashref{rules}{$match}{$param} for param '$param\', removing rule $match from list.");
+ }
+ }
+ }
+ logmsg (3, 2, keys (%{$matches})." matches after checking rules for $param");
+}
+=cut
+
+
+sub whoami { ( caller(1) )[3] }
+sub whowasi { ( caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
+print "$DEBUG";
if ($DEBUG >= $level) {
for my $i (0..$indent) {
print STDERR " ";
}
print STDERR whowasi."(): $msg\n";
}
}
sub profile {
my $caller = shift;
my $parent = shift;
-# $profile{$parent}{$caller}++;
+ $profile{$parent}{$caller}++;
}
sub profilereport {
- print Dumper(%profile);
+ pp(%profile);
}
|
mikeknox/LogParse | 8b8a1ddc5707bc8db82550226e4b6534bfe52a8d | format data loaded fully | diff --git a/logparse.pl b/logparse.pl
index 1626550..a87ec99 100644
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,941 +1,965 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=head1 NAME
logparse - syslog analysis tool
=cut
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
Describe config file for log parse / summary engine
Input fields from syslog:
Date, time, server, application, facility, ID, message
=head3 Config line
/server regex/, /app regex/, /facility regex/, /msg regex/, $ACTIONS
Summaries are required at various levels, from total instances to total sizes to server summaries.
=head2 ACTIONS
COUNT - Just list the total number of matches
SUM[x] - Report the sum of field x of all matches
SUM[x], /regex/ - Apply regex to msg field of matches and report the sum of field x from that regex
SUM[x], /regex/, {y,z} - Apply regex to msg field of matches and report the sum of field x from that regex for fields y & z
AVG[x], /regex/, {y,z} - Apply regex to msg field of matches and report the avg of field x from that regex for fields y & z
COUNT[x], /regex/, {y,z} - Apply regex to msg field of matches and report the count of field x from that regex for matching fields y & z
Each entry can test or regex, if text interpret as regex /^string$/
Sample entry...
*, /rshd/, *, *, COUNT /connect from (.*)/, {1}
=head2 BUGS:
See http://github.com/mikeknox/LogParse/issues
=head2 FORMAT stanza
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=head2 TODO:
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=cut
# expects data on std in
use strict;
use Getopt::Std;
#no strict 'refs';
#use Data::Dump qw(pp);
use Data::Dumper qw(Dumper);
#use utils;
#use logparse;
# Globals
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my $CONFIGFILE="logparse.conf";
my %cfghash;
my %reshash;
my $cmdcount = 0;
my $UNMATCHEDLINES = 1;
my $SYSLOGFILE = "/var/log/messages";
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
getopt('cdl', \%opts);
$DEBUG = $opts{d} if $opts{d};
$CONFIGFILE = $opts{c} if $opts{c};
$SYSLOGFILE = $opts{l} if $opts{l};
loadcfg (\%cfghash, $CONFIGFILE, $cmdcount);
+print Dumper(%cfghash);
+#processlogfile(\%cfghash, \%reshash, $SYSLOGFILE);
+#report(\%cfghash, \%reshash);
+#profilereport();
-processlogfile(\%cfghash, \%reshash, $SYSLOGFILE);
-
-report(\%cfghash, \%reshash);
-
-profilereport();
exit 0;
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfile = shift;
- logmsg (1, 0, "processing $logfile ...");
+ logmsg(1, 0, "processing $logfile ...");
logmsg(5, 1, " and I was called by ... ".&whowasi);
open (LOGFILE, "<$logfile") or die "Unable to open $SYSLOGFILE for reading...";
while (<LOGFILE>) {
- my $facility;
+ my $facility = "";
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
- logmsg (5, 1, "Processing next line");
+ logmsg(5, 1, "Processing next line");
($line{mth}, $line{date}, $line{time}, $line{svr}, $line{app}, $line{msg}) = split (/\s+/, $line{line}, 6);
- logmsg (9, 2, "mth: $line{mth}, date: $line{date}, time: $line{time}, svr: $line{svr}, app: $line{app}, msg: $line{msg}");
-
+ logmsg(9, 2, "mth: $line{mth}, date: $line{date}, time: $line{time}, svr: $line{svr}, app: $line{app}, msg: $line{msg}");
+ logmsg(9, 1, "Checking line: $line{line}");
+ logmsg(9, 1, "msg: $line{msg}");
+
if ($line{msg} =~ /^\[/) {
($line{facility}, $line{msg}) = split (/]\s+/, $line{msg}, 2);
$line{facility} =~ s/\[//;
+ logmsg(9, 1, "facility: $line{facility}");
}
- logmsg (9, 1, "Checking line: $line{line}");
- logmsg (9, 1, "facility: $line{facility}");
- logmsg (9, 1, "msg: $line{msg}");
-
+# These need to be abstracted out per description in the FORMAT stanza
my %matches;
my %matchregex = ("svrregex", "svr", "appregex", "app", "facregex", "facility", "msgregex", "line");
for my $param ("appregex", "facregex", "msgregex", "svrregex") {
+ $line{ $matchregex{$param} } = "" unless $line{ $matchregex{$param} }; # this really should be elsewhere, it's a hack
matchingrules($cfghashref, $param, \%matches, $line{ $matchregex{$param} } );
}
logmsg(9, 2, keys(%matches)." matches so far");
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} and next unless keys %matches > 0;
logmsg(9,1,"Results hash ...");
Dumper(%$reshashref);
if ($line{msg} =~ /message repeated/ and exists $svrlastline{$line{svr} }{line}{msg} ) { # and keys %{$svrlastline{ $line{svr} }{rulematches}} ) {
logmsg (9, 2, "last message repeated and matching svr line");
my $numrepeats = 0;
if ($line{msg} =~ /message repeated (.*) times/) {
$numrepeats = $1;
}
logmsg(9, 2, "Last message repeated $numrepeats times");
for my $i (1..$numrepeats) {
for my $rule (keys %{$svrlastline{ $line{svr} }{rulematches} } ) {
logmsg (5, 3, "Applying cmd for rule $rule: $$cfghashref{rules}{$rule}{cmd} - as prelim regexs pass");
actionrule($cfghashref, $reshashref, $rule, \%{ $svrlastline{$line{svr} }{line} }); # if $actrule == 0;
}
}
} else {
logmsg (5, 2, "No recorded last line for $line{svr}") if $line{msg} =~ /message repeated/;
logmsg (9, 2, "msg: $line{msg}");
%{ $svrlastline{$line{svr} }{line} } = %line;
# track line
# track matching rule(s)
logmsg (3, 2, keys (%matches)." matches after checking all rules");
if (keys %matches > 0) {
logmsg (5, 2, "svr & app & fac & msg matched rules: ");
logmsg (5, 2, "matched rules ".keys(%matches)." from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmpmatches = %matches;
for my $rule (keys %tmpmatches) {
my $result = actionrule($cfghashref, $reshashref, $rule, \%line);
delete $matches{$rule} unless $result ;
$actrule = $result unless $actrule;
logmsg (5, 3, "Applying cmd from rule $rule: $$cfghashref{rules}{$rule}{cmd} as passed prelim regexes");
logmsg (10, 4, "an action rule matched: $actrule");
}
logmsg (10, 4, "an action rule matched: $actrule");
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if $actrule == 0;
%{$svrlastline{$line{svr} }{rulematches}} = %matches unless ($line{msg} =~ /last message repeated d+ times/);
logmsg (5, 2, "setting lastline match for server: $line{svr} and line:\n$line{line}");
logmsg (5, 3, "added matches for $line{svr} for rules:");
for my $key (keys %{$svrlastline{$line{svr} }{rulematches}}) {
logmsg (5, 4, "$key");
}
logmsg (5, 3, "rules from line $line{line}");
} else {
logmsg (5, 2, "No match: $line{line}");
if ($svrlastline{$line{svr} }{unmatchedline}{msg} eq $line{msg} ) {
$svrlastline{$line{svr} }{unmatchedline}{count}++;
logmsg (9, 3, "$svrlastline{$line{svr} }{unmatchedline}{count} instances of msg: $line{msg} on $line{svr}");
} else {
$svrlastline{$line{svr} }{unmatchedline}{count} = 0 unless exists $svrlastline{$line{svr} }{unmatchedline}{count};
if ($svrlastline{$line{svr} }{unmatchedline}{msg} and $svrlastline{$line{svr} }{unmatchedline}{count} >= 1) {
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = "$line{svr}: Last unmatched message repeated $svrlastline{$line{svr} }{unmatchedline}{count} timesn";
} else {
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line};
$svrlastline{$line{svr} }{unmatchedline}{msg} = $line{msg};
}
$svrlastline{$line{svr} }{unmatchedline}{count} = 0;
}
logmsg (5, 2, "set unmatched{ $line{svr} }{msg} to $svrlastline{$line{svr} }{unmatchedline}{msg} and count to: $svrlastline{$line{svr} }{unmatchedline}{count}");
}
}
logmsg (5, 1, "finished processing line");
}
foreach my $server (keys %svrlastline) {
if ( $svrlastline{$server}{unmatchedline}{count} >= 1) {
logmsg (9, 2, "Added record #".( $#{$$reshashref{nomatch}} + 1 )." for unmatched results");
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = "$server: Last unmatched message repeated $svrlastline{$server }{unmatchedline}{count} timesn";
}
}
logmsg (1, 0, "Finished processing $logfile.");
}
sub parsecfgline {
my $line = shift;
#profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $cmd = "";
my $arg = "";
chomp $line;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 4, "line: ${line}");
if ($line =~ /^#|\s+#/ ) {
logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
} elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
} else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
$arg = "" unless $arg;
$cmd = "" unless $cmd;
}
logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
sub loadcfg {
my $cfghashref = shift;
my $cfgfile = shift;
my $cmdcount = shift;
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $rule = -1;
my $bracecount = 0;
my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "bracecount:$bracecount");
logmsg(6, 2, "stanzatype:$stanzatype");
my $cmd; my $arg;
($cmd, $arg) = parsecfgline($line);
next unless $cmd;
logmsg(6, 2, "rule:$rule");
logmsg(6, 2, "cmdcount:$cmdcount");
- logmsg (6, 2, "cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
+ logmsg(6, 2, "cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
if ($bracecount == 0 ) {
for ($cmd) {
if (/RULE/) {
if ($arg =~ /(.*)\s+\{/) {
$rule = $1;
- logmsg (9, 3, "rule (if) is now: $rule");
+ logmsg(9, 3, "rule (if) is now: $rule");
} else {
$rule = $cmdcount++;
- logmsg (9, 3, "rule (else) is now: $rule");
+ logmsg(9, 3, "rule (else) is now: $rule");
} # if arg
$stanzatype = "rule";
+ unless (exists $$cfghashref{formats}) {
+ logmsg(0, 0, "Aborted. Error, rule encounted before format defined.");
+ exit 2;
+ }
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rule");
} elsif (/FORMAT/) {
if ($arg =~ /(.*)\s+\{/) {
$rule = $1;
} # if arg
$stanzatype = "format";
logmsg(6, 2, "stanzatype updated to: $stanzatype");
} elsif (/\}/) {
# if bracecount = 0, cmd may == "}", so ignore
} else {
print STDERR "Error: $cmd didn't match any stanzasn\n";
} # if cmd
} # for cmd
} # bracecount == 0
if ($cmd =~ /\{/ or $arg =~ /\{/) {
$bracecount++;
} elsif ($cmd =~ /\}/ or $arg =~ /\}/) {
$bracecount--;
} # if cmd or arg
if ($bracecount > 0) { # else bracecount
for ($stanzatype) {
if (/rule/) {
logmsg (6, 2, "About to call processrule ... cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
processrule( \%{ $$cfghashref{rules}{$rule} }, $rule, $cmd, $arg);
} elsif (/format/) {
logmsg (6, 2, "About to call processformat ... cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
processformat( \%{$$cfghashref{formats}{$rule}} , $rule, $cmd, $arg);
} # if stanzatype
} #if stanzatype
} else {# else bracecount
logmsg (1, 2, "ERROR: bracecount: $bracecount. How did it go negative??");
} # bracecount
} # while
close CFGFILE;
logmsg (5, 1, "Config Hash contents:");
&Dumper( %$cfghashref );
logmsg (1, 0, "finished processing cfg: $cfgfile");
} # sub loadcfg
sub processformat {
my $cfghashref = shift;
my $rule = shift; # name of the rule to be processed
my $cmd = shift;
my $arg = shift;
#profile( whoami(), whowasi() );
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (5, 4, "Processing rule: $rule");
logmsg(9, 5, "passed cmd: $cmd");
logmsg(9, 5, "passed arg: $arg");
next unless $cmd;
for ($cmd) {
if (/DELIMITER/) {
$$cfghashref{delimiter} = $arg;
logmsg (5, 1, "Config Hash contents:");
- &Dumper( %$cfghashref );
+ &Dumper( %$cfghashref ) if $DEBUG >= 9;
} elsif (/FIELDS/) {
- $$cfghashref{fields} = $arg;
+ $$cfghashref{totalfields} = $arg;
+ for my $i(1..$$cfghashref{totalfields}) {
+ $$cfghashref{fields}{byindex}{$i} = "$i"; # map index to name
+ $$cfghashref{fields}{byname}{$i} = "$i"; # map name to index
+ }
} elsif (/FIELD(\d+)/) {
logmsg(6, 6, "FIELD#: $1 arg:$arg");
+ $$cfghashref{fields}{byindex}{$1} = "$arg"; # map index to name
+ $$cfghashref{fields}{byname}{$arg} = "$1"; # map name to index
+ if (exists($$cfghashref{fields}{byname}{$1}) ) {
+ delete($$cfghashref{fields}{byname}{$1});
+ }
} elsif (/^\}$/) {
} elsif (/^\{$/) {
} else {
print "Error: $cmd didn't match any known fields\n\n";
} # if cmd
} # for cmd
logmsg (5, 4, "Finished processing rule: $rule");
} # sub processformat
sub processrule {
my $cfghashref = shift;
my $rule = shift; # name of the rule to be processed
my $cmd = shift;
my $arg = shift;
#profile( whoami(), whowasi() );
logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (5, 4, "Processing $rule with cmd: $cmd and arg: $arg");
next unless $cmd;
for ($cmd) {
if (/HOST/) {
# fields
extractregex ($cfghashref, "svrregex", $arg, $rule);
} elsif (/APP($|\s+)/) {
extractregex ($cfghashref, "appregex", $arg, $rule);
} elsif (/FACILITY/) {
extractregex ($cfghashref, "facregex", $arg, $rule);
} elsif (/MSG/) {
extractregex ($cfghashref, "msgregex", $arg, $rule);
} elsif (/CMD/) {
extractregex ($cfghashref, "cmd", $arg, $rule) unless $arg =~ /\{/;
} elsif (/^REGEX/) {
extractregexold ($cfghashref, "cmdregex", $arg, $rule);
} elsif (/MATCH/) {
extractregexold ($cfghashref, "cmdmatrix", $arg, $rule);
$$cfghashref{cmdmatrix} =~ s/\s+//g; # strip all whitespace
} elsif (/IGNORE/) {
$$cfghashref{cmd} = $cmd;
} elsif (/COUNT/) {
$$cfghashref{cmd} = $cmd;
} elsif (/SUM/) {
extractregex ($cfghashref, "targetfield", $arg, $rule);
$$cfghashref{targetfield} =~ s/\s+//g; # strip all whitespace
$$cfghashref{cmd} = $cmd;
} elsif (/AVG/) {
extractregex ($cfghashref, "targetfield", $arg, $rule);
$$cfghashref{targetfield} =~ s/\s+//g; # strip all whitespace
$$cfghashref{cmd} = $cmd;
} elsif (/TITLE/) {
$$cfghashref{rpttitle} = $arg;
$$cfghashref{rpttitle} = $1 if $$cfghashref{rpttitle} =~ /^\"(.*)\"$/;
} elsif (/LINE/) {
$$cfghashref{rptline} = $arg;
$$cfghashref{rptline} = $1 if $$cfghashref{rptline} =~ /\^"(.*)\"$/;
} elsif (/APPEND/) {
$$cfghashref{appendrule} = $arg;
logmsg (1, 0, "*** Setting append for $rule to $arg");
} elsif (/REPORT/) {
} elsif (/^\}$/) {
# $bracecount{closed}++;
} elsif (/^\{$/) {
# $bracecount{open}++;
} else {
print "Error: $cmd didn't match any known fields\n\n";
}
} # for
logmsg (5, 1, "Finished processing rule: $rule");
logmsg (9, 1, "Config hash after running processrule");
Dumper(%$cfghashref);
} # sub processrule
sub extractregexold {
# Keep the old behaviour
my $cfghashref = shift;
my $param = shift;
my $arg = shift;
my $rule = shift;
# profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
my $paramnegat = $param."negate";
logmsg (5, 1, "rule: $rule param: $param arg: $arg");
if ($arg =~ /^!/) {
$arg =~ s/^!//g;
$$cfghashref{$paramnegat} = 1;
} else {
$$cfghashref{$paramnegat} = 0;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^\{//;
$arg =~ s/\}$//;
$$cfghashref{$param} = $arg;
logmsg (5, 2, "$param = $$cfghashref{$param}");
}
sub extractregex {
# Put the matches into an array, but would need to change how we handle negates
# Currently the negate is assigned to match group (ie facility or host) or rather than
# an indivudal regex, not an issue immediately because we only support 1 regex
# Need to assign the negate to the regex
# Make the structure ...
# $$cfghashref{rules}{$rule}{$param}[$index] is a hash with {regex} and {negate}
my $cfghashref = shift;
my $param = shift;
my $arg = shift;
my $rule = shift;
my $index = 0;
# profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
logmsg (1, 3, " rule: $rule for param $param with arg $arg ");
if (exists $$cfghashref{$param}[0] ) {
$index = @{$$cfghashref{$param}};
} else {
$$cfghashref{$param} = ();
}
my $regex = \%{$$cfghashref{$param}[$index]};
$$regex{negate} = 0;
logmsg (5, 1, "$param $arg");
if ($arg =~ /^!/) {
$arg =~ s/^!//g;
$$regex{negate} = 1;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^{//;
$arg =~ s/}$//;
$$regex{regex} = $arg;
logmsg (9, 3, "$regex\{regex\} = $$regex{regex} & \$regex\{negate\} = $$regex{negate}");
logmsg (5,2, "$index = $index");
logmsg (5, 2, "$param \[$index\]\{regex\} = $$cfghashref{$param}[$index]{regex}");
logmsg (5, 2, "$param \[$index\]\{negate\} = $$cfghashref{$param}[$index]{negate}");
for (my $i=0; $i<=$index; $i++)
{
logmsg (5,1, "index: $i");
foreach my $key (keys %{$$cfghashref{$param}[$i]}) {
logmsg (5, 2, "$param \[$i\]\{$key\} = $$cfghashref{$param}[$i]{$key}");
}
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
my $rpthashref = shift;
logmsg(1, 0, "Ruuning report");
# profile( whoami(), whowasi() );
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...");
Dumper(%$reshashref) if $DEBUG >= 5;
print "\n\nNo match for lines:\n";
foreach my $line (@{@$reshashref{nomatch}}) {
print "\t$line";
}
print "\n\nSummaries:\n";
for my $rule (sort keys %$reshashref) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{rules}{$rule}{rpttitle})) {
print "$$cfghashref{rules}{$rule}{rpttitle}\n";
} else {
logmsg (4, 2, "Rule: $rule");
}
for my $key (keys %{$$reshashref{$rule}} ) {
if (exists ($$cfghashref{rules}{$rule}{rptline})) {
print "\t".rptline($cfghashref, $reshashref, $rpthashref, $rule, $key)."\n";
} else {
print "\t$$rpthashref{$rule}{$key}: $key\n";
}
}
print "\n";
}
}
sub rptline {
my $cfghashref = shift;
my $reshashref = shift;
my $rpthashref = shift;
my $rule = shift;
my $key = shift;
my $line = $$cfghashref{rules}{$rule}{rptline};
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
# profile( whoami(), whowasi() );
logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (3, 2, "Starting with rule:$rule");
logmsg (9, 3, "key: $key");
my @fields = split /:/, $key;
logmsg (9, 3, "line: $line");
logmsg(9, 3, "subsituting {x} with $$rpthashref{$rule}{$key}{count}");
$line =~ s/\{x\}/$$rpthashref{$rule}{$key}{count}/;
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM") {
$line =~ s/\{s\}/$$rpthashref{$rule}{$key}{sum}/;
}
if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
my $avg = $$rpthashref{$rule}{$key}{sum} / $$reshashref{$rule}{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{a\}/$avg/;
}
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "$fields[$field] = $fields[$i]");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
return $line;
}
sub actionrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{rules}{$rule} but would break append
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $value;
my $retval = 0; my $resultsrule;
# profile( whoami(), whowasi() );
logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg (9, 2, "rule: $rule");
if (exists ($$cfghashref{rules}{$rule}{appendrule})) {
$resultsrule = $$cfghashref{rules}{$rule}{appendrule};
} else {
$resultsrule = $rule;
}
+
+ unless ($$cfghashref{rules}{cmdregex}) {
+ $$cfghashref{rules}{cmdregex} = "";
+ }
logmsg (5, 3, "rule: $rule");
logmsg (5, 4, "results goto: $resultsrule");
- logmsg (5, 4, "cmdregex: $}{cmdregex}");
+ logmsg (5, 4, "cmdregex: $$cfghashref{rules}{cmdregex}");
logmsg (5, 4, "CMD negative regex: $$cfghashref{rules}{$rule}{cmdregexnegat}");
logmsg (5, 4, "line: $$line{line}");
if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /IGNORE/) {
if (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "rule $rule does matches and is a positive IGNORE rule");
}
} else {
logmsg (5, 4, "rule $rule matches and is an IGNORE rule");
$retval = 1;
}
} elsif (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
if ( not $$cfghashref{rules}{$rule}{cmdregexnegat} ) {
if ( $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "Positive match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
} elsif ($$cfghashref{rules}{$rule}{cmdregexnegat}) {
if ( $$line{line} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "Negative match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
}
} else {
logmsg (5, 4, "No cmd regex, implicit match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
if ($retval == 0) {
logmsg (5, 4, "line does not match cmdregex for rule: $rule");
}
return $retval;
}
sub actionrulecmd
{
my $cfghashref = shift;
my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift;
my $resultsrule = shift;
#3 profile( whoami(), whowasi() );
logmsg (5, 3, " and I was called by ... ".&whowasi);
logmsg (2, 2, "actioning rule $rule for line: $$line{line}");
# This sub contains the first half of the black magic
# The results from the regex's that are applied later
# are used in actioncmdmatrix()
#
# create a matrix that can be used for matching for the black magic happens
# Instead of the string cmdmatrix
# make a hash of matchmatrix{<match field#>} = <cmdregex field #>
# 2 arrays ...
# fieldnums ... the <match field #'s> of matchmatrix{}
# fieldnames ... the named matches of matchmatrix{}, these match back to the names of the fields
# from the file FORMAT
#
my @tmpmatrix = split (/,/, $$cfghashref{rules}{$rule}{cmdmatrix});
my @matrix = ();
for my $val (@tmpmatrix) {
if ($val =~ /(\d+)/ ) {
push @matrix, $val;
} else {
logmsg(3,3, "Not adding val:$val to matrix");
}
}
logmsg(3, 3, "matrix: @matrix");
#
if (not $$cfghashref{rules}{$rule}{cmdregex}) {
$$cfghashref{rules}{$rule}{cmdregex} = "(.*)";
logmsg (5, 3, "rule did not define cmdregex, replacing with global match");
}
if ( exists $$cfghashref{rules}{$rule}{cmd}) {
logmsg (5, 3, "Collecting data from cmd $$cfghashref{rules}{$rule}{cmd}");
logmsg (5, 3, "rule $rule matches cmd") if $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/;
}
if (not exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
logmsg (5, 3, "No cmd regex, calling actioncmdmatrix");
actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
} elsif ($$cfghashref{rules}{$rule}{cmdregexnegat} ) {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 3, "Negative match, calling actioncmdmatrix");
actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
}
} else {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 3, "Positive match, calling actioncmdmatrixnline hash:");
print Dumper($line) if $DEBUG >= 5;
actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
}
}
}
sub printhash
{
# profile( whoami(), whowasi() );
my $line = shift; # hash passed by ref, DO NOT mod
foreach my $key (keys %{ $line} )
{
logmsg (9, 5, "$key: $$line{$key}");
}
}
sub actioncmdmatrix
{
my $cfghashref = shift;
my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift; # Name or ID of rule thats been matched
my $resultsrule = shift; # Name or ID of rule which contains the result set to be updated
my $matrixref = shift; # arrayref
logmsg(5, 4, " ... actioning resultsrule = $rule");
logmsg(5, 5, " and I was called by ... ".&whowasi);
logmsg(9, 5, "Line hash ...");
print Dumper(%$line);
#profile( whoami(), whowasi() );
my $cmdmatrix = $$cfghashref{rules}{$rule}{cmdmatrix};
#my @matrix = shift; #split (/,/, $cmdmatrix);
my $fieldhash;
my $cmdfield;
# @matrix - array of parameters that are used in results
if ( exists ($$cfghashref{rules}{$rule}{cmdfield}) ) {
$cmdfield = ${$$cfghashref{rules}{$rule}{cmdfield}};
}
if ( exists $$cfghashref{rules}{$rule}{cmdmatrix}) {
logmsg (5, 5, "Collecting data for matrix $$cfghashref{rules}{$rule}{cmdmatrix}");
print Dumper(@$matrixref);
logmsg (5, 5, "Using matrix @$matrixref");
# this is where "strict refs" breaks things
# sample: @matrix = svr,1,4,5
# error ... can't use string ("svr") as a SCALAR ref while "strict refs" in use
#
# soln: create a temp array which only has the field #'s and match that
# might need a hash to match
no strict 'refs'; # turn strict refs off just for this section
foreach my $field (@$matrixref) {
# This is were the black magic occurs, ${$field} causes becomes $1 or $2 etc
# and hence contains the various matches from the previous regex match
# which occured just before this function was called
logmsg (9, 5, "matrix field $field has value ${$field}");
if (exists $$line{$field}) {
if ($fieldhash) {
$fieldhash = "$fieldhash:$$line{$field}";
} else {
$fieldhash = "$$line{$field}";
}
} else {
if ($fieldhash) {
$fieldhash = "$fieldhash:${$field}";
} else {
if ( ${$field} ) {
$fieldhash = "${$field}";
} else {
logmsg (1, 6, "$field not found in \"$$line{line}\" with regex $$cfghashref{rules}{$rule}{cmdregex}");
logmsg (1, 6, "line hash:");
print Dumper(%$line) if $DEBUG >= 1;
}
}
}
}
use strict 'refs';
if ($$cfghashref{rules}{$rule}{targetfield}) {
logmsg (1, 5, "Setting cmdfield (field $$cfghashref{rules}{$rule}{targetfield}) to ${$$cfghashref{rules}{$rule}{targetfield}}");
$cmdfield = ${$$cfghashref{rules}{$rule}{targetfield}};
}
#if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
$$reshashref{$resultsrule}{$fieldhash}{count}++;
logmsg (5, 5, "$$reshashref{$resultsrule}{$fieldhash}{count} matches for rule $rule so far from $fieldhash");
#} els
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
$$reshashref{$resultsrule}{$fieldhash}{sum} = $$reshashref{$resultsrule}{$fieldhash}{sum} + $cmdfield;
logmsg (5, 5, "Adding $cmdfield to total (now $$reshashref{$resultsrule}{$fieldhash}{sum}) for rule $rule so far from $fieldhash");
if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
logmsg (5, 5, "Average is ".$$reshashref{$resultsrule}{$fieldhash}{sum} / $$reshashref{$resultsrule}{$fieldhash}{count}." for rule $rule so far from $fieldhash");
}
}
for my $key (keys %{$$reshashref{$resultsrule}}) {
logmsg (5, 5, "key $key for rule:$rule with $$reshashref{$resultsrule}{$key}{count} matches");
}
logmsg (5, 5, "$fieldhash matches for rule $rule so far from matrix: $$cfghashref{rules}{$rule}{cmdmatrix}");
} else {
logmsg (5, 5, "cmdmatrix is not set for $rule");
#if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
$$reshashref{$resultsrule}{count}++;
logmsg (5, 5, "$$reshashref{$resultsrule}{count} lines match rule $rule so far");
# } els
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
$$reshashref{$resultsrule}{sum} = $$reshashref{$resultsrule}{sum} + $cmdfield;
logmsg (5, 5, "$$reshashref{$resultsrule}{sum} lines match rule $rule so far");
}
}
logmsg(5, 4, " ... Finished actioning resultsrule = $rule");
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
logmsg(5, 4, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
+
+ # An empty or null $value = no match
logmsg(5, 3, " and I was called by ... ".&whowasi);
# profile( whoami(), whowasi() );
- if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
- logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
- $match = 1;
+ logmsg(6, 4, "Does value($value) match regex /$$regex{regex}/");
+ if ($value) {
+ if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
+ logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
+ $match = 1;
+ } else {
+ logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
+ }
} else {
- logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
+ logmsg(7, 5, "\$value is null, no match");
}
}
sub matchingrules {
my $cfghashref = shift;
my $param = shift;
my $matchref = shift;
my $value = shift;
logmsg(5, 3, " and I was called by ... ".&whowasi);
logmsg (6, 3, "param:$param");
- logmsg (6, 3, "value:$value");
- logmsg (3, 2, "$param, match count: ".keys(%{$matchref})." value: $value");
+ logmsg (6, 3, "value:$value") if $value;
+ logmsg (3, 2, "$param, match count: ".keys(%{$matchref}) );
if (keys %{$matchref} == 0) {
# Check all rules as we haevn't had a match yet
foreach my $rule (keys %{$cfghashref->{rules} } ) {
checkrule($cfghashref, $param, $matchref, $rule, $value);
}
} else {
# As we've allready had a match on the rules, only check those that matched in earlier rounds
# key in %matches is the rule that matches
foreach my $rule (keys %{$matchref}) {
checkrule($cfghashref, $param, $matchref, $rule, $value);
}
}
}
sub checkrule {
my $cfghashref = shift;
my $param = shift;
my $matches = shift;
my $rule = shift; # key to %matches
my $value = shift;
logmsg(2, 1, "Checking rule ($rule) & param ($param) for matches against: $value");
logmsg(5, 3, " and I was called by ... ".&whowasi);
my $paramref = \@{ $$cfghashref{rules}{$rule}{$param} };
defaultregex($paramref); # This should be done when reading the config
foreach my $index (@{ $paramref } ) {
my $match = matchregex($index, $value);
if ($$index{negate} ) {
if ( $match) {
delete $$matches{$rule};
logmsg (5, 5, "matches $index->{regex} for param \'$param\', but negative rule is set, so removing rule $match from list.");
} else {
$$matches{$rule} = "match" if $match;
logmsg (5, 5, "Doesn't match for $index->{regex} for param \'$param\', but negative rule is set, so leaving rule $match on list.");
}
} elsif ($match) {
$$matches{$rule} = "match" if $match;
logmsg (5, 4, "matches $index->{regex} for param \'$param\', leaving rule $match on list.");
} else {
delete $$matches{$rule};
logmsg (5, 4, "doesn't match $index->{regex} for param \'$param\', removing rule $match from list.");
}
} # for each regex hash in the array
logmsg (3, 2, "matches ".keys (%{$matches})." matches after checking rules for $param");
}
sub whoami { (caller(1) )[3] }
sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
if ($DEBUG >= $level) {
for my $i (0..$indent) {
print STDERR " ";
}
print STDERR whowasi."(): $msg\n";
}
}
sub profile {
my $caller = shift;
my $parent = shift;
# $profile{$parent}{$caller}++;
}
sub profilereport {
print Dumper(%profile);
}
|
mikeknox/LogParse | 648454de155b09e9956063344284b1b1f0ab4875 | Working ... | diff --git a/logparse.pl b/logparse.pl
old mode 100755
new mode 100644
index fbe3b4d..1626550
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,982 +1,941 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=head1 NAME
logparse - syslog analysis tool
=cut
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
Describe config file for log parse / summary engine
Input fields from syslog:
Date, time, server, application, facility, ID, message
=head3 Config line
/server regex/, /app regex/, /facility regex/, /msg regex/, $ACTIONS
Summaries are required at various levels, from total instances to total sizes to server summaries.
=head2 ACTIONS
COUNT - Just list the total number of matches
SUM[x] - Report the sum of field x of all matches
SUM[x], /regex/ - Apply regex to msg field of matches and report the sum of field x from that regex
SUM[x], /regex/, {y,z} - Apply regex to msg field of matches and report the sum of field x from that regex for fields y & z
AVG[x], /regex/, {y,z} - Apply regex to msg field of matches and report the avg of field x from that regex for fields y & z
COUNT[x], /regex/, {y,z} - Apply regex to msg field of matches and report the count of field x from that regex for matching fields y & z
Each entry can test or regex, if text interpret as regex /^string$/
Sample entry...
*, /rshd/, *, *, COUNT /connect from (.*)/, {1}
=head2 BUGS:
See http://github.com/mikeknox/LogParse/issues
=head2 FORMAT stanza
FORMAT <name> {
DELIMITER <xyz>
FIELDS <x>
FIELD<x> <name>
}
=head2 TODO:
=head3 Config hash design
The config hash needs to be redesigned, particuarly to support other input log formats.
current layout:
all parameters are members of $$cfghashref{rules}{$rule}
Planned:
$$cfghashref{rules}{$rule}{fields} - Hash of fields
$$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
$$cfghashref{rules}{$rule}{cmd} - Command hash
$$cfghashref{rules}{$rule}{report} - Report hash
=head3 Command hash
Config for commands such as COUNT, SUM, AVG etc for a rule
$cmd
=head3 Report hash
Config for the entry in the report / summary report for a rule
=head3 regex hash
$regex{regex} = regex string
$regex{negate} = 1|0 - 1 regex is to be negated
=cut
# expects data on std in
use strict;
use Getopt::Std;
#no strict 'refs';
-use Data::Dump qw(pp);
-use Data::Dumper;
+#use Data::Dump qw(pp);
+use Data::Dumper qw(Dumper);
-use utils;
-use logparse;
+#use utils;
+#use logparse;
# Globals
my %profile;
my $DEBUG = 0;
my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my $CONFIGFILE="logparse.conf";
my %cfghash;
my %reshash;
my $cmdcount = 0;
my $UNMATCHEDLINES = 1;
my $SYSLOGFILE = "/var/log/messages";
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
getopt('cdl', \%opts);
$DEBUG = $opts{d} if $opts{d};
$CONFIGFILE = $opts{c} if $opts{c};
$SYSLOGFILE = $opts{l} if $opts{l};
loadcfg (\%cfghash, $CONFIGFILE, $cmdcount);
processlogfile(\%cfghash, \%reshash, $SYSLOGFILE);
report(\%cfghash, \%reshash);
profilereport();
exit 0;
-
sub processlogfile {
my $cfghashref = shift;
my $reshashref = shift;
my $logfile = shift;
- profile( whoami, whowasi );
logmsg (1, 0, "processing $logfile ...");
+ logmsg(5, 1, " and I was called by ... ".&whowasi);
open (LOGFILE, "<$logfile") or die "Unable to open $SYSLOGFILE for reading...";
while (<LOGFILE>) {
my $facility;
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
logmsg (5, 1, "Processing next line");
($line{mth}, $line{date}, $line{time}, $line{svr}, $line{app}, $line{msg}) = split (/\s+/, $line{line}, 6);
logmsg (9, 2, "mth: $line{mth}, date: $line{date}, time: $line{time}, svr: $line{svr}, app: $line{app}, msg: $line{msg}");
if ($line{msg} =~ /^\[/) {
($line{facility}, $line{msg}) = split (/]\s+/, $line{msg}, 2);
$line{facility} =~ s/\[//;
}
logmsg (9, 1, "Checking line: $line{line}");
logmsg (9, 1, "facility: $line{facility}");
logmsg (9, 1, "msg: $line{msg}");
my %matches;
my %matchregex = ("svrregex", "svr", "appregex", "app", "facregex", "facility", "msgregex", "line");
for my $param ("appregex", "facregex", "msgregex", "svrregex") {
matchingrules($cfghashref, $param, \%matches, $line{ $matchregex{$param} } );
}
logmsg(9, 2, keys(%matches)." matches so far");
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} and next unless keys %matches > 0;
logmsg(9,1,"Results hash ...");
- pp(%$reshashref);
+ Dumper(%$reshashref);
if ($line{msg} =~ /message repeated/ and exists $svrlastline{$line{svr} }{line}{msg} ) { # and keys %{$svrlastline{ $line{svr} }{rulematches}} ) {
logmsg (9, 2, "last message repeated and matching svr line");
my $numrepeats = 0;
if ($line{msg} =~ /message repeated (.*) times/) {
$numrepeats = $1;
}
logmsg(9, 2, "Last message repeated $numrepeats times");
for my $i (1..$numrepeats) {
for my $rule (keys %{$svrlastline{ $line{svr} }{rulematches} } ) {
logmsg (5, 3, "Applying cmd for rule $rule: $$cfghashref{rules}{$rule}{cmd} - as prelim regexs pass");
actionrule($cfghashref, $reshashref, $rule, \%{ $svrlastline{$line{svr} }{line} }); # if $actrule == 0;
}
}
} else {
logmsg (5, 2, "No recorded last line for $line{svr}") if $line{msg} =~ /message repeated/;
logmsg (9, 2, "msg: $line{msg}");
%{ $svrlastline{$line{svr} }{line} } = %line;
# track line
# track matching rule(s)
logmsg (3, 2, keys (%matches)." matches after checking all rules");
if (keys %matches > 0) {
logmsg (5, 2, "svr & app & fac & msg matched rules: ");
logmsg (5, 2, "matched rules ".keys(%matches)." from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmpmatches = %matches;
for my $rule (keys %tmpmatches) {
my $result = actionrule($cfghashref, $reshashref, $rule, \%line);
delete $matches{$rule} unless $result ;
$actrule = $result unless $actrule;
logmsg (5, 3, "Applying cmd from rule $rule: $$cfghashref{rules}{$rule}{cmd} as passed prelim regexes");
logmsg (10, 4, "an action rule matched: $actrule");
}
logmsg (10, 4, "an action rule matched: $actrule");
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if $actrule == 0;
%{$svrlastline{$line{svr} }{rulematches}} = %matches unless ($line{msg} =~ /last message repeated d+ times/);
- logmsg (5, 2, "setting lastline match for server: $line{svr} and line:n$line{line}");
+ logmsg (5, 2, "setting lastline match for server: $line{svr} and line:\n$line{line}");
logmsg (5, 3, "added matches for $line{svr} for rules:");
for my $key (keys %{$svrlastline{$line{svr} }{rulematches}}) {
logmsg (5, 4, "$key");
}
logmsg (5, 3, "rules from line $line{line}");
} else {
logmsg (5, 2, "No match: $line{line}");
if ($svrlastline{$line{svr} }{unmatchedline}{msg} eq $line{msg} ) {
$svrlastline{$line{svr} }{unmatchedline}{count}++;
logmsg (9, 3, "$svrlastline{$line{svr} }{unmatchedline}{count} instances of msg: $line{msg} on $line{svr}");
} else {
$svrlastline{$line{svr} }{unmatchedline}{count} = 0 unless exists $svrlastline{$line{svr} }{unmatchedline}{count};
if ($svrlastline{$line{svr} }{unmatchedline}{msg} and $svrlastline{$line{svr} }{unmatchedline}{count} >= 1) {
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = "$line{svr}: Last unmatched message repeated $svrlastline{$line{svr} }{unmatchedline}{count} timesn";
} else {
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line};
$svrlastline{$line{svr} }{unmatchedline}{msg} = $line{msg};
}
$svrlastline{$line{svr} }{unmatchedline}{count} = 0;
}
logmsg (5, 2, "set unmatched{ $line{svr} }{msg} to $svrlastline{$line{svr} }{unmatchedline}{msg} and count to: $svrlastline{$line{svr} }{unmatchedline}{count}");
}
}
logmsg (5, 1, "finished processing line");
}
foreach my $server (keys %svrlastline) {
if ( $svrlastline{$server}{unmatchedline}{count} >= 1) {
logmsg (9, 2, "Added record #".( $#{$$reshashref{nomatch}} + 1 )." for unmatched results");
$$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = "$server: Last unmatched message repeated $svrlastline{$server }{unmatchedline}{count} timesn";
}
}
logmsg (1, 0, "Finished processing $logfile.");
}
sub parsecfgline {
my $line = shift;
- profile( whoami(), whowasi() );
- logmsg (5, 0, " and I was called by ... ".whowasi);
- my $cmd; my $arg;
+ #profile( whoami(), whowasi() );
+ logmsg (5, 3, " and I was called by ... ".&whowasi);
+ my $cmd = "";
+ my $arg = "";
chomp $line;
- logmsg (6, 4, "line: $line");
+ logmsg(5, 3, " and I was called by ... ".&whowasi);
+ logmsg (6, 4, "line: ${line}");
- unless ($line =~ /^#|\s+#/ ) {
+ if ($line =~ /^#|\s+#/ ) {
+ logmsg(9, 4, "comment line, skipping, therefore returns are empty strings");
+ } elsif ($line =~ /^\s+$/ or $line =~ /^$/ ){
+ logmsg(9, 4, "empty line, skipping, therefore returns are empty strings");
+ } else {
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
- } else {
- logmsg(9, 5, "comment line, skipping");
+ $arg = "" unless $arg;
+ $cmd = "" unless $cmd;
}
-
- logmsg (6, 4, "returning cmd: $cmd arg: $arg");
-
+
+ logmsg (6, 3, "returning cmd: $cmd arg: $arg");
return ($cmd, $arg);
}
sub loadcfg {
my $cfghashref = shift;
my $cfgfile = shift;
my $cmdcount = shift;
- profile( whoami(), whowasi() );
- logmsg (5, 0, " and I was called by ... ".whowasi);
open (CFGFILE, "<$cfgfile");
logmsg(1, 0, "Loading cfg from $cfgfile");
-
- my $rule;
- my $bracecount;
- my $stanzatype;
+ logmsg(5, 3, " and I was called by ... ".&whowasi);
+
+ my $rule = -1;
+ my $bracecount = 0;
+ my $stanzatype = "";
while (<CFGFILE>) {
my $line = $_;
logmsg(5, 1, "line: $line");
logmsg(6, 2, "bracecount:$bracecount");
logmsg(6, 2, "stanzatype:$stanzatype");
my $cmd; my $arg;
($cmd, $arg) = parsecfgline($line);
next unless $cmd;
+ logmsg(6, 2, "rule:$rule");
+ logmsg(6, 2, "cmdcount:$cmdcount");
logmsg (6, 2, "cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
if ($bracecount == 0 ) {
for ($cmd) {
if (/RULE/) {
if ($arg =~ /(.*)\s+\{/) {
$rule = $1;
logmsg (9, 3, "rule (if) is now: $rule");
} else {
$rule = $cmdcount++;
logmsg (9, 3, "rule (else) is now: $rule");
} # if arg
$stanzatype = "rule";
logmsg(6, 2, "stanzatype updated to: $stanzatype");
logmsg(6, 2, "rule updated to:$rule");
} elsif (/FORMAT/) {
if ($arg =~ /(.*)\s+\{/) {
$rule = $1;
} # if arg
$stanzatype = "format";
logmsg(6, 2, "stanzatype updated to: $stanzatype");
} elsif (/\}/) {
# if bracecount = 0, cmd may == "}", so ignore
} else {
print STDERR "Error: $cmd didn't match any stanzasn\n";
} # if cmd
} # for cmd
} # bracecount == 0
if ($cmd =~ /\{/ or $arg =~ /\{/) {
$bracecount++;
} elsif ($cmd =~ /\}/ or $arg =~ /\}/) {
$bracecount--;
} # if cmd or arg
if ($bracecount > 0) { # else bracecount
for ($stanzatype) {
if (/rule/) {
logmsg (6, 2, "About to call processrule ... cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
- processrule( %{ $$cfghashref{rules}{$rule} }, $rule, $cmd, $arg);
+ processrule( \%{ $$cfghashref{rules}{$rule} }, $rule, $cmd, $arg);
} elsif (/format/) {
- processformat( %{ $$cfghashref{formats}{$rule} } , $rule, $cmd, $arg);
+ logmsg (6, 2, "About to call processformat ... cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
+ processformat( \%{$$cfghashref{formats}{$rule}} , $rule, $cmd, $arg);
} # if stanzatype
} #if stanzatype
} else {# else bracecount
logmsg (1, 2, "ERROR: bracecount: $bracecount. How did it go negative??");
} # bracecount
} # while
close CFGFILE;
logmsg (5, 1, "Config Hash contents:");
- &pp( %$cfghashref );
+ &Dumper( %$cfghashref );
logmsg (1, 0, "finished processing cfg: $cfgfile");
} # sub loadcfg
sub processformat {
my $cfghashref = shift;
my $rule = shift; # name of the rule to be processed
my $cmd = shift;
my $arg = shift;
- profile( whoami(), whowasi() );
- logmsg (5, 0, " and I was called by ... ".whowasi);
+ #profile( whoami(), whowasi() );
+ logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (5, 4, "Processing rule: $rule");
- logmsg(9, 5, "extracted cmd: $cmd and arg:$arg");
- next unless $cmd;
+ logmsg(9, 5, "passed cmd: $cmd");
+ logmsg(9, 5, "passed arg: $arg");
+ next unless $cmd;
for ($cmd) {
if (/DELIMITER/) {
$$cfghashref{delimiter} = $arg;
logmsg (5, 1, "Config Hash contents:");
- &pp( %$cfghashref );
+ &Dumper( %$cfghashref );
} elsif (/FIELDS/) {
$$cfghashref{fields} = $arg;
- } elsif (/FIELD(d)/) {
+ } elsif (/FIELD(\d+)/) {
logmsg(6, 6, "FIELD#: $1 arg:$arg");
} elsif (/^\}$/) {
} elsif (/^\{$/) {
} else {
print "Error: $cmd didn't match any known fields\n\n";
} # if cmd
} # for cmd
logmsg (5, 4, "Finished processing rule: $rule");
} # sub processformat
sub processrule {
my $cfghashref = shift;
my $rule = shift; # name of the rule to be processed
my $cmd = shift;
my $arg = shift;
- profile( whoami(), whowasi() );
- logmsg (5, 4, " and I was called by ... ".whowasi);
+ #profile( whoami(), whowasi() );
+ logmsg (5, 4, " and I was called by ... ".&whowasi);
logmsg (5, 4, "Processing $rule with cmd: $cmd and arg: $arg");
next unless $cmd;
for ($cmd) {
if (/HOST/) {
# fields
extractregex ($cfghashref, "svrregex", $arg, $rule);
} elsif (/APP($|\s+)/) {
extractregex ($cfghashref, "appregex", $arg, $rule);
} elsif (/FACILITY/) {
extractregex ($cfghashref, "facregex", $arg, $rule);
} elsif (/MSG/) {
extractregex ($cfghashref, "msgregex", $arg, $rule);
} elsif (/CMD/) {
extractregex ($cfghashref, "cmd", $arg, $rule) unless $arg =~ /\{/;
} elsif (/^REGEX/) {
extractregexold ($cfghashref, "cmdregex", $arg, $rule);
} elsif (/MATCH/) {
extractregexold ($cfghashref, "cmdmatrix", $arg, $rule);
$$cfghashref{cmdmatrix} =~ s/\s+//g; # strip all whitespace
} elsif (/IGNORE/) {
$$cfghashref{cmd} = $cmd;
} elsif (/COUNT/) {
$$cfghashref{cmd} = $cmd;
} elsif (/SUM/) {
extractregex ($cfghashref, "targetfield", $arg, $rule);
$$cfghashref{targetfield} =~ s/\s+//g; # strip all whitespace
$$cfghashref{cmd} = $cmd;
} elsif (/AVG/) {
extractregex ($cfghashref, "targetfield", $arg, $rule);
$$cfghashref{targetfield} =~ s/\s+//g; # strip all whitespace
$$cfghashref{cmd} = $cmd;
} elsif (/TITLE/) {
$$cfghashref{rpttitle} = $arg;
$$cfghashref{rpttitle} = $1 if $$cfghashref{rpttitle} =~ /^\"(.*)\"$/;
} elsif (/LINE/) {
$$cfghashref{rptline} = $arg;
$$cfghashref{rptline} = $1 if $$cfghashref{rptline} =~ /\^"(.*)\"$/;
} elsif (/APPEND/) {
$$cfghashref{appendrule} = $arg;
logmsg (1, 0, "*** Setting append for $rule to $arg");
} elsif (/REPORT/) {
} elsif (/^\}$/) {
# $bracecount{closed}++;
} elsif (/^\{$/) {
# $bracecount{open}++;
} else {
print "Error: $cmd didn't match any known fields\n\n";
}
} # for
logmsg (5, 1, "Finished processing rule: $rule");
logmsg (9, 1, "Config hash after running processrule");
- &pp(%$cfghashref);
+ Dumper(%$cfghashref);
} # sub processrule
sub extractregexold {
# Keep the old behaviour
my $cfghashref = shift;
my $param = shift;
my $arg = shift;
my $rule = shift;
- profile( whoami(), whowasi() );
- logmsg (5, 0, " and I was called by ... ".whowasi);
+# profile( whoami(), whowasi() );
+ logmsg (5, 3, " and I was called by ... ".&whowasi);
my $paramnegat = $param."negate";
logmsg (5, 1, "rule: $rule param: $param arg: $arg");
if ($arg =~ /^!/) {
$arg =~ s/^!//g;
$$cfghashref{$paramnegat} = 1;
} else {
$$cfghashref{$paramnegat} = 0;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^\{//;
$arg =~ s/\}$//;
$$cfghashref{$param} = $arg;
logmsg (5, 2, "$param = $$cfghashref{$param}");
}
sub extractregex {
# Put the matches into an array, but would need to change how we handle negates
# Currently the negate is assigned to match group (ie facility or host) or rather than
# an indivudal regex, not an issue immediately because we only support 1 regex
# Need to assign the negate to the regex
# Make the structure ...
# $$cfghashref{rules}{$rule}{$param}[$index] is a hash with {regex} and {negate}
my $cfghashref = shift;
my $param = shift;
my $arg = shift;
my $rule = shift;
my $index = 0;
- profile( whoami(), whowasi() );
- logmsg (5, 0, " and I was called by ... ".whowasi);
+# profile( whoami(), whowasi() );
+ logmsg (5, 3, " and I was called by ... ".&whowasi);
logmsg (1, 3, " rule: $rule for param $param with arg $arg ");
if (exists $$cfghashref{$param}[0] ) {
$index = @{$$cfghashref{$param}};
} else {
$$cfghashref{$param} = ();
}
- my $regex = %{$$cfghashref{$param}[$index]};
+ my $regex = \%{$$cfghashref{$param}[$index]};
$$regex{negate} = 0;
logmsg (5, 1, "$param $arg");
if ($arg =~ /^!/) {
$arg =~ s/^!//g;
$$regex{negate} = 1;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^{//;
$arg =~ s/}$//;
$$regex{regex} = $arg;
logmsg (9, 3, "$regex\{regex\} = $$regex{regex} & \$regex\{negate\} = $$regex{negate}");
logmsg (5,2, "$index = $index");
- logmsg (5, 2, "$param [$index\]\{regex\} = $$cfghashref{$param}[$index]{regex}");
- logmsg (5, 2, "$param [$index\]\{negate\} = $$cfghashref{$param}[$index]{negate}");
+ logmsg (5, 2, "$param \[$index\]\{regex\} = $$cfghashref{$param}[$index]{regex}");
+ logmsg (5, 2, "$param \[$index\]\{negate\} = $$cfghashref{$param}[$index]{negate}");
for (my $i=0; $i<=$index; $i++)
{
logmsg (5,1, "index: $i");
foreach my $key (keys %{$$cfghashref{$param}[$i]}) {
- logmsg (5, 2, "$param [$i\]\{$key\} = $$cfghashref{$param}[$i]{$key}");
+ logmsg (5, 2, "$param \[$i\]\{$key\} = $$cfghashref{$param}[$i]{$key}");
}
}
}
sub report {
my $cfghashref = shift;
my $reshashref = shift;
my $rpthashref = shift;
logmsg(1, 0, "Ruuning report");
- profile( whoami(), whowasi() );
- logmsg (5, 0, " and I was called by ... ".whowasi);
+# profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg(5, 1, "Dump of results hash ...");
- pp(%$reshashref) if $DEBUG >= 5;
+ Dumper(%$reshashref) if $DEBUG >= 5;
- print "n\nNo match for lines:\n";
- foreach my $line (@{@$rpthashref{nomatch}}) {
- print "t$line";
+ print "\n\nNo match for lines:\n";
+ foreach my $line (@{@$reshashref{nomatch}}) {
+ print "\t$line";
}
- print "n\nSummaries:\n";
- for my $rule (sort keys %$rpthashref) {
+ print "\n\nSummaries:\n";
+ for my $rule (sort keys %$reshashref) {
next if $rule =~ /nomatch/;
if (exists ($$cfghashref{rules}{$rule}{rpttitle})) {
- print "$$cfghashref{rules}{$rule}{rpttitle}:n";
+ print "$$cfghashref{rules}{$rule}{rpttitle}\n";
} else {
- logmsg (4, 2, "Rule: $rule:");
+ logmsg (4, 2, "Rule: $rule");
}
- for my $key (keys %{$$rpthashref{$rule}} ) {
+ for my $key (keys %{$$reshashref{$rule}} ) {
if (exists ($$cfghashref{rules}{$rule}{rptline})) {
- print "t".rptline($cfghashref, $reshashref, $rpthashref, $rule, $key)."\n";
+ print "\t".rptline($cfghashref, $reshashref, $rpthashref, $rule, $key)."\n";
} else {
- print "t$$rpthashref{$rule}{$key}: $key\n";
+ print "\t$$rpthashref{$rule}{$key}: $key\n";
}
}
- print "n";
+ print "\n";
}
}
sub rptline {
my $cfghashref = shift;
my $reshashref = shift;
my $rpthashref = shift;
my $rule = shift;
my $key = shift;
my $line = $$cfghashref{rules}{$rule}{rptline};
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
- profile( whoami(), whowasi() );
- logmsg (5, 0, " and I was called by ... ".whowasi);
+# profile( whoami(), whowasi() );
+ logmsg (5, 2, " and I was called by ... ".&whowasi);
logmsg (3, 2, "Starting with rule:$rule");
logmsg (9, 3, "key: $key");
my @fields = split /:/, $key;
logmsg (9, 3, "line: $line");
+ logmsg(9, 3, "subsituting {x} with $$rpthashref{$rule}{$key}{count}");
$line =~ s/\{x\}/$$rpthashref{$rule}{$key}{count}/;
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM") {
$line =~ s/\{s\}/$$rpthashref{$rule}{$key}{sum}/;
}
if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
my $avg = $$rpthashref{$rule}{$key}{sum} / $$reshashref{$rule}{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{a\}/$avg/;
}
logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
logmsg (9, 4, "$fields[$field] = $fields[$i]");
- if ($line =~ /{$field\}/) {
- $line =~ s/{$field\}/$fields[$i]/;
+ if ($line =~ /\{$field\}/) {
+ $line =~ s/\{$field\}/$fields[$i]/;
}
}
return $line;
}
sub actionrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{rules}{$rule} but would break append
my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $value;
my $retval = 0; my $resultsrule;
- profile( whoami(), whowasi() );
- logmsg (5, 0, " and I was called by ... ".whowasi);
+# profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".&whowasi);
logmsg (9, 2, "rule: $rule");
if (exists ($$cfghashref{rules}{$rule}{appendrule})) {
$resultsrule = $$cfghashref{rules}{$rule}{appendrule};
} else {
$resultsrule = $rule;
}
logmsg (5, 3, "rule: $rule");
logmsg (5, 4, "results goto: $resultsrule");
logmsg (5, 4, "cmdregex: $}{cmdregex}");
logmsg (5, 4, "CMD negative regex: $$cfghashref{rules}{$rule}{cmdregexnegat}");
logmsg (5, 4, "line: $$line{line}");
if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /IGNORE/) {
if (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "rule $rule does matches and is a positive IGNORE rule");
}
} else {
logmsg (5, 4, "rule $rule matches and is an IGNORE rule");
$retval = 1;
}
} elsif (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
if ( not $$cfghashref{rules}{$rule}{cmdregexnegat} ) {
if ( $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "Positive match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
} elsif ($$cfghashref{rules}{$rule}{cmdregexnegat}) {
if ( $$line{line} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 4, "Negative match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
}
} else {
logmsg (5, 4, "No cmd regex, implicit match, calling actionrulecmd");
actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
if ($retval == 0) {
logmsg (5, 4, "line does not match cmdregex for rule: $rule");
}
return $retval;
}
sub actionrulecmd
{
my $cfghashref = shift;
my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift;
my $resultsrule = shift;
- profile( whoami(), whowasi() );
+#3 profile( whoami(), whowasi() );
+ logmsg (5, 3, " and I was called by ... ".&whowasi);
logmsg (2, 2, "actioning rule $rule for line: $$line{line}");
# This sub contains the first half of the black magic
# The results from the regex's that are applied later
# are used in actioncmdmatrix()
#
# create a matrix that can be used for matching for the black magic happens
# Instead of the string cmdmatrix
# make a hash of matchmatrix{<match field#>} = <cmdregex field #>
# 2 arrays ...
# fieldnums ... the <match field #'s> of matchmatrix{}
# fieldnames ... the named matches of matchmatrix{}, these match back to the names of the fields
# from the file FORMAT
#
my @tmpmatrix = split (/,/, $$cfghashref{rules}{$rule}{cmdmatrix});
my @matrix = ();
for my $val (@tmpmatrix) {
if ($val =~ /(\d+)/ ) {
push @matrix, $val;
} else {
logmsg(3,3, "Not adding val:$val to matrix");
}
}
logmsg(3, 3, "matrix: @matrix");
#
if (not $$cfghashref{rules}{$rule}{cmdregex}) {
$$cfghashref{rules}{$rule}{cmdregex} = "(.*)";
logmsg (5, 3, "rule did not define cmdregex, replacing with global match");
}
if ( exists $$cfghashref{rules}{$rule}{cmd}) {
logmsg (5, 3, "Collecting data from cmd $$cfghashref{rules}{$rule}{cmd}");
logmsg (5, 3, "rule $rule matches cmd") if $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/;
}
if (not exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
logmsg (5, 3, "No cmd regex, calling actioncmdmatrix");
- actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, @matrix);
+ actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
} elsif ($$cfghashref{rules}{$rule}{cmdregexnegat} ) {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 3, "Negative match, calling actioncmdmatrix");
- actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, @matrix);
+ actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
}
} else {
if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
logmsg (5, 3, "Positive match, calling actioncmdmatrixnline hash:");
- &pp($line) if $DEBUG >= 5;
- actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, @matrix);
+ print Dumper($line) if $DEBUG >= 5;
+ actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, \@matrix);
}
}
}
sub printhash
{
- profile( whoami(), whowasi() );
+# profile( whoami(), whowasi() );
my $line = shift; # hash passed by ref, DO NOT mod
foreach my $key (keys %{ $line} )
{
logmsg (9, 5, "$key: $$line{$key}");
}
}
sub actioncmdmatrix
{
my $cfghashref = shift;
my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift; # Name or ID of rule thats been matched
my $resultsrule = shift; # Name or ID of rule which contains the result set to be updated
my $matrixref = shift; # arrayref
- profile( whoami(), whowasi() );
+ logmsg(5, 4, " ... actioning resultsrule = $rule");
+ logmsg(5, 5, " and I was called by ... ".&whowasi);
+ logmsg(9, 5, "Line hash ...");
+ print Dumper(%$line);
+ #profile( whoami(), whowasi() );
my $cmdmatrix = $$cfghashref{rules}{$rule}{cmdmatrix};
#my @matrix = shift; #split (/,/, $cmdmatrix);
my $fieldhash;
my $cmdfield;
# @matrix - array of parameters that are used in results
if ( exists ($$cfghashref{rules}{$rule}{cmdfield}) ) {
$cmdfield = ${$$cfghashref{rules}{$rule}{cmdfield}};
}
-
- logmsg(5, 2, " ... actioning resultsrule = $rule");
if ( exists $$cfghashref{rules}{$rule}{cmdmatrix}) {
- logmsg (5, 3, "Collecting data for matrix $$cfghashref{rules}{$rule}{cmdmatrix}");
- logmsg (5, 3, "Using matrix @$matrixref");
+ logmsg (5, 5, "Collecting data for matrix $$cfghashref{rules}{$rule}{cmdmatrix}");
+ print Dumper(@$matrixref);
+ logmsg (5, 5, "Using matrix @$matrixref");
# this is where "strict refs" breaks things
# sample: @matrix = svr,1,4,5
# error ... can't use string ("svr") as a SCALAR ref while "strict refs" in use
#
# soln: create a temp array which only has the field #'s and match that
# might need a hash to match
no strict 'refs'; # turn strict refs off just for this section
foreach my $field (@$matrixref) {
# This is were the black magic occurs, ${$field} causes becomes $1 or $2 etc
# and hence contains the various matches from the previous regex match
# which occured just before this function was called
- logmsg (9, 4, "matrix field $field has value ${$field}");
+ logmsg (9, 5, "matrix field $field has value ${$field}");
if (exists $$line{$field}) {
if ($fieldhash) {
$fieldhash = "$fieldhash:$$line{$field}";
} else {
$fieldhash = "$$line{$field}";
}
} else {
if ($fieldhash) {
$fieldhash = "$fieldhash:${$field}";
} else {
if ( ${$field} ) {
$fieldhash = "${$field}";
} else {
- logmsg (1, 4, "$field not found in \"$$line{line}\" with regex $$cfghashref{rules}{$rule}{cmdregex}");
- logmsg (1, 4, "line hash:");
- printhash($line) if $DEBUG >= 1;
+ logmsg (1, 6, "$field not found in \"$$line{line}\" with regex $$cfghashref{rules}{$rule}{cmdregex}");
+ logmsg (1, 6, "line hash:");
+ print Dumper(%$line) if $DEBUG >= 1;
}
}
}
}
use strict 'refs';
if ($$cfghashref{rules}{$rule}{targetfield}) {
- logmsg (1, 4, "Setting cmdfield (field $$cfghashref{rules}{$rule}{targetfield}) to ${$$cfghashref{rules}{$rule}{targetfield}}");
+ logmsg (1, 5, "Setting cmdfield (field $$cfghashref{rules}{$rule}{targetfield}) to ${$$cfghashref{rules}{$rule}{targetfield}}");
$cmdfield = ${$$cfghashref{rules}{$rule}{targetfield}};
}
#if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
$$reshashref{$resultsrule}{$fieldhash}{count}++;
- logmsg (5, 4, "$$reshashref{$resultsrule}{$fieldhash}{count} matches for rule $rule so far from $fieldhash");
+ logmsg (5, 5, "$$reshashref{$resultsrule}{$fieldhash}{count} matches for rule $rule so far from $fieldhash");
#} els
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
$$reshashref{$resultsrule}{$fieldhash}{sum} = $$reshashref{$resultsrule}{$fieldhash}{sum} + $cmdfield;
- logmsg (5, 4, "Adding $cmdfield to total (now $$reshashref{$resultsrule}{$fieldhash}{sum}) for rule $rule so far from $fieldhash");
+ logmsg (5, 5, "Adding $cmdfield to total (now $$reshashref{$resultsrule}{$fieldhash}{sum}) for rule $rule so far from $fieldhash");
if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
- logmsg (5, 4, "Average is ".$$reshashref{$resultsrule}{$fieldhash}{sum} / $$reshashref{$resultsrule}{$fieldhash}{count}." for rule $rule so far from $fieldhash");
+ logmsg (5, 5, "Average is ".$$reshashref{$resultsrule}{$fieldhash}{sum} / $$reshashref{$resultsrule}{$fieldhash}{count}." for rule $rule so far from $fieldhash");
}
}
for my $key (keys %{$$reshashref{$resultsrule}}) {
- logmsg (5, 3, "key $key for rule:$rule with $$reshashref{$resultsrule}{$key}{count} matches");
+ logmsg (5, 5, "key $key for rule:$rule with $$reshashref{$resultsrule}{$key}{count} matches");
}
- logmsg (5, 2, "$fieldhash matches for rule $rule so far from matrix: $$cfghashref{rules}{$rule}{cmdmatrix}");
+ logmsg (5, 5, "$fieldhash matches for rule $rule so far from matrix: $$cfghashref{rules}{$rule}{cmdmatrix}");
} else {
- logmsg (5, 2, "cmdmatrix is not set for $rule");
+ logmsg (5, 5, "cmdmatrix is not set for $rule");
#if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
$$reshashref{$resultsrule}{count}++;
- logmsg (5, 3, "$$reshashref{$resultsrule}{count} lines match rule $rule so far");
+ logmsg (5, 5, "$$reshashref{$resultsrule}{count} lines match rule $rule so far");
# } els
if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
$$reshashref{$resultsrule}{sum} = $$reshashref{$resultsrule}{sum} + $cmdfield;
- logmsg (5, 3, "$$reshashref{$resultsrule}{sum} lines match rule $rule so far");
+ logmsg (5, 5, "$$reshashref{$resultsrule}{sum} lines match rule $rule so far");
}
}
+ logmsg(5, 4, " ... Finished actioning resultsrule = $rule");
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
-
- profile( whoami(), whowasi() );
+ logmsg(5, 4, " and I was called by ... ".&whowasi);
+# profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
-
- profile( whoami(), whowasi() );
- if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^*$/ ) {
+ logmsg(5, 3, " and I was called by ... ".&whowasi);
+# profile( whoami(), whowasi() );
+ if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
} else {
logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
}
}
sub matchingrules {
my $cfghashref = shift;
my $param = shift;
my $matchref = shift;
my $value = shift;
- profile( whoami(), whowasi() );
-
- logmsg (6, 3, "param:$param ");
- logmsg (6,3, "value:$value");
- logmsg (3, 2, " $param, match count: ".keys(%{$matchref})." value: $value");
+ logmsg(5, 3, " and I was called by ... ".&whowasi);
+ logmsg (6, 3, "param:$param");
+ logmsg (6, 3, "value:$value");
+ logmsg (3, 2, "$param, match count: ".keys(%{$matchref})." value: $value");
if (keys %{$matchref} == 0) {
# Check all rules as we haevn't had a match yet
foreach my $rule (keys %{$cfghashref->{rules} } ) {
checkrule($cfghashref, $param, $matchref, $rule, $value);
}
} else {
# As we've allready had a match on the rules, only check those that matched in earlier rounds
# key in %matches is the rule that matches
foreach my $rule (keys %{$matchref}) {
checkrule($cfghashref, $param, $matchref, $rule, $value);
}
}
}
sub checkrule {
my $cfghashref = shift;
my $param = shift;
my $matches = shift;
my $rule = shift; # key to %matches
my $value = shift;
- profile( whoami(), whowasi() );
logmsg(2, 1, "Checking rule ($rule) & param ($param) for matches against: $value");
-
+ logmsg(5, 3, " and I was called by ... ".&whowasi);
my $paramref = \@{ $$cfghashref{rules}{$rule}{$param} };
defaultregex($paramref); # This should be done when reading the config
foreach my $index (@{ $paramref } ) {
my $match = matchregex($index, $value);
if ($$index{negate} ) {
if ( $match) {
delete $$matches{$rule};
- logmsg (5, 5, "matches $index->{regex} for param '$param\', but negative rule is set, so removing rule $match from list.");
+ logmsg (5, 5, "matches $index->{regex} for param \'$param\', but negative rule is set, so removing rule $match from list.");
} else {
$$matches{$rule} = "match" if $match;
- logmsg (5, 5, "Doesn't match for $index->{regex} for param '$param\', but negative rule is set, so leaving rule $match on list.");
+ logmsg (5, 5, "Doesn't match for $index->{regex} for param \'$param\', but negative rule is set, so leaving rule $match on list.");
}
} elsif ($match) {
$$matches{$rule} = "match" if $match;
- logmsg (5, 4, "matches $index->{regex} for param '$param\', leaving rule $match on list.");
+ logmsg (5, 4, "matches $index->{regex} for param \'$param\', leaving rule $match on list.");
} else {
delete $$matches{$rule};
- logmsg (5, 4, "doesn't match $index->{regex} for param '$param\', removing rule $match from list.");
+ logmsg (5, 4, "doesn't match $index->{regex} for param \'$param\', removing rule $match from list.");
}
} # for each regex hash in the array
logmsg (3, 2, "matches ".keys (%{$matches})." matches after checking rules for $param");
}
-=oldcode
-sub matchingrules {
- my $cfghashref = shift;
- my $param = shift;
- my $matches = shift;
- my $value = shift;
-
- profile( whoami(), whowasi() );
- logmsg (3, 2, "param: $param, matches: $matches, value: $value");
- if (keys %{$matches} == 0) {
- # Check all rules as we haevn't had a match yet
- foreach my $rule (keys %config) {
- $$cfghashref{rules}{$rule}{$param} = "(.*)" unless exists ($$cfghashref{rules}{$rule}{$param});
- logmsg (5, 3, "Does $value match /$$cfghashref{rules}{$rule}{$param}/ ??");
- if ($value =~ /$$cfghashref{rules}{$rule}{$param}/ or $$cfghashref{rules}{$rule}{$param} =~ /^*$/ ) {
- logmsg (5, 4, "Matches rule: $rule");
- $$matches{$rule} = "match";
- }
- }
- } else {
- # As we've allready had a match on the rules, only check those that matched in earlier rounds
- foreach my $match (keys %{$matches}) {
- if (exists ($$cfghashref{rules}{$match}{$param}) ) {
- logmsg (5, 4, "Does value: "$value\" match \'$$cfghashref{rules}{$match}{$param}\' for param $param ??");
- if ($$cfghashref{rules}{$match}{"${param}negat"}) {
- logmsg (5, 5, "Doing a negative match");
- }
- } else {
- logmsg (5, 3, "No rule for value: "$value\" in rule $match, leaving on match list.");
- $$cfghashref{rules}{$match}{$param} = "(.*)";
- }
- if ($$cfghashref{rules}{$match}{"${param}negat"}) {
- if ($value =~ /$$cfghashref{rules}{$match}{$param}/ or $$cfghashref{rules}{$match}{$param} =~ /^*$/ ) {
- delete $$matches{$match};
- logmsg (5, 5, "matches $$cfghashref{rules}{$match}{$param} for param '$param\', but negative rule is set, so removing rule $match from list.");
- } else {
- logmsg (5, 5, "Doesn't match for $$cfghashref{rules}{$match}{$param} for param '$param\', but negative rule is set, so leaving rule $match on list.");
- }
- } elsif ($value =~ /$$cfghashref{rules}{$match}{$param}/ or $$cfghashref{rules}{$match}{$param} =~ /^*$/ ) {
- logmsg (5, 4, "matches $$cfghashref{rules}{$match}{$param} for param '$param\', leaving rule $match on list.");
- } else {
- delete $$matches{$match};
- logmsg (5, 4, "doesn't match $$cfghashref{rules}{$match}{$param} for param '$param\', removing rule $match from list.");
- }
- }
- }
- logmsg (3, 2, keys (%{$matches})." matches after checking rules for $param");
-}
-=cut
-
-
-sub whoami { ( caller(1) )[3] }
-sub whowasi { ( caller(2) )[3] }
+sub whoami { (caller(1) )[3] }
+sub whowasi { (caller(2) )[3] }
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
-print "$DEBUG";
if ($DEBUG >= $level) {
for my $i (0..$indent) {
print STDERR " ";
}
print STDERR whowasi."(): $msg\n";
}
}
sub profile {
my $caller = shift;
my $parent = shift;
- $profile{$parent}{$caller}++;
+# $profile{$parent}{$caller}++;
}
sub profilereport {
- pp(%profile);
+ print Dumper(%profile);
}
|
mikeknox/LogParse | 5f725740ae4e37c25da4e9b226436d79640048f2 | Lots of updates, but doesn't work yet | diff --git a/logparse.pl b/logparse.pl
index 86336f7..fbe3b4d 100755
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,706 +1,982 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=head1 NAME
logparse - syslog analysis tool
=cut
=head1 SYNOPSIS
./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
Describe config file for log parse / summary engine
Input fields from syslog:
Date, time, server, application, facility, ID, message
=head3 Config line
/server regex/, /app regex/, /facility regex/, /msg regex/, $ACTIONS
Summaries are required at various levels, from total instances to total sizes to server summaries.
=head2 ACTIONS
COUNT - Just list the total number of matches
SUM[x] - Report the sum of field x of all matches
SUM[x], /regex/ - Apply regex to msg field of matches and report the sum of field x from that regex
SUM[x], /regex/, {y,z} - Apply regex to msg field of matches and report the sum of field x from that regex for fields y & z
AVG[x], /regex/, {y,z} - Apply regex to msg field of matches and report the avg of field x from that regex for fields y & z
COUNT[x], /regex/, {y,z} - Apply regex to msg field of matches and report the count of field x from that regex for matching fields y & z
Each entry can test or regex, if text interpret as regex /^string$/
Sample entry...
*, /rshd/, *, *, COUNT /connect from (.*)/, {1}
=head2 BUGS:
+ See http://github.com/mikeknox/LogParse/issues
+
+=head2 FORMAT stanza
+FORMAT <name> {
+ DELIMITER <xyz>
+ FIELDS <x>
+ FIELD<x> <name>
+}
=head2 TODO:
+
+=head3 Config hash design
+ The config hash needs to be redesigned, particuarly to support other input log formats.
+ current layout:
+ all parameters are members of $$cfghashref{rules}{$rule}
+
+ Planned:
+ $$cfghashref{rules}{$rule}{fields} - Hash of fields
+ $$cfghashref{rules}{$rule}{fields}{$field} - Array of regex hashes
+ $$cfghashref{rules}{$rule}{cmd} - Command hash
+ $$cfghashref{rules}{$rule}{report} - Report hash
+=head3 Command hash
+ Config for commands such as COUNT, SUM, AVG etc for a rule
+ $cmd
+
+=head3 Report hash
+ Config for the entry in the report / summary report for a rule
+
+=head3 regex hash
+ $regex{regex} = regex string
+ $regex{negate} = 1|0 - 1 regex is to be negated
+
=cut
# expects data on std in
use strict;
use Getopt::Std;
-no strict 'refs';
+#no strict 'refs';
+use Data::Dump qw(pp);
+use Data::Dumper;
+
+use utils;
+use logparse;
+# Globals
+my %profile;
+my $DEBUG = 0;
+my %DEFAULTS = ("CONFIGFILE", "logparse.conf", "SYSLOGFILE", "/var/log/messages" );
my %opts;
my $CONFIGFILE="logparse.conf";
-my %config;
-my %results;
+my %cfghash;
+my %reshash;
my $cmdcount = 0;
my $UNMATCHEDLINES = 1;
-my $DEBUG = 0;
my $SYSLOGFILE = "/var/log/messages";
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
getopt('cdl', \%opts);
$DEBUG = $opts{d} if $opts{d};
$CONFIGFILE = $opts{c} if $opts{c};
$SYSLOGFILE = $opts{l} if $opts{l};
-open (CFGFILE, "<$CONFIGFILE");
-my $rule;
-while (<CFGFILE>) {
- my $line = $_;
- my $cmd; my $arg;
- chomp $line;
+loadcfg (\%cfghash, $CONFIGFILE, $cmdcount);
- next if $line =~ /^#|\s+#/;
- $line = $1 if $line =~ /^\s+(.*)/;
- ($cmd, $arg) = split (/\s+/, $line, 2);
- next unless $cmd;
- logmsg (6, 0, "main(): parse cmd: $cmd arg: $arg");
-
- for ($cmd) {
- if (/RULE/) {
- if ($arg =~ /(.*)\s+\{/) {
- $rule = $1;
- } else {
- $rule = $cmdcount++;
- }
- } elsif (/HOST/) {
- extractregex ("svrregex", $arg);
- } elsif (/APP($|\s+)/) {
- extractregex ("appregex", $arg);
- } elsif (/FACILITY/) {
- extractregex ("facregex", $arg);
- } elsif (/MSG/) {
- extractregex ("msgregex", $arg);
- } elsif (/CMD/) {
- extractregex ("cmd", $arg) unless $arg =~ /\{/;
- } elsif (/^REGEX/) {
- extractregexold ("cmdregex", $arg);
- } elsif (/MATCH/) {
- extractregexold ("cmdmatrix", $arg);
- $config{$rule}{cmdmatrix} =~ s/\s+//g; # strip all whitespace
- } elsif (/IGNORE/) {
- $config{$rule}{cmd} = $cmd;
- } elsif (/COUNT/) {
- $config{$rule}{cmd} = $cmd;
- } elsif (/SUM/) {
- extractregex ("targetfield", $arg);
- $config{$rule}{targetfield} =~ s/\s+//g; # strip all whitespace
- $config{$rule}{cmd} = $cmd;
- } elsif (/AVG/) {
- extractregex ("targetfield", $arg);
- $config{$rule}{targetfield} =~ s/\s+//g; # strip all whitespace
- $config{$rule}{cmd} = $cmd;
- } elsif (/TITLE/) {
- $config{$rule}{rpttitle} = $arg;
- $config{$rule}{rpttitle} = $1 if $config{$rule}{rpttitle} =~ /^\"(.*)\"$/;
- } elsif (/LINE/) {
- $config{$rule}{rptline} = $arg;
- $config{$rule}{rptline} = $1 if $config{$rule}{rptline} =~ /^\"(.*)\"$/;
- } elsif (/APPEND/) {
- $config{$rule}{appendrule} = $arg;
- logmsg (1, 0, "*** Setting append for $rule to $arg");
- } elsif (/REPORT/) {
- } elsif (/^\}$/) {
- } elsif (/^\{$/) {
- } else {
- print "Error: $cmd didn't match any known commands\n\n";
- }
- }
- logmsg (5, 1, "main() rule: $rule");
- for my $key (keys %{ $config{$rule} } ) {
- foreach my $index (@{ $config{$rule}{$key} } ) {
- logmsg (5, 2, "main() key=$key");
- for my $regkey (keys %{ $index} ) {
- logmsg (5,3, "main(): $regkey=$$index{$regkey}");
- }
- }
- }
-}
+processlogfile(\%cfghash, \%reshash, $SYSLOGFILE);
+report(\%cfghash, \%reshash);
+
+profilereport();
+exit 0;
-open (LOGFILE, "<$SYSLOGFILE") or die "Unable to open $SYSLOGFILE for reading...";
-while (<LOGFILE>) {
- #my $mth; my $date; my $time; my $svr; my $app; my $msg;
- my $facility;
- my %line;
- # Placing line and line componenents into a hash to be passed to actrule, components can then be refered
- # to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
- $line{line} = $_;
- logmsg (5, 1, "Processing next line");
- ($line{mth}, $line{date}, $line{time}, $line{svr}, $line{app}, $line{msg}) = split (/\s+/, $line{line}, 6);
- logmsg (9, 2, "mth: $line{mth}, date: $line{date}, time: $line{time}, svr: $line{svr}, app: $line{app}, msg: $line{msg}");
+sub processlogfile {
+ my $cfghashref = shift;
+ my $reshashref = shift;
+ my $logfile = shift;
+
+ profile( whoami, whowasi );
+ logmsg (1, 0, "processing $logfile ...");
+ open (LOGFILE, "<$logfile") or die "Unable to open $SYSLOGFILE for reading...";
+ while (<LOGFILE>) {
+ my $facility;
+ my %line;
+ # Placing line and line componenents into a hash to be passed to actrule, components can then be refered
+ # to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
+ $line{line} = $_;
+
+ logmsg (5, 1, "Processing next line");
+ ($line{mth}, $line{date}, $line{time}, $line{svr}, $line{app}, $line{msg}) = split (/\s+/, $line{line}, 6);
+ logmsg (9, 2, "mth: $line{mth}, date: $line{date}, time: $line{time}, svr: $line{svr}, app: $line{app}, msg: $line{msg}");
+
+ if ($line{msg} =~ /^\[/) {
+ ($line{facility}, $line{msg}) = split (/]\s+/, $line{msg}, 2);
+ $line{facility} =~ s/\[//;
+ }
+
+ logmsg (9, 1, "Checking line: $line{line}");
+ logmsg (9, 1, "facility: $line{facility}");
+ logmsg (9, 1, "msg: $line{msg}");
+
+ my %matches;
+ my %matchregex = ("svrregex", "svr", "appregex", "app", "facregex", "facility", "msgregex", "line");
+ for my $param ("appregex", "facregex", "msgregex", "svrregex") {
+ matchingrules($cfghashref, $param, \%matches, $line{ $matchregex{$param} } );
+ }
+ logmsg(9, 2, keys(%matches)." matches so far");
+ $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} and next unless keys %matches > 0;
+ logmsg(9,1,"Results hash ...");
+ pp(%$reshashref);
+
+ if ($line{msg} =~ /message repeated/ and exists $svrlastline{$line{svr} }{line}{msg} ) { # and keys %{$svrlastline{ $line{svr} }{rulematches}} ) {
+ logmsg (9, 2, "last message repeated and matching svr line");
+ my $numrepeats = 0;
+ if ($line{msg} =~ /message repeated (.*) times/) {
+ $numrepeats = $1;
+ }
+ logmsg(9, 2, "Last message repeated $numrepeats times");
+ for my $i (1..$numrepeats) {
+ for my $rule (keys %{$svrlastline{ $line{svr} }{rulematches} } ) {
+ logmsg (5, 3, "Applying cmd for rule $rule: $$cfghashref{rules}{$rule}{cmd} - as prelim regexs pass");
+ actionrule($cfghashref, $reshashref, $rule, \%{ $svrlastline{$line{svr} }{line} }); # if $actrule == 0;
+ }
+ }
+ } else {
+ logmsg (5, 2, "No recorded last line for $line{svr}") if $line{msg} =~ /message repeated/;
+ logmsg (9, 2, "msg: $line{msg}");
+ %{ $svrlastline{$line{svr} }{line} } = %line;
+ # track line
+ # track matching rule(s)
+
+ logmsg (3, 2, keys (%matches)." matches after checking all rules");
+
+ if (keys %matches > 0) {
+ logmsg (5, 2, "svr & app & fac & msg matched rules: ");
+ logmsg (5, 2, "matched rules ".keys(%matches)." from line $line{line}");
+
+ # loop through matching rules and collect data as defined in the ACTIONS section of %config
+ my $actrule = 0;
+ my %tmpmatches = %matches;
+ for my $rule (keys %tmpmatches) {
+ my $result = actionrule($cfghashref, $reshashref, $rule, \%line);
+ delete $matches{$rule} unless $result ;
+ $actrule = $result unless $actrule;
+ logmsg (5, 3, "Applying cmd from rule $rule: $$cfghashref{rules}{$rule}{cmd} as passed prelim regexes");
+ logmsg (10, 4, "an action rule matched: $actrule");
+ }
+ logmsg (10, 4, "an action rule matched: $actrule");
+ $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line} if $actrule == 0;
+ %{$svrlastline{$line{svr} }{rulematches}} = %matches unless ($line{msg} =~ /last message repeated d+ times/);
+
+ logmsg (5, 2, "setting lastline match for server: $line{svr} and line:n$line{line}");
+ logmsg (5, 3, "added matches for $line{svr} for rules:");
+ for my $key (keys %{$svrlastline{$line{svr} }{rulematches}}) {
+ logmsg (5, 4, "$key");
+ }
+ logmsg (5, 3, "rules from line $line{line}");
+ } else {
+ logmsg (5, 2, "No match: $line{line}");
+ if ($svrlastline{$line{svr} }{unmatchedline}{msg} eq $line{msg} ) {
+ $svrlastline{$line{svr} }{unmatchedline}{count}++;
+ logmsg (9, 3, "$svrlastline{$line{svr} }{unmatchedline}{count} instances of msg: $line{msg} on $line{svr}");
+ } else {
+ $svrlastline{$line{svr} }{unmatchedline}{count} = 0 unless exists $svrlastline{$line{svr} }{unmatchedline}{count};
+ if ($svrlastline{$line{svr} }{unmatchedline}{msg} and $svrlastline{$line{svr} }{unmatchedline}{count} >= 1) {
+ $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = "$line{svr}: Last unmatched message repeated $svrlastline{$line{svr} }{unmatchedline}{count} timesn";
+ } else {
+ $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = $line{line};
+ $svrlastline{$line{svr} }{unmatchedline}{msg} = $line{msg};
+ }
+ $svrlastline{$line{svr} }{unmatchedline}{count} = 0;
+ }
+ logmsg (5, 2, "set unmatched{ $line{svr} }{msg} to $svrlastline{$line{svr} }{unmatchedline}{msg} and count to: $svrlastline{$line{svr} }{unmatchedline}{count}");
+ }
+ }
+ logmsg (5, 1, "finished processing line");
+ }
- if ($line{msg} =~ /^\[/) {
- ($line{facility}, $line{msg}) = split (/\]\s+/, $line{msg}, 2);
- $line{facility} =~ s/\[//;
+ foreach my $server (keys %svrlastline) {
+ if ( $svrlastline{$server}{unmatchedline}{count} >= 1) {
+ logmsg (9, 2, "Added record #".( $#{$$reshashref{nomatch}} + 1 )." for unmatched results");
+ $$reshashref{nomatch}[$#{$$reshashref{nomatch}}+1] = "$server: Last unmatched message repeated $svrlastline{$server }{unmatchedline}{count} timesn";
+ }
}
+ logmsg (1, 0, "Finished processing $logfile.");
+}
+
+sub parsecfgline {
+ my $line = shift;
+
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
+ my $cmd; my $arg;
+ chomp $line;
- logmsg (9, 1, "Checking line: $line{line}");
- logmsg (9, 1, "facility: $line{facility}");
- logmsg (9, 1, "msg: $line{msg}");
+ logmsg (6, 4, "line: $line");
- my %matches;
- my %matchregex = ("svrregex", "svr", "appregex", "app", "facregex", "facility", "msgregex", "line");
- for my $param ("appregex", "facregex", "msgregex", "svrregex") {
- matchingrules($param, \%matches, $line{ $matchregex{$param} } );
+ unless ($line =~ /^#|\s+#/ ) {
+ $line = $1 if $line =~ /^\s+(.*)/;
+ ($cmd, $arg) = split (/\s+/, $line, 2);
+ } else {
+ logmsg(9, 5, "comment line, skipping");
}
- $results{nomatch}[$#{$results{nomatch}}+1] = $line{line} and next unless keys %matches > 0;
- if ($line{msg} =~ /message repeated/ and exists $svrlastline{$line{svr} }{line}{msg} ) { # and keys %{$svrlastline{ $line{svr} }{rulematches}} ) {
- logmsg (9, 2, "last message repeated and matching svr line");
- my $numrepeats = 0;
- if ($line{msg} =~ /message repeated (.*) times/) {
- $numrepeats = $1;
- }
- logmsg(9, 2, "Last message repeated $numrepeats times");
- for my $i (1..$numrepeats) {
- for my $rule (keys %{$svrlastline{ $line{svr} }{rulematches} } ) {
- logmsg (5, 3, "Applying cmd for rule $rule: $config{$rule}{cmd} - as prelim regexs pass");
- actionrule($rule, \%{ $svrlastline{$line{svr} }{line} }); # if $actrule == 0;
- }
- }
- } else {
- logmsg (5, 2, "No recorded last line for $line{svr}") if $line{msg} =~ /message repeated/;
- logmsg (9, 2, "msg: $line{msg}");
- %{ $svrlastline{$line{svr} }{line} } = %line;
- # track line
- # track matching rule(s)
-
- logmsg (3, 2, keys (%matches)." matches after checking all rules");
-
- if (keys %matches > 0) {
- logmsg (5, 2, "svr & app & fac & msg matched rules: ");
- for my $key (keys %matches) {
- logmsg (5, 3, "$key ");
- }
- logmsg (5, 2, " rules from line $line{line}");
-
- # loop through matching rules and collect data as defined in the ACTIONS section of %config
- my $actrule = 0;
- my %tmpmatches = %matches;
- for my $rule (keys %tmpmatches) {
- my $result = actionrule($rule, \%line);
- delete $matches{$rule} unless $result ;
- $actrule = $result unless $actrule;
- logmsg (5, 3, "Applying cmd from rule $rule: $config{$rule}{cmd} as passed prelim regexes");
- logmsg (10, 4, "an action rule matched: $actrule");
- }
- logmsg (10, 4, "an action rule matched: $actrule");
- $results{nomatch}[$#{$results{nomatch}}+1] = $line{line} if $actrule == 0;
- %{$svrlastline{$line{svr} }{rulematches}} = %matches unless ($line{msg} =~ /last message repeated \d+ times/);
-
- logmsg (5, 2, "main(): setting lastline match for server: $line{svr} and line:\n$line{line}");
- logmsg (5, 3, "added matches for $line{svr} for rules:");
- for my $key (keys %{$svrlastline{$line{svr} }{rulematches}}) {
- logmsg (5, 4, "$key");
- }
- logmsg (5, 3, "rules from line $line{line}");
- } else {
- logmsg (5, 2, "No match: $line{line}") if $UNMATCHEDLINES;
- if ($svrlastline{$line{svr} }{unmatchedline}{msg} eq $line{msg} ) {
- $svrlastline{$line{svr} }{unmatchedline}{count}++;
- logmsg (9, 3, "$svrlastline{$line{svr} }{unmatchedline}{count} instances of msg: $line{msg} on $line{svr}");
- } else {
- $svrlastline{$line{svr} }{unmatchedline}{count} = 0 unless exists $svrlastline{$line{svr} }{unmatchedline}{count};
- if ($svrlastline{$line{svr} }{unmatchedline}{msg} and $svrlastline{$line{svr} }{unmatchedline}{count} >= 1) {
- $results{nomatch}[$#{$results{nomatch}}+1] = "$line{svr}: Last unmatched message repeated $svrlastline{$line{svr} }{unmatchedline}{count} times\n";
- } else {
- $results{nomatch}[$#{$results{nomatch}}+1] = $line{line};
- $svrlastline{$line{svr} }{unmatchedline}{msg} = $line{msg};
- }
- $svrlastline{$line{svr} }{unmatchedline}{count} = 0;
- }
- logmsg (5, 2, "main(): set unmatched{ $line{svr} }{msg} to $svrlastline{$line{svr} }{unmatchedline}{msg} and count to: $svrlastline{$line{svr} }{unmatchedline}{count}");
- }
- }
- logmsg (5, 1, "main(): finished processing line");
-}
+ logmsg (6, 4, "returning cmd: $cmd arg: $arg");
-foreach my $server (keys %svrlastline) {
- if ( $svrlastline{$server}{unmatchedline}{count} >= 1) {
- logmsg (9, 2, "main(): Added record #".( $#{$results{nomatch}} + 1 )." for unmatched results");
- $results{nomatch}[$#{$results{nomatch}}+1] = "$server: Last unmatched message repeated $svrlastline{$server }{unmatchedline}{count} times\n";
- }
+ return ($cmd, $arg);
}
-report();
-exit 0;
+sub loadcfg {
+ my $cfghashref = shift;
+ my $cfgfile = shift;
+ my $cmdcount = shift;
+
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
+ open (CFGFILE, "<$cfgfile");
+
+ logmsg(1, 0, "Loading cfg from $cfgfile");
+
+ my $rule;
+ my $bracecount;
+ my $stanzatype;
+
+ while (<CFGFILE>) {
+ my $line = $_;
+
+ logmsg(5, 1, "line: $line");
+ logmsg(6, 2, "bracecount:$bracecount");
+ logmsg(6, 2, "stanzatype:$stanzatype");
+
+ my $cmd; my $arg;
+ ($cmd, $arg) = parsecfgline($line);
+ next unless $cmd;
+ logmsg (6, 2, "cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
+
+ if ($bracecount == 0 ) {
+ for ($cmd) {
+ if (/RULE/) {
+ if ($arg =~ /(.*)\s+\{/) {
+ $rule = $1;
+ logmsg (9, 3, "rule (if) is now: $rule");
+ } else {
+ $rule = $cmdcount++;
+ logmsg (9, 3, "rule (else) is now: $rule");
+ } # if arg
+ $stanzatype = "rule";
+ logmsg(6, 2, "stanzatype updated to: $stanzatype");
+ logmsg(6, 2, "rule updated to:$rule");
+ } elsif (/FORMAT/) {
+ if ($arg =~ /(.*)\s+\{/) {
+ $rule = $1;
+ } # if arg
+ $stanzatype = "format";
+ logmsg(6, 2, "stanzatype updated to: $stanzatype");
+ } elsif (/\}/) {
+ # if bracecount = 0, cmd may == "}", so ignore
+ } else {
+ print STDERR "Error: $cmd didn't match any stanzasn\n";
+ } # if cmd
+ } # for cmd
+ } # bracecount == 0
+ if ($cmd =~ /\{/ or $arg =~ /\{/) {
+ $bracecount++;
+ } elsif ($cmd =~ /\}/ or $arg =~ /\}/) {
+ $bracecount--;
+ } # if cmd or arg
+
+ if ($bracecount > 0) { # else bracecount
+ for ($stanzatype) {
+ if (/rule/) {
+ logmsg (6, 2, "About to call processrule ... cmd:$cmd arg:$arg rule:$rule cmdcount:$cmdcount");
+ processrule( %{ $$cfghashref{rules}{$rule} }, $rule, $cmd, $arg);
+ } elsif (/format/) {
+ processformat( %{ $$cfghashref{formats}{$rule} } , $rule, $cmd, $arg);
+ } # if stanzatype
+ } #if stanzatype
+ } else {# else bracecount
+ logmsg (1, 2, "ERROR: bracecount: $bracecount. How did it go negative??");
+ } # bracecount
+ } # while
+ close CFGFILE;
+ logmsg (5, 1, "Config Hash contents:");
+ &pp( %$cfghashref );
+ logmsg (1, 0, "finished processing cfg: $cfgfile");
+} # sub loadcfg
+
+sub processformat {
+ my $cfghashref = shift;
+ my $rule = shift; # name of the rule to be processed
+ my $cmd = shift;
+ my $arg = shift;
+
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
+ logmsg (5, 4, "Processing rule: $rule");
+ logmsg(9, 5, "extracted cmd: $cmd and arg:$arg");
+ next unless $cmd;
+
+ for ($cmd) {
+ if (/DELIMITER/) {
+ $$cfghashref{delimiter} = $arg;
+ logmsg (5, 1, "Config Hash contents:");
+ &pp( %$cfghashref );
+ } elsif (/FIELDS/) {
+ $$cfghashref{fields} = $arg;
+ } elsif (/FIELD(d)/) {
+ logmsg(6, 6, "FIELD#: $1 arg:$arg");
+ } elsif (/^\}$/) {
+ } elsif (/^\{$/) {
+ } else {
+ print "Error: $cmd didn't match any known fields\n\n";
+ } # if cmd
+ } # for cmd
+ logmsg (5, 4, "Finished processing rule: $rule");
+} # sub processformat
+
+sub processrule {
+ my $cfghashref = shift;
+ my $rule = shift; # name of the rule to be processed
+ my $cmd = shift;
+ my $arg = shift;
+
+ profile( whoami(), whowasi() );
+ logmsg (5, 4, " and I was called by ... ".whowasi);
+ logmsg (5, 4, "Processing $rule with cmd: $cmd and arg: $arg");
+
+ next unless $cmd;
+ for ($cmd) {
+ if (/HOST/) {
+ # fields
+ extractregex ($cfghashref, "svrregex", $arg, $rule);
+ } elsif (/APP($|\s+)/) {
+ extractregex ($cfghashref, "appregex", $arg, $rule);
+ } elsif (/FACILITY/) {
+ extractregex ($cfghashref, "facregex", $arg, $rule);
+ } elsif (/MSG/) {
+ extractregex ($cfghashref, "msgregex", $arg, $rule);
+ } elsif (/CMD/) {
+ extractregex ($cfghashref, "cmd", $arg, $rule) unless $arg =~ /\{/;
+ } elsif (/^REGEX/) {
+ extractregexold ($cfghashref, "cmdregex", $arg, $rule);
+ } elsif (/MATCH/) {
+ extractregexold ($cfghashref, "cmdmatrix", $arg, $rule);
+ $$cfghashref{cmdmatrix} =~ s/\s+//g; # strip all whitespace
+ } elsif (/IGNORE/) {
+ $$cfghashref{cmd} = $cmd;
+ } elsif (/COUNT/) {
+ $$cfghashref{cmd} = $cmd;
+ } elsif (/SUM/) {
+ extractregex ($cfghashref, "targetfield", $arg, $rule);
+ $$cfghashref{targetfield} =~ s/\s+//g; # strip all whitespace
+ $$cfghashref{cmd} = $cmd;
+ } elsif (/AVG/) {
+ extractregex ($cfghashref, "targetfield", $arg, $rule);
+ $$cfghashref{targetfield} =~ s/\s+//g; # strip all whitespace
+ $$cfghashref{cmd} = $cmd;
+ } elsif (/TITLE/) {
+ $$cfghashref{rpttitle} = $arg;
+ $$cfghashref{rpttitle} = $1 if $$cfghashref{rpttitle} =~ /^\"(.*)\"$/;
+ } elsif (/LINE/) {
+ $$cfghashref{rptline} = $arg;
+ $$cfghashref{rptline} = $1 if $$cfghashref{rptline} =~ /\^"(.*)\"$/;
+ } elsif (/APPEND/) {
+ $$cfghashref{appendrule} = $arg;
+ logmsg (1, 0, "*** Setting append for $rule to $arg");
+ } elsif (/REPORT/) {
+ } elsif (/^\}$/) {
+ # $bracecount{closed}++;
+ } elsif (/^\{$/) {
+ # $bracecount{open}++;
+ } else {
+ print "Error: $cmd didn't match any known fields\n\n";
+ }
+ } # for
+ logmsg (5, 1, "Finished processing rule: $rule");
+ logmsg (9, 1, "Config hash after running processrule");
+ &pp(%$cfghashref);
+} # sub processrule
sub extractregexold {
# Keep the old behaviour
-
+ my $cfghashref = shift;
my $param = shift;
my $arg = shift;
+ my $rule = shift;
+
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
my $paramnegat = $param."negate";
- logmsg (5, 1, "extractregex(): $param $arg");
- if ($arg =~ /^\!/) {
- $arg =~ s/^\!//g;
- $config{$rule}{$paramnegat} = 1;
+ logmsg (5, 1, "rule: $rule param: $param arg: $arg");
+ if ($arg =~ /^!/) {
+ $arg =~ s/^!//g;
+ $$cfghashref{$paramnegat} = 1;
} else {
- $config{$rule}{$paramnegat} = 0;
+ $$cfghashref{$paramnegat} = 0;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
- $arg =~ s/^{//;
- $arg =~ s/}$//;
- $config{$rule}{$param} = $arg;
- logmsg (5, 2, "extractregex(): $param = $config{$rule}{$param}");
-
+ $arg =~ s/^\{//;
+ $arg =~ s/\}$//;
+ $$cfghashref{$param} = $arg;
+ logmsg (5, 2, "$param = $$cfghashref{$param}");
}
sub extractregex {
# Put the matches into an array, but would need to change how we handle negates
# Currently the negate is assigned to match group (ie facility or host) or rather than
# an indivudal regex, not an issue immediately because we only support 1 regex
# Need to assign the negate to the regex
# Make the structure ...
- # $config{$rule}{$param}[$index] is a hash with {regex} and {negate}
+ # $$cfghashref{rules}{$rule}{$param}[$index] is a hash with {regex} and {negate}
+ my $cfghashref = shift;
my $param = shift;
my $arg = shift;
- my $index = @{$config{$rule}{$param}};
- $index = 0 if $index == "";
+ my $rule = shift;
+
+ my $index = 0;
- my $regex = \%{$config{$rule}{$param}[$index]};
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
+ logmsg (1, 3, " rule: $rule for param $param with arg $arg ");
+ if (exists $$cfghashref{$param}[0] ) {
+ $index = @{$$cfghashref{$param}};
+ } else {
+ $$cfghashref{$param} = ();
+ }
+
+ my $regex = %{$$cfghashref{$param}[$index]};
$$regex{negate} = 0;
- logmsg (5, 1, "extractregex(): $param $arg");
- if ($arg =~ /^\!/) {
- $arg =~ s/^\!//g;
+ logmsg (5, 1, "$param $arg");
+ if ($arg =~ /^!/) {
+ $arg =~ s/^!//g;
$$regex{negate} = 1;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^{//;
$arg =~ s/}$//;
$$regex{regex} = $arg;
- logmsg (9, 3, "extractregex(): \$regex\{regex\} = $$regex{regex} & \$regex\{negate\} = $$regex{negate}");
+ logmsg (9, 3, "$regex\{regex\} = $$regex{regex} & \$regex\{negate\} = $$regex{negate}");
- logmsg (5,2, "extractregex(): \$index = $index");
- logmsg (5, 2, "extractregex(): $param \[$index\]\{regex\} = $config{$rule}{$param}[$index]{regex}");
- logmsg (5, 2, "extractregex(): $param \[$index\]\{negate\} = $config{$rule}{$param}[$index]{negate}");
+ logmsg (5,2, "$index = $index");
+ logmsg (5, 2, "$param [$index\]\{regex\} = $$cfghashref{$param}[$index]{regex}");
+ logmsg (5, 2, "$param [$index\]\{negate\} = $$cfghashref{$param}[$index]{negate}");
for (my $i=0; $i<=$index; $i++)
{
- logmsg (5,1, "extractregex(): index: $i");
- foreach my $key (keys %{$config{$rule}{$param}[$i]}) {
- logmsg (5, 2, "extractregex(): $param \[$i\]\{$key\} = $config{$rule}{$param}[$i]{$key}");
+ logmsg (5,1, "index: $i");
+ foreach my $key (keys %{$$cfghashref{$param}[$i]}) {
+ logmsg (5, 2, "$param [$i\]\{$key\} = $$cfghashref{$param}[$i]{$key}");
}
}
}
sub report {
- print "\n\nNo match for lines:\n";
- foreach my $line (@{$results{nomatch}}) {
- print "\t$line";
+ my $cfghashref = shift;
+ my $reshashref = shift;
+ my $rpthashref = shift;
+
+ logmsg(1, 0, "Ruuning report");
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
+
+ logmsg(5, 1, "Dump of results hash ...");
+ pp(%$reshashref) if $DEBUG >= 5;
+
+ print "n\nNo match for lines:\n";
+ foreach my $line (@{@$rpthashref{nomatch}}) {
+ print "t$line";
}
- print "\n\nSummaries:\n";
- for my $rule (sort keys %results) {
+ print "n\nSummaries:\n";
+ for my $rule (sort keys %$rpthashref) {
next if $rule =~ /nomatch/;
- if (exists ($config{$rule}{rpttitle})) {
- print "$config{$rule}{rpttitle}:\n";
+ if (exists ($$cfghashref{rules}{$rule}{rpttitle})) {
+ print "$$cfghashref{rules}{$rule}{rpttitle}:n";
} else {
logmsg (4, 2, "Rule: $rule:");
}
- for my $key (keys %{$results{$rule}} ) {
- if (exists ($config{$rule}{rptline})) {
- print "\t".rptline($rule, $key)."\n";
+ for my $key (keys %{$$rpthashref{$rule}} ) {
+ if (exists ($$cfghashref{rules}{$rule}{rptline})) {
+ print "t".rptline($cfghashref, $reshashref, $rpthashref, $rule, $key)."\n";
} else {
- print "\t$results{$rule}{$key}: $key\n";
+ print "t$$rpthashref{$rule}{$key}: $key\n";
}
}
- print "\n";
+ print "n";
}
}
sub rptline {
+ my $cfghashref = shift;
+ my $reshashref = shift;
+ my $rpthashref = shift;
my $rule = shift;
my $key = shift;
- my $line = $config{$rule}{rptline};
+ my $line = $$cfghashref{rules}{$rule}{rptline};
+
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
- logmsg (9, 2, "rptline():");
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
+ logmsg (3, 2, "Starting with rule:$rule");
logmsg (9, 3, "key: $key");
my @fields = split /:/, $key;
logmsg (9, 3, "line: $line");
- $line =~ s/\{x\}/$results{$rule}{$key}{count}/;
+ $line =~ s/\{x\}/$$rpthashref{$rule}{$key}{count}/;
- if ($config{$rule}{cmd} eq "SUM") {
- $line =~ s/\{s\}/$results{$rule}{$key}{sum}/;
+ if ($$cfghashref{rules}{$rule}{cmd} eq "SUM") {
+ $line =~ s/\{s\}/$$rpthashref{$rule}{$key}{sum}/;
}
- if ($config{$rule}{cmd} eq "AVG") {
- my $avg = $results{$rule}{$key}{sum} / $results{$rule}{$key}{count};
+ if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
+ my $avg = $$rpthashref{$rule}{$key}{sum} / $$reshashref{$rule}{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{a\}/$avg/;
}
- logmsg (9, 3, "rptline(): #fields ".($#fields+1)." in \@fields");
+ logmsg (9, 3, "#fields ".($#fields+1)." in @fields");
for my $i (0..$#fields) {
my $field = $i+1;
- #my $field = $#fields;
- #for ($field; $field >= 0; $field--) {
- #for my $i ($#fields..0) {
- # my $field = $i+1;
- logmsg (9, 4, "rptline(): \$fields[$field] = $fields[$i]");
- if ($line =~ /\{$field\}/) {
- $line =~ s/\{$field\}/$fields[$i]/;
+ logmsg (9, 4, "$fields[$field] = $fields[$i]");
+ if ($line =~ /{$field\}/) {
+ $line =~ s/{$field\}/$fields[$i]/;
}
}
return $line;
}
sub actionrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
+
+ my $cfghashref = shift; # ref to $cfghash, would like to do $cfghash{rules}{$rule} but would break append
+ my $reshashref = shift;
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $value;
my $retval = 0; my $resultsrule;
- logmsg (9, 2, "actionrule()");
- if (exists ($config{$rule}{appendrule})) {
- $resultsrule = $config{$rule}{appendrule};
+ profile( whoami(), whowasi() );
+ logmsg (5, 0, " and I was called by ... ".whowasi);
+ logmsg (9, 2, "rule: $rule");
+
+ if (exists ($$cfghashref{rules}{$rule}{appendrule})) {
+ $resultsrule = $$cfghashref{rules}{$rule}{appendrule};
} else {
$resultsrule = $rule;
}
- logmsg (5, 3, "actionrule(): rule: $rule");
+ logmsg (5, 3, "rule: $rule");
logmsg (5, 4, "results goto: $resultsrule");
- logmsg (5, 4, "cmdregex: $config{$rule}{cmdregex}");
- logmsg (5, 4, "CMD negative regex: $config{$rule}{cmdregexnegat}");
+ logmsg (5, 4, "cmdregex: $}{cmdregex}");
+ logmsg (5, 4, "CMD negative regex: $$cfghashref{rules}{$rule}{cmdregexnegat}");
logmsg (5, 4, "line: $$line{line}");
- if ($config{$rule}{cmd} and $config{$rule}{cmd} =~ /IGNORE/) {
- if (exists ($config{$rule}{cmdregex}) ) {
- if ($config{$rule}{cmdregex} and $$line{line} =~ /$config{$rule}{cmdregex}/ ) {
- logmsg (5, 4, "actionrule(): rule $rule does matches and is a positive IGNORE rule");
+ if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /IGNORE/) {
+ if (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
+ if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
+ logmsg (5, 4, "rule $rule does matches and is a positive IGNORE rule");
}
} else {
- logmsg (5, 4, "actionrule(): rule $rule matches and is an IGNORE rule");
+ logmsg (5, 4, "rule $rule matches and is an IGNORE rule");
$retval = 1;
}
-
- #} elsif ($config{$rule}{cmdregexnegat} and $config{$rule}{cmdregex} and $$line{line} !~ /$config{$rule}{cmdregex}/ ) {
- # $retval = 0;
- # print "\tactionrule(): rule $rule doesn't match and is a negative IGNORE rule\n" if $DEBUG >= 5;
-
- #} elsif ($$line{line} =~ /$config{$rule}{cmdregex}/ ) {
- } elsif (exists ($config{$rule}{cmdregex}) ) {
- if ( not $config{$rule}{cmdregexnegat} ) {
- if ( $$line{line} =~ /$config{$rule}{cmdregex}/ ) {
- logmsg (5, 4, "actionrule(): Positive match, calling actionrulecmd");
- actionrulecmd($line, $rule, $resultsrule);
+ } elsif (exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
+ if ( not $$cfghashref{rules}{$rule}{cmdregexnegat} ) {
+ if ( $$line{line} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
+ logmsg (5, 4, "Positive match, calling actionrulecmd");
+ actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
- } elsif ($config{$rule}{cmdregexnegat}) {
- if ( $$line{line} !~ /$config{$rule}{cmdregex}/ ) {
- logmsg (5, 4, "actionrule(): Negative match, calling actionrulecmd");
- actionrulecmd($line, $rule, $resultsrule);
+ } elsif ($$cfghashref{rules}{$rule}{cmdregexnegat}) {
+ if ( $$line{line} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
+ logmsg (5, 4, "Negative match, calling actionrulecmd");
+ actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
}
} else {
- logmsg (5, 4, "actionrule(): No cmd regex, implicit match, calling actionrulecmd");
- actionrulecmd($line, $rule, $resultsrule);
+ logmsg (5, 4, "No cmd regex, implicit match, calling actionrulecmd");
+ actionrulecmd($cfghashref, $reshashref, $line, $rule, $resultsrule);
$retval = 1;
}
if ($retval == 0) {
- logmsg (5, 4, "actionrule(): line does not match cmdregex for rule: $rule");
- #logmsg (5, 4, "actionrule(): cmdregex: $config{$rule}{cmdregex} line: $$line{line}");
+ logmsg (5, 4, "line does not match cmdregex for rule: $rule");
}
return $retval;
}
sub actionrulecmd
{
+ my $cfghashref = shift;
+ my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift;
my $resultsrule = shift;
- logmsg (2, 2, "actionrulecmd(): actioning rule $rule for line: $$line{line}");
- if (not $config{$rule}{cmdregex}) {
- $config{$rule}{cmdregex} = "(.*)";
- logmsg (5, 3, "actionrulecmd(): rule did not define cmdregex, replacing with global match");
+ profile( whoami(), whowasi() );
+ logmsg (2, 2, "actioning rule $rule for line: $$line{line}");
+
+ # This sub contains the first half of the black magic
+ # The results from the regex's that are applied later
+ # are used in actioncmdmatrix()
+ #
+
+ # create a matrix that can be used for matching for the black magic happens
+ # Instead of the string cmdmatrix
+ # make a hash of matchmatrix{<match field#>} = <cmdregex field #>
+ # 2 arrays ...
+ # fieldnums ... the <match field #'s> of matchmatrix{}
+ # fieldnames ... the named matches of matchmatrix{}, these match back to the names of the fields
+ # from the file FORMAT
+ #
+ my @tmpmatrix = split (/,/, $$cfghashref{rules}{$rule}{cmdmatrix});
+ my @matrix = ();
+ for my $val (@tmpmatrix) {
+ if ($val =~ /(\d+)/ ) {
+ push @matrix, $val;
+ } else {
+ logmsg(3,3, "Not adding val:$val to matrix");
+ }
+ }
+ logmsg(3, 3, "matrix: @matrix");
+ #
+
+ if (not $$cfghashref{rules}{$rule}{cmdregex}) {
+ $$cfghashref{rules}{$rule}{cmdregex} = "(.*)";
+ logmsg (5, 3, "rule did not define cmdregex, replacing with global match");
}
- if ( exists $config{$rule}{cmd}) {
- logmsg (5, 3, "actionrulecmd(): Collecting data from cmd $config{$rule}{cmd}");
- logmsg (5, 3, "actionrulecmd(): rule $rule matches cmd") if $$line{msg} =~ /$config{$rule}{cmdregex}/;
+ if ( exists $$cfghashref{rules}{$rule}{cmd}) {
+ logmsg (5, 3, "Collecting data from cmd $$cfghashref{rules}{$rule}{cmd}");
+ logmsg (5, 3, "rule $rule matches cmd") if $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/;
}
- if (not exists ($config{$rule}{cmdregex}) ) {
- logmsg (5, 3, "actionrulecmd(): No cmd regex, calling actioncmdmatrix");
- actioncmdmatrix($line, $rule, $resultsrule);
- } elsif ($config{$rule}{cmdregexnegat} ) {
- if ($config{$rule}{cmdregex} and $$line{msg} and $$line{msg} !~ /$config{$rule}{cmdregex}/ ) {
- logmsg (5, 3, "\tactionrulecmd(): Negative match, calling actioncmdmatrix");
- actioncmdmatrix($line, $rule, $resultsrule);
+ if (not exists ($$cfghashref{rules}{$rule}{cmdregex}) ) {
+ logmsg (5, 3, "No cmd regex, calling actioncmdmatrix");
+ actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, @matrix);
+ } elsif ($$cfghashref{rules}{$rule}{cmdregexnegat} ) {
+ if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} !~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
+ logmsg (5, 3, "Negative match, calling actioncmdmatrix");
+ actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, @matrix);
}
} else {
- if ($config{$rule}{cmdregex} and $$line{msg} and $$line{msg} =~ /$config{$rule}{cmdregex}/ ) {
- logmsg (5, 3, "actionrulecmd(): Positive match, calling actioncmdmatrix");
- printhash ($line);
- actioncmdmatrix($line, $rule, $resultsrule);
+ if ($$cfghashref{rules}{$rule}{cmdregex} and $$line{msg} and $$line{msg} =~ /$$cfghashref{rules}{$rule}{cmdregex}/ ) {
+ logmsg (5, 3, "Positive match, calling actioncmdmatrixnline hash:");
+ &pp($line) if $DEBUG >= 5;
+ actioncmdmatrix($cfghashref, $reshashref, $line, $rule, $resultsrule, @matrix);
}
}
}
sub printhash
{
+ profile( whoami(), whowasi() );
my $line = shift; # hash passed by ref, DO NOT mod
foreach my $key (keys %{ $line} )
{
logmsg (9, 5, "$key: $$line{$key}");
}
}
sub actioncmdmatrix
{
+ my $cfghashref = shift;
+ my $reshashref = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift; # Name or ID of rule thats been matched
my $resultsrule = shift; # Name or ID of rule which contains the result set to be updated
- my $cmdmatrix = $config{$rule}{cmdmatrix};
+ my $matrixref = shift; # arrayref
+
+ profile( whoami(), whowasi() );
+ my $cmdmatrix = $$cfghashref{rules}{$rule}{cmdmatrix};
+ #my @matrix = shift; #split (/,/, $cmdmatrix);
+
my $fieldhash;
my $cmdfield;
- my @matrix = split (/,/, $cmdmatrix);
+
# @matrix - array of parameters that are used in results
- if ( exists ($config{$rule}{cmdfield}) ) {
- $cmdfield = ${$config{$rule}{cmdfield}};
+ if ( exists ($$cfghashref{rules}{$rule}{cmdfield}) ) {
+ $cmdfield = ${$$cfghashref{rules}{$rule}{cmdfield}};
}
- logmsg(5, 2, "Entering actioncmdmatrix():");
- logmsg(6, 3, "resultsrule = $rule");
+ logmsg(5, 2, " ... actioning resultsrule = $rule");
- if ( exists $config{$rule}{cmdmatrix}) {
- logmsg (5, 3, "actioncmdmatrix(): Collecting data for matrix $config{$rule}{cmdmatrix}");
+ if ( exists $$cfghashref{rules}{$rule}{cmdmatrix}) {
+ logmsg (5, 3, "Collecting data for matrix $$cfghashref{rules}{$rule}{cmdmatrix}");
+ logmsg (5, 3, "Using matrix @$matrixref");
+
+ # this is where "strict refs" breaks things
+ # sample: @matrix = svr,1,4,5
+ # error ... can't use string ("svr") as a SCALAR ref while "strict refs" in use
+ #
+
+ # soln: create a temp array which only has the field #'s and match that
+ # might need a hash to match
- foreach my $field (@matrix) {
+ no strict 'refs'; # turn strict refs off just for this section
+ foreach my $field (@$matrixref) {
# This is were the black magic occurs, ${$field} causes becomes $1 or $2 etc
# and hence contains the various matches from the previous regex match
# which occured just before this function was called
- logmsg (9, 4, "actioncmdmatrix(): matrix field $field has value ${$field}");
+
+ logmsg (9, 4, "matrix field $field has value ${$field}");
if (exists $$line{$field}) {
if ($fieldhash) {
$fieldhash = "$fieldhash:$$line{$field}";
} else {
$fieldhash = "$$line{$field}";
}
} else {
if ($fieldhash) {
$fieldhash = "$fieldhash:${$field}";
} else {
if ( ${$field} ) {
$fieldhash = "${$field}";
} else {
- logmsg (1, 4, "actioncmdmatrix(): $field not found in \"$$line{line}\" with regex $config{$rule}{cmdregex}");
- printhash($line);
+ logmsg (1, 4, "$field not found in \"$$line{line}\" with regex $$cfghashref{rules}{$rule}{cmdregex}");
+ logmsg (1, 4, "line hash:");
+ printhash($line) if $DEBUG >= 1;
}
}
}
}
- if ($config{$rule}{targetfield}) {
- logmsg (1, 4, "actioncmdmatrix(): Setting cmdfield (field $config{$rule}{targetfield}) to ${$config{$rule}{targetfield}}");
- $cmdfield = ${$config{$rule}{targetfield}};
+ use strict 'refs';
+ if ($$cfghashref{rules}{$rule}{targetfield}) {
+ logmsg (1, 4, "Setting cmdfield (field $$cfghashref{rules}{$rule}{targetfield}) to ${$$cfghashref{rules}{$rule}{targetfield}}");
+ $cmdfield = ${$$cfghashref{rules}{$rule}{targetfield}};
}
- #if ($config{$rule}{cmd} and $config{$rule}{cmd} =~ /^COUNT$/) {
- $results{$resultsrule}{$fieldhash}{count}++;
- logmsg (5, 4, "actioncmdmatrix(): $results{$resultsrule}{$fieldhash}{count} matches for rule $rule so far from $fieldhash");
+ #if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
+ $$reshashref{$resultsrule}{$fieldhash}{count}++;
+ logmsg (5, 4, "$$reshashref{$resultsrule}{$fieldhash}{count} matches for rule $rule so far from $fieldhash");
#} els
- if ($config{$rule}{cmd} eq "SUM" or $config{$rule}{cmd} eq "AVG") {
- $results{$resultsrule}{$fieldhash}{sum} = $results{$resultsrule}{$fieldhash}{sum} + $cmdfield;
- logmsg (5, 4, "actioncmdmatrix(): Adding $cmdfield to total (now $results{$resultsrule}{$fieldhash}{sum}) for rule $rule so far from $fieldhash");
- if ($config{$rule}{cmd} eq "AVG") {
- logmsg (5, 4, "actioncmdmatrix(): Average is ".$results{$resultsrule}{$fieldhash}{sum} / $results{$resultsrule}{$fieldhash}{count}." for rule $rule so far from $fieldhash");
+ if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
+ $$reshashref{$resultsrule}{$fieldhash}{sum} = $$reshashref{$resultsrule}{$fieldhash}{sum} + $cmdfield;
+ logmsg (5, 4, "Adding $cmdfield to total (now $$reshashref{$resultsrule}{$fieldhash}{sum}) for rule $rule so far from $fieldhash");
+ if ($$cfghashref{rules}{$rule}{cmd} eq "AVG") {
+ logmsg (5, 4, "Average is ".$$reshashref{$resultsrule}{$fieldhash}{sum} / $$reshashref{$resultsrule}{$fieldhash}{count}." for rule $rule so far from $fieldhash");
}
}
- for my $key (keys %{$results{$resultsrule}}) {
- logmsg (5, 3, "actioncmdmatrix(): key $key for rule:$rule with $results{$resultsrule}{$key}{count} matches");
+ for my $key (keys %{$$reshashref{$resultsrule}}) {
+ logmsg (5, 3, "key $key for rule:$rule with $$reshashref{$resultsrule}{$key}{count} matches");
}
- logmsg (5, 2, "actioncmdmatrix(): $fieldhash matches for rule $rule so far from matrix: $config{$rule}{cmdmatrix}");
+ logmsg (5, 2, "$fieldhash matches for rule $rule so far from matrix: $$cfghashref{rules}{$rule}{cmdmatrix}");
} else {
- logmsg (5, 2, "actioncmdmatrix(): cmdmatrix is not set for $rule");
- #if ($config{$rule}{cmd} and $config{$rule}{cmd} =~ /^COUNT$/) {
- $results{$resultsrule}{count}++;
- logmsg (5, 3, "actioncmdmatrix(): $results{$resultsrule}{count} lines match rule $rule so far");
+ logmsg (5, 2, "cmdmatrix is not set for $rule");
+ #if ($$cfghashref{rules}{$rule}{cmd} and $$cfghashref{rules}{$rule}{cmd} =~ /^COUNT$/) {
+ $$reshashref{$resultsrule}{count}++;
+ logmsg (5, 3, "$$reshashref{$resultsrule}{count} lines match rule $rule so far");
# } els
- if ($config{$rule}{cmd} eq "SUM" or $config{$rule}{cmd} eq "AVG") {
- $results{$resultsrule}{sum} = $results{$resultsrule}{sum} + $cmdfield;
- logmsg (5, 3, "actioncmdmatrix(): $results{$resultsrule}{sum} lines match rule $rule so far");
+ if ($$cfghashref{rules}{$rule}{cmd} eq "SUM" or $$cfghashref{rules}{$rule}{cmd} eq "AVG") {
+ $$reshashref{$resultsrule}{sum} = $$reshashref{$resultsrule}{sum} + $cmdfield;
+ logmsg (5, 3, "$$reshashref{$resultsrule}{sum} lines match rule $rule so far");
}
}
}
sub defaultregex {
# expects a reference to the rule and param
my $paramref = shift;
+ profile( whoami(), whowasi() );
if (defined $$paramref[0]{regex} ) {
- logmsg(9, 4, "defaultregex(): Skipping, there are already regex hashes in this rule/param match");
- logmsg(9, 5, "defaultregex(): regex[0]regex = $$paramref[0]{regex}");
- logmsg(9, 5, "defaultregex(): regex[0]negate = $$paramref[0]{negate}");
+ logmsg(9, 4, "Skipping, there are already regex hashes in this rule/param match");
+ logmsg(9, 5, "regex[0]regex = $$paramref[0]{regex}");
+ logmsg(9, 5, "regex[0]negate = $$paramref[0]{negate}");
} else {
- logmsg(9, 1, "defaultregex(): There's no regex hash for this rule/param so setting defaults");
+ logmsg(9, 1, "There's no regex hash for this rule/param so setting defaults");
$$paramref[0]{regex} = "(.*)";
$$paramref[0]{negate} = 0 ;
}
}
sub matchregex {
# expects a reference to a regex for a given rule & param
# For a given rules regex hash, return true/false for a match
my $regex = shift;
my $value = shift;
my $match = 0;
- if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
- #logmsg (5, 4, "Matches rule: $rule");
+ profile( whoami(), whowasi() );
+ if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^*$/ ) {
+ logmsg (9, 4, "value ($value) matches regex /$$regex{regex}/");
$match = 1;
- }
+ } else {
+ logmsg (9, 4, "value ($value) doesn't match regex /$$regex{regex}/");
+ }
}
sub matchingrules {
+ my $cfghashref = shift;
my $param = shift;
- my $matches = shift;
+ my $matchref = shift;
my $value = shift;
- logmsg (3, 2, "\nmatchingrules(): param: $param, match count: ".keys(%{$matches})." value: $value");
+ profile( whoami(), whowasi() );
- if (keys %{$matches} == 0) {
+ logmsg (6, 3, "param:$param ");
+ logmsg (6,3, "value:$value");
+ logmsg (3, 2, " $param, match count: ".keys(%{$matchref})." value: $value");
+
+ if (keys %{$matchref} == 0) {
# Check all rules as we haevn't had a match yet
- foreach my $rule (keys %config) {
- checkrule($param, $matches, $rule, $value);
+ foreach my $rule (keys %{$cfghashref->{rules} } ) {
+ checkrule($cfghashref, $param, $matchref, $rule, $value);
}
} else {
# As we've allready had a match on the rules, only check those that matched in earlier rounds
# key in %matches is the rule that matches
- foreach my $rule (keys %{$matches}) {
- checkrule($param, $matches, $rule, $value);
+ foreach my $rule (keys %{$matchref}) {
+ checkrule($cfghashref, $param, $matchref, $rule, $value);
}
}
}
sub checkrule {
+ my $cfghashref = shift;
my $param = shift;
my $matches = shift;
my $rule = shift; # key to %matches
my $value = shift;
- logmsg(2, 1, "checkrule(): Checking rule ($rule) & param ($param) for matches against: $value");
+ profile( whoami(), whowasi() );
+ logmsg(2, 1, "Checking rule ($rule) & param ($param) for matches against: $value");
- my $paramref = \@{ $config{$rule}{$param} };
+ my $paramref = \@{ $$cfghashref{rules}{$rule}{$param} };
defaultregex($paramref); # This should be done when reading the config
foreach my $index (@{ $paramref } ) {
my $match = matchregex($index, $value);
if ($$index{negate} ) {
if ( $match) {
delete $$matches{$rule};
- logmsg (5, 5, "checkrules(): matches $index->{regex} for param \'$param\', but negative rule is set, so removing rule $match from list.");
+ logmsg (5, 5, "matches $index->{regex} for param '$param\', but negative rule is set, so removing rule $match from list.");
} else {
$$matches{$rule} = "match" if $match;
- logmsg (5, 5, "checkrules(): Doesn't match for $index->{regex} for param \'$param\', but negative rule is set, so leaving rule $match on list.");
+ logmsg (5, 5, "Doesn't match for $index->{regex} for param '$param\', but negative rule is set, so leaving rule $match on list.");
}
} elsif ($match) {
$$matches{$rule} = "match" if $match;
- logmsg (5, 4, "checkrules(): matches $index->{regex} for param \'$param\', leaving rule $match on list.");
+ logmsg (5, 4, "matches $index->{regex} for param '$param\', leaving rule $match on list.");
} else {
delete $$matches{$rule};
- logmsg (5, 4, "checkrules(): doesn't match $index->{regex} for param \'$param\', removing rule $match from list.");
+ logmsg (5, 4, "doesn't match $index->{regex} for param '$param\', removing rule $match from list.");
}
} # for each regex hash in the array
- logmsg (3, 2, "checkrules(): matches ".keys (%{$matches})." matches after checking rules for $param");
+ logmsg (3, 2, "matches ".keys (%{$matches})." matches after checking rules for $param");
}
=oldcode
sub matchingrules {
+ my $cfghashref = shift;
my $param = shift;
my $matches = shift;
my $value = shift;
- logmsg (3, 2, "matchingrules(): param: $param, matches: $matches, value: $value");
+ profile( whoami(), whowasi() );
+ logmsg (3, 2, "param: $param, matches: $matches, value: $value");
if (keys %{$matches} == 0) {
# Check all rules as we haevn't had a match yet
foreach my $rule (keys %config) {
- $config{$rule}{$param} = "(.*)" unless exists ($config{$rule}{$param});
- logmsg (5, 3, "Does $value match /$config{$rule}{$param}/ ??");
- if ($value =~ /$config{$rule}{$param}/ or $config{$rule}{$param} =~ /^\*$/ ) {
+ $$cfghashref{rules}{$rule}{$param} = "(.*)" unless exists ($$cfghashref{rules}{$rule}{$param});
+ logmsg (5, 3, "Does $value match /$$cfghashref{rules}{$rule}{$param}/ ??");
+ if ($value =~ /$$cfghashref{rules}{$rule}{$param}/ or $$cfghashref{rules}{$rule}{$param} =~ /^*$/ ) {
logmsg (5, 4, "Matches rule: $rule");
$$matches{$rule} = "match";
}
}
} else {
# As we've allready had a match on the rules, only check those that matched in earlier rounds
foreach my $match (keys %{$matches}) {
- if (exists ($config{$match}{$param}) ) {
- logmsg (5, 4, "Does value: \"$value\" match \'$config{$match}{$param}\' for param $param ??");
- if ($config{$match}{"${param}negat"}) {
+ if (exists ($$cfghashref{rules}{$match}{$param}) ) {
+ logmsg (5, 4, "Does value: "$value\" match \'$$cfghashref{rules}{$match}{$param}\' for param $param ??");
+ if ($$cfghashref{rules}{$match}{"${param}negat"}) {
logmsg (5, 5, "Doing a negative match");
}
} else {
- logmsg (5, 3, "No rule for value: \"$value\" in rule $match, leaving on match list.");
- $config{$match}{$param} = "(.*)";
+ logmsg (5, 3, "No rule for value: "$value\" in rule $match, leaving on match list.");
+ $$cfghashref{rules}{$match}{$param} = "(.*)";
}
- if ($config{$match}{"${param}negat"}) {
- if ($value =~ /$config{$match}{$param}/ or $config{$match}{$param} =~ /^\*$/ ) {
+ if ($$cfghashref{rules}{$match}{"${param}negat"}) {
+ if ($value =~ /$$cfghashref{rules}{$match}{$param}/ or $$cfghashref{rules}{$match}{$param} =~ /^*$/ ) {
delete $$matches{$match};
- logmsg (5, 5, "matches $config{$match}{$param} for param \'$param\', but negative rule is set, so removing rule $match from list.");
+ logmsg (5, 5, "matches $$cfghashref{rules}{$match}{$param} for param '$param\', but negative rule is set, so removing rule $match from list.");
} else {
- logmsg (5, 5, "Doesn't match for $config{$match}{$param} for param \'$param\', but negative rule is set, so leaving rule $match on list.");
+ logmsg (5, 5, "Doesn't match for $$cfghashref{rules}{$match}{$param} for param '$param\', but negative rule is set, so leaving rule $match on list.");
}
- } elsif ($value =~ /$config{$match}{$param}/ or $config{$match}{$param} =~ /^\*$/ ) {
- logmsg (5, 4, "matches $config{$match}{$param} for param \'$param\', leaving rule $match on list.");
+ } elsif ($value =~ /$$cfghashref{rules}{$match}{$param}/ or $$cfghashref{rules}{$match}{$param} =~ /^*$/ ) {
+ logmsg (5, 4, "matches $$cfghashref{rules}{$match}{$param} for param '$param\', leaving rule $match on list.");
} else {
delete $$matches{$match};
- logmsg (5, 4, "doesn't match $config{$match}{$param} for param \'$param\', removing rule $match from list.");
+ logmsg (5, 4, "doesn't match $$cfghashref{rules}{$match}{$param} for param '$param\', removing rule $match from list.");
}
}
}
logmsg (3, 2, keys (%{$matches})." matches after checking rules for $param");
}
=cut
+
+sub whoami { ( caller(1) )[3] }
+sub whowasi { ( caller(2) )[3] }
+
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
+print "$DEBUG";
if ($DEBUG >= $level) {
for my $i (0..$indent) {
print STDERR " ";
}
- print STDERR "$msg\n";
+ print STDERR whowasi."(): $msg\n";
}
}
+sub profile {
+ my $caller = shift;
+ my $parent = shift;
+
+ $profile{$parent}{$caller}++;
+
+}
+
+sub profilereport {
+ pp(%profile);
+}
+
|
mikeknox/LogParse | 3c101dc5e144db286491f80f441374374eea14b3 | Now allows the logfile fields specifications in the config to have multiple entires ie. you can do MSG /abc/ MSG /!def/ in the same stanza, and both are applied when evaluating the rule | diff --git a/logparse.pl b/logparse.pl
old mode 100644
new mode 100755
index 48b0a7c..86336f7
--- a/logparse.pl
+++ b/logparse.pl
@@ -1,572 +1,706 @@
#!/usr/bin/perl
# Copyright 2003, 2009 Michael Knox, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=head1 NAME
logparse - syslog analysis tool
=cut
-=head SYNOPSIS
+=head1 SYNOPSIS
+./logparse.pl [-c <configfile> ] [-l <logfile>] [-d <debug level>]
-# Describe config file for log parse / summary engine
-# Input fields from syslog:
-# Date, time, server, application, facility, ID, message
-#
-# Config line
-# /server regex/, /app regex/, /facility regex/, /msg regex/, $ACTIONS
-# Summaries are required at various levels, from total instances to total sizes to server summaries.
-#
-# ACTIONS:
-# COUNT - Just list the total number of matches
-# SUM[x] - Report the sum of field x of all matches
-# SUM[x], /regex/ - Apply regex to msg field of matches and report the sum of field x from that regex
-# SUM[x], /regex/, {y,z} - Apply regex to msg field of matches and report the sum of field x from that regex for fields y & z
-# AVG[x], /regex/, {y,z} - Apply regex to msg field of matches and report the avg of field x from that regex for fields y & z
-# COUNT[x], /regex/, {y,z} - Apply regex to msg field of matches and report the count of field x from that regex for matching fields y & z
-#
-# Each entry can test or regex, if text interpret as regex /^string$/
-# Sample entry...
-# *, /rshd/, *, *, COUNT /connect from (.*)/, {1}
+Describe config file for log parse / summary engine
+ Input fields from syslog:
+ Date, time, server, application, facility, ID, message
+
+=head3 Config line
+ /server regex/, /app regex/, /facility regex/, /msg regex/, $ACTIONS
+ Summaries are required at various levels, from total instances to total sizes to server summaries.
+
+=head2 ACTIONS
+ COUNT - Just list the total number of matches
+ SUM[x] - Report the sum of field x of all matches
+ SUM[x], /regex/ - Apply regex to msg field of matches and report the sum of field x from that regex
+ SUM[x], /regex/, {y,z} - Apply regex to msg field of matches and report the sum of field x from that regex for fields y & z
+ AVG[x], /regex/, {y,z} - Apply regex to msg field of matches and report the avg of field x from that regex for fields y & z
+ COUNT[x], /regex/, {y,z} - Apply regex to msg field of matches and report the count of field x from that regex for matching fields y & z
-# BUGS:
+ Each entry can test or regex, if text interpret as regex /^string$/
+ Sample entry...
+ *, /rshd/, *, *, COUNT /connect from (.*)/, {1}
-# TODO:
+=head2 BUGS:
+
+=head2 TODO:
=cut
# expects data on std in
use strict;
use Getopt::Std;
no strict 'refs';
my %opts;
my $CONFIGFILE="logparse.conf";
my %config;
my %results;
my $cmdcount = 0;
my $UNMATCHEDLINES = 1;
my $DEBUG = 0;
my $SYSLOGFILE = "/var/log/messages";
my %svrlastline; # hash of the last line per server, excluding 'last message repeated x times'
getopt('cdl', \%opts);
$DEBUG = $opts{d} if $opts{d};
$CONFIGFILE = $opts{c} if $opts{c};
$SYSLOGFILE = $opts{l} if $opts{l};
open (CFGFILE, "<$CONFIGFILE");
my $rule;
while (<CFGFILE>) {
my $line = $_;
my $cmd; my $arg;
chomp $line;
next if $line =~ /^#|\s+#/;
$line = $1 if $line =~ /^\s+(.*)/;
($cmd, $arg) = split (/\s+/, $line, 2);
next unless $cmd;
logmsg (6, 0, "main(): parse cmd: $cmd arg: $arg");
for ($cmd) {
if (/RULE/) {
if ($arg =~ /(.*)\s+\{/) {
$rule = $1;
} else {
$rule = $cmdcount++;
}
} elsif (/HOST/) {
extractregex ("svrregex", $arg);
} elsif (/APP($|\s+)/) {
extractregex ("appregex", $arg);
} elsif (/FACILITY/) {
extractregex ("facregex", $arg);
} elsif (/MSG/) {
extractregex ("msgregex", $arg);
} elsif (/CMD/) {
extractregex ("cmd", $arg) unless $arg =~ /\{/;
} elsif (/^REGEX/) {
- extractregex ("cmdregex", $arg);
+ extractregexold ("cmdregex", $arg);
} elsif (/MATCH/) {
- extractregex ("cmdmatrix", $arg);
+ extractregexold ("cmdmatrix", $arg);
$config{$rule}{cmdmatrix} =~ s/\s+//g; # strip all whitespace
+ } elsif (/IGNORE/) {
+ $config{$rule}{cmd} = $cmd;
} elsif (/COUNT/) {
$config{$rule}{cmd} = $cmd;
} elsif (/SUM/) {
extractregex ("targetfield", $arg);
$config{$rule}{targetfield} =~ s/\s+//g; # strip all whitespace
$config{$rule}{cmd} = $cmd;
} elsif (/AVG/) {
extractregex ("targetfield", $arg);
$config{$rule}{targetfield} =~ s/\s+//g; # strip all whitespace
$config{$rule}{cmd} = $cmd;
} elsif (/TITLE/) {
$config{$rule}{rpttitle} = $arg;
$config{$rule}{rpttitle} = $1 if $config{$rule}{rpttitle} =~ /^\"(.*)\"$/;
} elsif (/LINE/) {
$config{$rule}{rptline} = $arg;
$config{$rule}{rptline} = $1 if $config{$rule}{rptline} =~ /^\"(.*)\"$/;
} elsif (/APPEND/) {
$config{$rule}{appendrule} = $arg;
logmsg (1, 0, "*** Setting append for $rule to $arg");
} elsif (/REPORT/) {
} elsif (/^\}$/) {
} elsif (/^\{$/) {
} else {
print "Error: $cmd didn't match any known commands\n\n";
}
}
- #if ($DEBUG >= 5)
- #{
- logmsg (5, 1, "rule: $rule");
+ logmsg (5, 1, "main() rule: $rule");
for my $key (keys %{ $config{$rule} } ) {
- logmsg (5, 2, "$key: $config{$rule}{$key}");
+ foreach my $index (@{ $config{$rule}{$key} } ) {
+ logmsg (5, 2, "main() key=$key");
+ for my $regkey (keys %{ $index} ) {
+ logmsg (5,3, "main(): $regkey=$$index{$regkey}");
+ }
+ }
}
- #}
}
open (LOGFILE, "<$SYSLOGFILE") or die "Unable to open $SYSLOGFILE for reading...";
while (<LOGFILE>) {
#my $mth; my $date; my $time; my $svr; my $app; my $msg;
my $facility;
-# my $actval = 0;
my %line;
# Placing line and line componenents into a hash to be passed to actrule, components can then be refered
# to in action lines, ie {svr} instead of trying to create regexs to collect individual bits
$line{line} = $_;
logmsg (5, 1, "Processing next line");
($line{mth}, $line{date}, $line{time}, $line{svr}, $line{app}, $line{msg}) = split (/\s+/, $line{line}, 6);
logmsg (9, 2, "mth: $line{mth}, date: $line{date}, time: $line{time}, svr: $line{svr}, app: $line{app}, msg: $line{msg}");
- #$facility = $1 and $msg = $2 if $msg =~ /\[(.*)\](.*)/;
+
if ($line{msg} =~ /^\[/) {
($line{facility}, $line{msg}) = split (/\]\s+/, $line{msg}, 2);
$line{facility} =~ s/\[//;
}
logmsg (9, 1, "Checking line: $line{line}");
logmsg (9, 1, "facility: $line{facility}");
logmsg (9, 1, "msg: $line{msg}");
- # Does svr match
- # Check others
my %matches;
- matchingrules("appregex", \%matches, $line{app});
- $results{nomatch}[$#{$results{nomatch}}+1] = $line{line} and next unless keys %matches > 0;
- matchingrules("facregex", \%matches, $line{facility});
- $results{nomatch}[$#{$results{nomatch}}+1] = $line{line} and next unless keys %matches > 0;
- matchingrules("msgregex", \%matches, $line{msg});
+ my %matchregex = ("svrregex", "svr", "appregex", "app", "facregex", "facility", "msgregex", "line");
+ for my $param ("appregex", "facregex", "msgregex", "svrregex") {
+ matchingrules($param, \%matches, $line{ $matchregex{$param} } );
+ }
$results{nomatch}[$#{$results{nomatch}}+1] = $line{line} and next unless keys %matches > 0;
- matchingrules("svrregex", \%matches, $line{svr});
if ($line{msg} =~ /message repeated/ and exists $svrlastline{$line{svr} }{line}{msg} ) { # and keys %{$svrlastline{ $line{svr} }{rulematches}} ) {
logmsg (9, 2, "last message repeated and matching svr line");
my $numrepeats = 0;
if ($line{msg} =~ /message repeated (.*) times/) {
$numrepeats = $1;
}
logmsg(9, 2, "Last message repeated $numrepeats times");
for my $i (1..$numrepeats) {
for my $rule (keys %{$svrlastline{ $line{svr} }{rulematches} } ) {
logmsg (5, 3, "Applying cmd for rule $rule: $config{$rule}{cmd} - as prelim regexs pass");
actionrule($rule, \%{ $svrlastline{$line{svr} }{line} }); # if $actrule == 0;
}
}
} else {
logmsg (5, 2, "No recorded last line for $line{svr}") if $line{msg} =~ /message repeated/;
logmsg (9, 2, "msg: $line{msg}");
%{ $svrlastline{$line{svr} }{line} } = %line;
# track line
# track matching rule(s)
logmsg (3, 2, keys (%matches)." matches after checking all rules");
if (keys %matches > 0) {
logmsg (5, 2, "svr & app & fac & msg matched rules: ");
for my $key (keys %matches) {
logmsg (5, 3, "$key ");
}
logmsg (5, 2, " rules from line $line{line}");
# loop through matching rules and collect data as defined in the ACTIONS section of %config
my $actrule = 0;
my %tmpmatches = %matches;
for my $rule (keys %tmpmatches) {
my $result = actionrule($rule, \%line);
delete $matches{$rule} unless $result ;
$actrule = $result unless $actrule;
logmsg (5, 3, "Applying cmd from rule $rule: $config{$rule}{cmd} as passed prelim regexes");
logmsg (10, 4, "an action rule matched: $actrule");
}
logmsg (10, 4, "an action rule matched: $actrule");
$results{nomatch}[$#{$results{nomatch}}+1] = $line{line} if $actrule == 0;
%{$svrlastline{$line{svr} }{rulematches}} = %matches unless ($line{msg} =~ /last message repeated \d+ times/);
logmsg (5, 2, "main(): setting lastline match for server: $line{svr} and line:\n$line{line}");
logmsg (5, 3, "added matches for $line{svr} for rules:");
for my $key (keys %{$svrlastline{$line{svr} }{rulematches}}) {
logmsg (5, 4, "$key");
}
logmsg (5, 3, "rules from line $line{line}");
} else {
logmsg (5, 2, "No match: $line{line}") if $UNMATCHEDLINES;
if ($svrlastline{$line{svr} }{unmatchedline}{msg} eq $line{msg} ) {
$svrlastline{$line{svr} }{unmatchedline}{count}++;
logmsg (9, 3, "$svrlastline{$line{svr} }{unmatchedline}{count} instances of msg: $line{msg} on $line{svr}");
} else {
$svrlastline{$line{svr} }{unmatchedline}{count} = 0 unless exists $svrlastline{$line{svr} }{unmatchedline}{count};
if ($svrlastline{$line{svr} }{unmatchedline}{msg} and $svrlastline{$line{svr} }{unmatchedline}{count} >= 1) {
$results{nomatch}[$#{$results{nomatch}}+1] = "$line{svr}: Last unmatched message repeated $svrlastline{$line{svr} }{unmatchedline}{count} times\n";
} else {
$results{nomatch}[$#{$results{nomatch}}+1] = $line{line};
$svrlastline{$line{svr} }{unmatchedline}{msg} = $line{msg};
}
$svrlastline{$line{svr} }{unmatchedline}{count} = 0;
}
logmsg (5, 2, "main(): set unmatched{ $line{svr} }{msg} to $svrlastline{$line{svr} }{unmatchedline}{msg} and count to: $svrlastline{$line{svr} }{unmatchedline}{count}");
}
}
logmsg (5, 1, "main(): finished processing line");
}
foreach my $server (keys %svrlastline) {
if ( $svrlastline{$server}{unmatchedline}{count} >= 1) {
logmsg (9, 2, "main(): Added record #".( $#{$results{nomatch}} + 1 )." for unmatched results");
$results{nomatch}[$#{$results{nomatch}}+1] = "$server: Last unmatched message repeated $svrlastline{$server }{unmatchedline}{count} times\n";
}
}
report();
exit 0;
-sub extractregex {
+sub extractregexold {
+ # Keep the old behaviour
+
my $param = shift;
my $arg = shift;
- my $paramnegat = $param."negat";
+ my $paramnegat = $param."negate";
logmsg (5, 1, "extractregex(): $param $arg");
if ($arg =~ /^\!/) {
$arg =~ s/^\!//g;
$config{$rule}{$paramnegat} = 1;
} else {
$config{$rule}{$paramnegat} = 0;
}
# strip leading and trailing /'s
$arg =~ s/^\///;
$arg =~ s/\/$//;
# strip leading and trailing brace's {}
$arg =~ s/^{//;
$arg =~ s/}$//;
$config{$rule}{$param} = $arg;
- logmsg (5, 2, "extractregex(): $param = $config{$rule}{$param}");
+ logmsg (5, 2, "extractregex(): $param = $config{$rule}{$param}");
+
+}
+
+sub extractregex {
+ # Put the matches into an array, but would need to change how we handle negates
+ # Currently the negate is assigned to match group (ie facility or host) or rather than
+ # an indivudal regex, not an issue immediately because we only support 1 regex
+ # Need to assign the negate to the regex
+ # Make the structure ...
+ # $config{$rule}{$param}[$index] is a hash with {regex} and {negate}
+
+ my $param = shift;
+ my $arg = shift;
+ my $index = @{$config{$rule}{$param}};
+ $index = 0 if $index == "";
+
+ my $regex = \%{$config{$rule}{$param}[$index]};
+
+ $$regex{negate} = 0;
+
+ logmsg (5, 1, "extractregex(): $param $arg");
+ if ($arg =~ /^\!/) {
+ $arg =~ s/^\!//g;
+ $$regex{negate} = 1;
+ }
+
+# strip leading and trailing /'s
+ $arg =~ s/^\///;
+ $arg =~ s/\/$//;
+# strip leading and trailing brace's {}
+ $arg =~ s/^{//;
+ $arg =~ s/}$//;
+ $$regex{regex} = $arg;
+ logmsg (9, 3, "extractregex(): \$regex\{regex\} = $$regex{regex} & \$regex\{negate\} = $$regex{negate}");
+
+ logmsg (5,2, "extractregex(): \$index = $index");
+ logmsg (5, 2, "extractregex(): $param \[$index\]\{regex\} = $config{$rule}{$param}[$index]{regex}");
+ logmsg (5, 2, "extractregex(): $param \[$index\]\{negate\} = $config{$rule}{$param}[$index]{negate}");
+
+ for (my $i=0; $i<=$index; $i++)
+ {
+ logmsg (5,1, "extractregex(): index: $i");
+ foreach my $key (keys %{$config{$rule}{$param}[$i]}) {
+ logmsg (5, 2, "extractregex(): $param \[$i\]\{$key\} = $config{$rule}{$param}[$i]{$key}");
+ }
+ }
}
sub report {
print "\n\nNo match for lines:\n";
foreach my $line (@{$results{nomatch}}) {
print "\t$line";
}
print "\n\nSummaries:\n";
for my $rule (sort keys %results) {
next if $rule =~ /nomatch/;
if (exists ($config{$rule}{rpttitle})) {
print "$config{$rule}{rpttitle}:\n";
} else {
logmsg (4, 2, "Rule: $rule:");
}
for my $key (keys %{$results{$rule}} ) {
if (exists ($config{$rule}{rptline})) {
print "\t".rptline($rule, $key)."\n";
} else {
print "\t$results{$rule}{$key}: $key\n";
}
}
print "\n";
}
}
sub rptline {
my $rule = shift;
my $key = shift;
my $line = $config{$rule}{rptline};
# generate rpt line based on config spec for line and results.
# Sample entry: {x}: logouts from {2} by {1}
logmsg (9, 2, "rptline():");
logmsg (9, 3, "key: $key");
my @fields = split /:/, $key;
logmsg (9, 3, "line: $line");
$line =~ s/\{x\}/$results{$rule}{$key}{count}/;
if ($config{$rule}{cmd} eq "SUM") {
$line =~ s/\{s\}/$results{$rule}{$key}{sum}/;
}
if ($config{$rule}{cmd} eq "AVG") {
my $avg = $results{$rule}{$key}{sum} / $results{$rule}{$key}{count};
$avg = sprintf ("%.3f", $avg);
$line =~ s/\{a\}/$avg/;
}
logmsg (9, 3, "rptline(): #fields ".($#fields+1)." in \@fields");
for my $i (0..$#fields) {
my $field = $i+1;
#my $field = $#fields;
#for ($field; $field >= 0; $field--) {
#for my $i ($#fields..0) {
# my $field = $i+1;
logmsg (9, 4, "rptline(): \$fields[$field] = $fields[$i]");
if ($line =~ /\{$field\}/) {
$line =~ s/\{$field\}/$fields[$i]/;
}
}
return $line;
}
sub actionrule {
# Collect data for rule $rule as defined in the ACTIONS section of %config
my $rule = shift;
my $line = shift; # hash passed by ref, DO NOT mod
my $value;
my $retval = 0; my $resultsrule;
logmsg (9, 2, "actionrule()");
if (exists ($config{$rule}{appendrule})) {
$resultsrule = $config{$rule}{appendrule};
} else {
$resultsrule = $rule;
}
logmsg (5, 3, "actionrule(): rule: $rule");
logmsg (5, 4, "results goto: $resultsrule");
logmsg (5, 4, "cmdregex: $config{$rule}{cmdregex}");
logmsg (5, 4, "CMD negative regex: $config{$rule}{cmdregexnegat}");
logmsg (5, 4, "line: $$line{line}");
if ($config{$rule}{cmd} and $config{$rule}{cmd} =~ /IGNORE/) {
if (exists ($config{$rule}{cmdregex}) ) {
if ($config{$rule}{cmdregex} and $$line{line} =~ /$config{$rule}{cmdregex}/ ) {
logmsg (5, 4, "actionrule(): rule $rule does matches and is a positive IGNORE rule");
}
} else {
logmsg (5, 4, "actionrule(): rule $rule matches and is an IGNORE rule");
$retval = 1;
}
#} elsif ($config{$rule}{cmdregexnegat} and $config{$rule}{cmdregex} and $$line{line} !~ /$config{$rule}{cmdregex}/ ) {
# $retval = 0;
# print "\tactionrule(): rule $rule doesn't match and is a negative IGNORE rule\n" if $DEBUG >= 5;
#} elsif ($$line{line} =~ /$config{$rule}{cmdregex}/ ) {
} elsif (exists ($config{$rule}{cmdregex}) ) {
if ( not $config{$rule}{cmdregexnegat} ) {
if ( $$line{line} =~ /$config{$rule}{cmdregex}/ ) {
logmsg (5, 4, "actionrule(): Positive match, calling actionrulecmd");
actionrulecmd($line, $rule, $resultsrule);
$retval = 1;
}
} elsif ($config{$rule}{cmdregexnegat}) {
if ( $$line{line} !~ /$config{$rule}{cmdregex}/ ) {
logmsg (5, 4, "actionrule(): Negative match, calling actionrulecmd");
actionrulecmd($line, $rule, $resultsrule);
$retval = 1;
}
}
} else {
logmsg (5, 4, "actionrule(): No cmd regex, implicit match, calling actionrulecmd");
actionrulecmd($line, $rule, $resultsrule);
$retval = 1;
}
if ($retval == 0) {
logmsg (5, 4, "actionrule(): line does not match cmdregex for rule: $rule");
#logmsg (5, 4, "actionrule(): cmdregex: $config{$rule}{cmdregex} line: $$line{line}");
}
return $retval;
}
sub actionrulecmd
{
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift;
my $resultsrule = shift;
logmsg (2, 2, "actionrulecmd(): actioning rule $rule for line: $$line{line}");
if (not $config{$rule}{cmdregex}) {
$config{$rule}{cmdregex} = "(.*)";
logmsg (5, 3, "actionrulecmd(): rule did not define cmdregex, replacing with global match");
}
if ( exists $config{$rule}{cmd}) {
logmsg (5, 3, "actionrulecmd(): Collecting data from cmd $config{$rule}{cmd}");
logmsg (5, 3, "actionrulecmd(): rule $rule matches cmd") if $$line{msg} =~ /$config{$rule}{cmdregex}/;
}
if (not exists ($config{$rule}{cmdregex}) ) {
logmsg (5, 3, "actionrulecmd(): No cmd regex, calling actioncmdmatrix");
actioncmdmatrix($line, $rule, $resultsrule);
} elsif ($config{$rule}{cmdregexnegat} ) {
if ($config{$rule}{cmdregex} and $$line{msg} and $$line{msg} !~ /$config{$rule}{cmdregex}/ ) {
logmsg (5, 3, "\tactionrulecmd(): Negative match, calling actioncmdmatrix");
actioncmdmatrix($line, $rule, $resultsrule);
}
} else {
if ($config{$rule}{cmdregex} and $$line{msg} and $$line{msg} =~ /$config{$rule}{cmdregex}/ ) {
logmsg (5, 3, "actionrulecmd(): Positive match, calling actioncmdmatrix");
printhash ($line);
actioncmdmatrix($line, $rule, $resultsrule);
}
}
}
sub printhash
{
my $line = shift; # hash passed by ref, DO NOT mod
foreach my $key (keys %{ $line} )
{
logmsg (9, 5, "$key: $$line{$key}");
}
}
sub actioncmdmatrix
{
my $line = shift; # hash passed by ref, DO NOT mod
my $rule = shift; # Name or ID of rule thats been matched
my $resultsrule = shift; # Name or ID of rule which contains the result set to be updated
my $cmdmatrix = $config{$rule}{cmdmatrix};
my $fieldhash;
my $cmdfield;
my @matrix = split (/,/, $cmdmatrix);
# @matrix - array of parameters that are used in results
if ( exists ($config{$rule}{cmdfield}) ) {
$cmdfield = ${$config{$rule}{cmdfield}};
}
logmsg(5, 2, "Entering actioncmdmatrix():");
logmsg(6, 3, "resultsrule = $rule");
if ( exists $config{$rule}{cmdmatrix}) {
logmsg (5, 3, "actioncmdmatrix(): Collecting data for matrix $config{$rule}{cmdmatrix}");
foreach my $field (@matrix) {
# This is were the black magic occurs, ${$field} causes becomes $1 or $2 etc
# and hence contains the various matches from the previous regex match
# which occured just before this function was called
logmsg (9, 4, "actioncmdmatrix(): matrix field $field has value ${$field}");
if (exists $$line{$field}) {
if ($fieldhash) {
$fieldhash = "$fieldhash:$$line{$field}";
} else {
$fieldhash = "$$line{$field}";
}
} else {
if ($fieldhash) {
$fieldhash = "$fieldhash:${$field}";
} else {
if ( ${$field} ) {
$fieldhash = "${$field}";
} else {
logmsg (1, 4, "actioncmdmatrix(): $field not found in \"$$line{line}\" with regex $config{$rule}{cmdregex}");
printhash($line);
}
}
}
}
if ($config{$rule}{targetfield}) {
logmsg (1, 4, "actioncmdmatrix(): Setting cmdfield (field $config{$rule}{targetfield}) to ${$config{$rule}{targetfield}}");
$cmdfield = ${$config{$rule}{targetfield}};
}
#if ($config{$rule}{cmd} and $config{$rule}{cmd} =~ /^COUNT$/) {
$results{$resultsrule}{$fieldhash}{count}++;
logmsg (5, 4, "actioncmdmatrix(): $results{$resultsrule}{$fieldhash}{count} matches for rule $rule so far from $fieldhash");
#} els
if ($config{$rule}{cmd} eq "SUM" or $config{$rule}{cmd} eq "AVG") {
$results{$resultsrule}{$fieldhash}{sum} = $results{$resultsrule}{$fieldhash}{sum} + $cmdfield;
logmsg (5, 4, "actioncmdmatrix(): Adding $cmdfield to total (now $results{$resultsrule}{$fieldhash}{sum}) for rule $rule so far from $fieldhash");
if ($config{$rule}{cmd} eq "AVG") {
logmsg (5, 4, "actioncmdmatrix(): Average is ".$results{$resultsrule}{$fieldhash}{sum} / $results{$resultsrule}{$fieldhash}{count}." for rule $rule so far from $fieldhash");
}
}
for my $key (keys %{$results{$resultsrule}}) {
logmsg (5, 3, "actioncmdmatrix(): key $key for rule:$rule with $results{$resultsrule}{$key}{count} matches");
}
logmsg (5, 2, "actioncmdmatrix(): $fieldhash matches for rule $rule so far from matrix: $config{$rule}{cmdmatrix}");
} else {
logmsg (5, 2, "actioncmdmatrix(): cmdmatrix is not set for $rule");
#if ($config{$rule}{cmd} and $config{$rule}{cmd} =~ /^COUNT$/) {
$results{$resultsrule}{count}++;
logmsg (5, 3, "actioncmdmatrix(): $results{$resultsrule}{count} lines match rule $rule so far");
# } els
if ($config{$rule}{cmd} eq "SUM" or $config{$rule}{cmd} eq "AVG") {
$results{$resultsrule}{sum} = $results{$resultsrule}{sum} + $cmdfield;
logmsg (5, 3, "actioncmdmatrix(): $results{$resultsrule}{sum} lines match rule $rule so far");
}
}
}
+sub defaultregex {
+ # expects a reference to the rule and param
+ my $paramref = shift;
+
+ if (defined $$paramref[0]{regex} ) {
+ logmsg(9, 4, "defaultregex(): Skipping, there are already regex hashes in this rule/param match");
+ logmsg(9, 5, "defaultregex(): regex[0]regex = $$paramref[0]{regex}");
+ logmsg(9, 5, "defaultregex(): regex[0]negate = $$paramref[0]{negate}");
+ } else {
+ logmsg(9, 1, "defaultregex(): There's no regex hash for this rule/param so setting defaults");
+ $$paramref[0]{regex} = "(.*)";
+ $$paramref[0]{negate} = 0 ;
+ }
+}
+
+sub matchregex {
+ # expects a reference to a regex for a given rule & param
+ # For a given rules regex hash, return true/false for a match
+ my $regex = shift;
+ my $value = shift;
+ my $match = 0;
+
+ if ($value =~ /$$regex{regex}/ or $$regex{regex} =~ /^\*$/ ) {
+ #logmsg (5, 4, "Matches rule: $rule");
+ $match = 1;
+ }
+}
+
+sub matchingrules {
+ my $param = shift;
+ my $matches = shift;
+ my $value = shift;
+
+ logmsg (3, 2, "\nmatchingrules(): param: $param, match count: ".keys(%{$matches})." value: $value");
+
+ if (keys %{$matches} == 0) {
+ # Check all rules as we haevn't had a match yet
+ foreach my $rule (keys %config) {
+ checkrule($param, $matches, $rule, $value);
+ }
+ } else {
+ # As we've allready had a match on the rules, only check those that matched in earlier rounds
+ # key in %matches is the rule that matches
+ foreach my $rule (keys %{$matches}) {
+ checkrule($param, $matches, $rule, $value);
+ }
+ }
+}
+
+sub checkrule {
+ my $param = shift;
+ my $matches = shift;
+ my $rule = shift; # key to %matches
+ my $value = shift;
+
+ logmsg(2, 1, "checkrule(): Checking rule ($rule) & param ($param) for matches against: $value");
+
+ my $paramref = \@{ $config{$rule}{$param} };
+ defaultregex($paramref); # This should be done when reading the config
+
+ foreach my $index (@{ $paramref } ) {
+ my $match = matchregex($index, $value);
+
+ if ($$index{negate} ) {
+ if ( $match) {
+ delete $$matches{$rule};
+ logmsg (5, 5, "checkrules(): matches $index->{regex} for param \'$param\', but negative rule is set, so removing rule $match from list.");
+ } else {
+ $$matches{$rule} = "match" if $match;
+ logmsg (5, 5, "checkrules(): Doesn't match for $index->{regex} for param \'$param\', but negative rule is set, so leaving rule $match on list.");
+ }
+ } elsif ($match) {
+ $$matches{$rule} = "match" if $match;
+ logmsg (5, 4, "checkrules(): matches $index->{regex} for param \'$param\', leaving rule $match on list.");
+ } else {
+ delete $$matches{$rule};
+ logmsg (5, 4, "checkrules(): doesn't match $index->{regex} for param \'$param\', removing rule $match from list.");
+ }
+ } # for each regex hash in the array
+ logmsg (3, 2, "checkrules(): matches ".keys (%{$matches})." matches after checking rules for $param");
+}
+
+=oldcode
sub matchingrules {
my $param = shift;
my $matches = shift;
my $value = shift;
logmsg (3, 2, "matchingrules(): param: $param, matches: $matches, value: $value");
if (keys %{$matches} == 0) {
+ # Check all rules as we haevn't had a match yet
foreach my $rule (keys %config) {
$config{$rule}{$param} = "(.*)" unless exists ($config{$rule}{$param});
logmsg (5, 3, "Does $value match /$config{$rule}{$param}/ ??");
if ($value =~ /$config{$rule}{$param}/ or $config{$rule}{$param} =~ /^\*$/ ) {
logmsg (5, 4, "Matches rule: $rule");
$$matches{$rule} = "match";
}
}
} else {
+ # As we've allready had a match on the rules, only check those that matched in earlier rounds
foreach my $match (keys %{$matches}) {
if (exists ($config{$match}{$param}) ) {
logmsg (5, 4, "Does value: \"$value\" match \'$config{$match}{$param}\' for param $param ??");
if ($config{$match}{"${param}negat"}) {
logmsg (5, 5, "Doing a negative match");
}
} else {
logmsg (5, 3, "No rule for value: \"$value\" in rule $match, leaving on match list.");
$config{$match}{$param} = "(.*)";
}
if ($config{$match}{"${param}negat"}) {
if ($value =~ /$config{$match}{$param}/ or $config{$match}{$param} =~ /^\*$/ ) {
delete $$matches{$match};
logmsg (5, 5, "matches $config{$match}{$param} for param \'$param\', but negative rule is set, so removing rule $match from list.");
} else {
logmsg (5, 5, "Doesn't match for $config{$match}{$param} for param \'$param\', but negative rule is set, so leaving rule $match on list.");
}
} elsif ($value =~ /$config{$match}{$param}/ or $config{$match}{$param} =~ /^\*$/ ) {
logmsg (5, 4, "matches $config{$match}{$param} for param \'$param\', leaving rule $match on list.");
} else {
delete $$matches{$match};
logmsg (5, 4, "doesn't match $config{$match}{$param} for param \'$param\', removing rule $match from list.");
}
}
}
logmsg (3, 2, keys (%{$matches})." matches after checking rules for $param");
}
+=cut
sub logmsg {
my $level = shift;
my $indent = shift;
my $msg = shift;
if ($DEBUG >= $level) {
for my $i (0..$indent) {
print STDERR " ";
}
print STDERR "$msg\n";
}
}
|
simonmaddox/PayToPlay----ota10-AR.Drone-and-Car-Hack | 07cdd7b67d6795aaeed34e22c1df96ee8715232f | Added readme | diff --git a/README.markdown b/README.markdown
new file mode 100644
index 0000000..5578f56
--- /dev/null
+++ b/README.markdown
@@ -0,0 +1,5 @@
+# PayToPlay
+
+This is the client app we built for our "Best In Show" entry to Over The Air's hack competition.
+
+Originally we had this as a standalone project, but due to difficulties integrating Parrot's static library we added our code into their "FreeFlight" project. It works, and in the spirit of the event it's a total hack!
\ No newline at end of file
|
simonmaddox/PayToPlay----ota10-AR.Drone-and-Car-Hack | a41a157c6b398da483ad22250d1ec9637f57fbab | added git ignore | diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..0ef1ffb
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+*.pbxproj -crlf -diff -merge
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..87cca62
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,11 @@
+# xcode noise
+build/*
+*.pbxuser
+*.mode1v3
+
+# old skool
+.svn
+
+# osx noise
+.DS_Store
+profile
\ No newline at end of file
|
blueyed/dotfiles | 9f2c882fb8e9844d013fa9af6d7f04b122badd26 | vimrc: indent | diff --git a/vimrc b/vimrc
index 6717499..fd50aa9 100644
--- a/vimrc
+++ b/vimrc
@@ -1660,1044 +1660,1044 @@ function! MyFollowSymlink(...)
endif
let fname = simplify(fname)
let resolvedfile = resolve(fname)
if resolvedfile == fname
return
endif
let resolvedfile = fnameescape(resolvedfile)
let sshm = &shm
set shortmess+=A " silence ATTENTION message about swap file (would get displayed twice)
redraw " Redraw now, to avoid hit-enter prompt.
exec 'file ' . resolvedfile
let &shm=sshm
unlet! b:git_dir
call fugitive#detect(resolvedfile)
if &modifiable
" Only display a note when editing a file, especially not for `:help`.
redraw " Redraw now, to avoid hit-enter prompt.
echomsg 'Resolved symlink: =>' resolvedfile
endif
endfunction
command! -bar FollowSymlink call MyFollowSymlink()
command! ToggleFollowSymlink let w:no_resolve_symlink = !get(w:, 'no_resolve_symlink', 0) | echo "w:no_resolve_symlink =>" w:no_resolve_symlink
" au BufWinEnter * nested call MyFollowSymlink(expand('%'))
nnoremap <Leader>gf :FollowSymlink<cr>
" Automatically load .vimrc source when saved
au BufWritePost $MYVIMRC,~/.dotfiles/vimrc,$MYVIMRC.local source $MYVIMRC
au BufWritePost $MYGVIMRC,~/.dotfiles/gvimrc source $MYGVIMRC
" if (has("gui_running"))
" au FocusLost * stopinsert
" endif
" autocommands for fugitive {{{2
" Source: http://vimcasts.org/episodes/fugitive-vim-browsing-the-git-object-database/
au User Fugitive
\ if fugitive#buffer().type() =~# '^\%(tree\|blob\)' |
\ nnoremap <buffer> .. :edit %:h<CR> |
\ endif
au BufReadPost fugitive://* set bufhidden=delete
" Expand tabs for Debian changelog. This is probably not the correct way.
au BufNewFile,BufRead */debian/changelog,changelog.dch set expandtab
" Ignore certain files with vim-stay.
au BufNewFile,BufRead */.git/addp-hunk-edit.diff let b:stay_ignore = 1
" Python
" irrelevant, using python-pep8-indent
" let g:pyindent_continue = '&sw * 1'
" let g:pyindent_open_paren = '&sw * 1'
" let g:pyindent_nested_paren = '&sw'
" python-mode
let g:pymode_options = 0 " do not change relativenumber
let g:pymode_indent = 0 " use vim-python-pep8-indent (upstream of pymode)
let g:pymode_lint = 0 " prefer syntastic; pymode has problems when PyLint was invoked already before VirtualEnvActivate..!?!
let g:pymode_virtualenv = 0 " use virtualenv plugin (required for pylint?!)
let g:pymode_doc = 0 " use pydoc
let g:pymode_rope_completion = 0 " use YouCompleteMe instead (python-jedi)
let g:pymode_syntax_space_errors = 0 " using MyWhitespaceSetup
let g:pymode_trim_whitespaces = 0
let g:pymode_debug = 0
let g:pymode_rope = 0
let g:pydoc_window_lines=0.5 " use 50% height
let g:pydoc_perform_mappings=0
" let python_space_error_highlight = 1 " using MyWhitespaceSetup
" C
au FileType C setlocal formatoptions-=c formatoptions-=o formatoptions-=r
fu! Select_c_style()
if search('^\t', 'n', 150)
setlocal shiftwidth=8 noexpandtab
el
setlocal shiftwidth=4 expandtab
en
endf
au FileType c call Select_c_style()
au FileType make setlocal noexpandtab
" Disable highlighting of markdownError (Ref: https://github.com/tpope/vim-markdown/issues/79).
autocmd FileType markdown hi link markdownError NONE
augroup END
" Trailing whitespace highlighting {{{2
" Map to toogle EOLWS syntax highlighting
noremap <silent> <leader>se :let g:MyAuGroupEOLWSactive = (synIDattr(synIDtrans(hlID("EOLWS")), "bg", "cterm") == -1)<cr>
\:call MyAuGroupEOLWS(mode())<cr>
let g:MyAuGroupEOLWSactive = 0
function! MyAuGroupEOLWS(mode)
if g:MyAuGroupEOLWSactive && &buftype == ''
hi EOLWS ctermbg=red guibg=red
syn clear EOLWS
" match whitespace not preceded by a backslash
if a:mode == "i"
syn match EOLWS excludenl /[\\]\@<!\s\+\%#\@!$/ containedin=ALL
else
syn match EOLWS excludenl /[\\]\@<!\s\+$\| \+\ze\t/ containedin=ALLBUT,gitcommitDiff |
endif
else
syn clear EOLWS
hi clear EOLWS
endif
endfunction
augroup vimrcExEOLWS
au!
" highlight EOLWS ctermbg=red guibg=red
" based on solarizedTrailingSpace
highlight EOLWS term=underline cterm=underline ctermfg=1
au InsertEnter * call MyAuGroupEOLWS("i")
" highlight trailing whitespace, space before tab and tab not at the
" beginning of the line (except in comments), only for normal buffers:
au InsertLeave,BufWinEnter * call MyAuGroupEOLWS("n")
" fails with gitcommit: filetype | syn match EOLWS excludenl /[^\t]\zs\t\+/ containedin=ALLBUT,gitcommitComment
" add this for Python (via python_highlight_all?!):
" au FileType python
" \ if g:MyAuGroupEOLWSactive |
" \ syn match EOLWS excludenl /^\t\+/ containedin=ALL |
" \ endif
augroup END "}}}
" automatically save and reload viminfo across Vim instances
" Source: http://vimhelp.appspot.com/vim_faq.txt.html#faq-17.3
augroup viminfo_onfocus
au!
" au FocusLost * wviminfo
" au FocusGained * rviminfo
augroup end
endif " has("autocmd") }}}
" Shorten a given (absolute) file path, via external `shorten_path` script.
" This mainly shortens entries from Zsh's `hash -d` list.
let s:_cache_shorten_path = {}
let s:_has_functional_shorten_path = 1
let s:shorten_path_exe = executable('shorten_path')
\ ? 'shorten_path'
\ : filereadable(expand("$HOME/.dotfiles/usr/bin/shorten_path"))
\ ? expand("$HOME/.dotfiles/usr/bin/shorten_path")
\ : expand("/home/$SUDO_USER/.dotfiles/usr/bin/shorten_path")
function! ShortenPath(path, ...)
if !len(a:path) || !s:_has_functional_shorten_path
return a:path
endif
let base = a:0 ? a:1 : ""
let annotate = a:0 > 1 ? a:2 : 0
let cache_key = base . ":" . a:path . ":" . annotate
if !exists('s:_cache_shorten_path[cache_key]')
let shorten_path = [s:shorten_path_exe]
if annotate
let shorten_path += ['-a']
endif
let cmd = shorten_path + [a:path, base]
let output = s:systemlist(cmd)
let lastline = empty(output) ? '' : output[-1]
let s:_cache_shorten_path[cache_key] = lastline
if v:shell_error
try
let tmpfile = tempname()
let system_cmd = join(map(copy(cmd), 'fnameescape(v:val)'))
call system(system_cmd.' 2>'.tmpfile)
if v:shell_error == 127
let s:_has_functional_shorten_path = 0
endif
echohl ErrorMsg
echom printf('There was a problem running %s: %s (%d)',
\ cmd, join(readfile(tmpfile), "\n"), v:shell_error)
echohl None
return a:path
finally
call delete(tmpfile)
endtry
endif
endif
return s:_cache_shorten_path[cache_key]
endfun
function! My_get_qfloclist_type(bufnr)
let isLoc = getbufvar(a:bufnr, 'isLoc', -1) " via vim-qf.
if isLoc != -1
return isLoc ? 'll' : 'qf'
endif
" A hacky way to distinguish qf from loclist windows/buffers.
" https://github.com/vim-airline/vim-airline/blob/83b6dd11a8829bbd934576e76bfbda6559ed49e1/autoload/airline/extensions/quickfix.vim#L27-L43.
" Changes:
" - Caching!
" - Match opening square bracket at least. Apart from that it could be
" localized.
" if &ft !=# 'qf'
" return ''
" endif
let type = getbufvar(a:bufnr, 'my_qfloclist_type', '')
if type != ''
return type
endif
redir => buffers
silent ls -
redir END
let type = 'unknown'
for buf in split(buffers, '\n')
if match(buf, '\v^\s*'.a:bufnr.'\s\S+\s+"\[') > -1
if match(buf, '\cQuickfix') > -1
let type = 'qf'
break
else
let type = 'll'
break
endif
endif
endfor
call setbufvar(a:bufnr, 'my_qfloclist_type', type)
return type
endfunction
function! s:systemlist(l) abort
if !has('nvim')
let cmd = join(map(copy(a:l), 'fnameescape(v:val)'))
else
let cmd = a:l
endif
return systemlist(cmd)
endfunction
" Shorten a given filename by truncating path segments.
let g:_cache_shorten_filename = {}
let g:_cache_shorten_filename_git = {}
function! ShortenString(s, maxlen)
if len(a:s) <= a:maxlen
return a:s
endif
return a:s[0:a:maxlen-1] . 'â¦'
endfunction
function! ShortenFilename(...) " {{{
" Args: bufname ('%' for default), maxlength, cwd
let cwd = a:0 > 2 ? a:3 : getcwd()
" Maxlen from a:2 (used for cache key) and caching.
let maxlen = a:0>1 ? a:2 : max([10, winwidth(0)-50])
" get bufname from a:1, defaulting to bufname('%') {{{
if a:0 && type(a:1) == type('') && a:1 !=# '%'
let bufname = expand(a:1) " tilde-expansion.
else
if !a:0 || a:1 == '%'
let bufnr = bufnr('%')
else
let bufnr = a:1
endif
let bufname = bufname(bufnr)
let ft = getbufvar(bufnr, '&filetype')
if !len(bufname)
if ft == 'qf'
let type = My_get_qfloclist_type(bufnr)
" XXX: uses current window. Also not available after ":tab split".
let qf_title = get(w:, 'quickfix_title', '')
if qf_title != ''
return ShortenString('['.type.'] '.qf_title, maxlen)
elseif type == 'll'
let alt_name = expand('#')
" For location lists the alternate file is the corresponding buffer
" and the quickfix list does not have an alternate buffer
" (but not always)!?!
if len(alt_name)
return '[loc] '.ShortenFilename(alt_name, maxlen-5)
endif
return '[loc]'
endif
return '[qf]'
else
let bt = getbufvar(bufnr, '&buftype')
if bt != '' && ft != ''
" Use &ft for name (e.g. with 'startify' and quickfix windows).
" if &ft == 'qf'
" let alt_name = expand('#')
" if len(alt_name)
" return '[loc] '.ShortenFilename(alt_name)
" else
" return '[qf]'
" endif
let alt_name = expand('#')
if len(alt_name)
return '['.&ft.'] '.ShortenFilename(expand('#'))
else
return '['.&ft.']'
endif
else
" TODO: get Vim's original "[No Name]" somehow
return '[No Name]'
endif
endif
end
if ft ==# 'help'
return '[?] '.fnamemodify(bufname, ':t')
endif
if bufname =~# '^__'
return bufname
endif
" '^\[ref-\w\+:.*\]$'
if bufname =~# '^\[.*\]$'
return bufname
endif
endif
" }}}
" {{{ fugitive
if bufname =~# '^fugitive:///'
let [gitdir, fug_path] = split(bufname, '//')[1:2]
" Caching based on bufname and timestamp of gitdir.
let git_ftime = getftime(gitdir)
if exists('g:_cache_shorten_filename_git[bufname]')
\ && g:_cache_shorten_filename_git[bufname][0] == git_ftime
let [commit_name, fug_type, fug_path]
\ = g:_cache_shorten_filename_git[bufname][1:-1]
else
let fug_buffer = fugitive#buffer(bufname)
let fug_type = fug_buffer.type()
" if fug_path =~# '^\x\{7,40\}\>'
let commit = matchstr(fug_path, '\v\w*')
if len(commit) > 1
let git_argv = ['git', '--git-dir='.gitdir]
let commit = systemlist(git_argv + ['rev-parse', '--short', commit])[0]
let commit_name = systemlist(git_argv + ['name-rev', '--name-only', commit])[0]
if commit_name !=# 'undefined'
" Remove current branch name (master~4 => ~4).
let HEAD = get(systemlist(git_argv + ['symbolic-ref', '--quiet', '--short', 'HEAD']), 0, '')
let len_HEAD = len(HEAD)
if len_HEAD > len(commit_name) && commit_name[0:len_HEAD-1] == HEAD
let commit_name = commit_name[len_HEAD:-1]
endif
" let commit .= '('.commit_name.')'
let commit_name .= '('.commit.')'
else
let commit_name = commit
endif
else
let commit_name = commit
endif
" endif
if fug_type !=# 'commit'
let fug_path = substitute(fug_path, '\v\w*/', '', '')
if len(fug_path)
let fug_path = ShortenFilename(fug_buffer.repo().tree(fug_path))
endif
else
let fug_path = 'NOT_USED'
endif
" Set cache.
let g:_cache_shorten_filename_git[bufname]
\ = [git_ftime, commit_name, fug_type, fug_path]
endif
if fug_type ==# 'blob'
return 'λ:' . commit_name . ':' . fug_path
elseif fug_type ==# 'file'
return 'λ:' . fug_path . '@' . commit_name
elseif fug_type ==# 'commit'
" elseif fug_path =~# '^\x\{7,40\}\>'
let work_tree = fugitive#buffer(bufname).repo().tree()
if cwd[0:len(work_tree)-1] == work_tree
let rel_work_tree = ''
else
let rel_work_tree = ShortenPath(fnamemodify(work_tree.'/', ':.'))
endif
return 'λ:' . rel_work_tree . '@' . commit_name
endif
throw "fug_type: ".fug_type." not handled: ".fug_path
endif " }}}
" Check for cache (avoiding fnamemodify): {{{
let cache_key = bufname.'::'.cwd.'::'.maxlen
if has_key(g:_cache_shorten_filename, cache_key)
return g:_cache_shorten_filename[cache_key]
endif
" Make path relative first, which might not work with the result from
" `shorten_path`.
let rel_path = fnamemodify(bufname, ":.")
let bufname = ShortenPath(rel_path, cwd, 1)
" }}}
" Loop over all segments/parts, to mark symlinks.
" XXX: symlinks get resolved currently anyway!?
" NOTE: consider using another method like http://stackoverflow.com/questions/13165941/how-to-truncate-long-file-path-in-vim-powerline-statusline
let maxlen_of_parts = 7 " including slash/dot
let maxlen_of_subparts = 1 " split at hypen/underscore; including split
let s:PS = exists('+shellslash') ? (&shellslash ? '/' : '\') : "/"
let parts = split(bufname, '\ze['.escape(s:PS, '\').']')
let i = 0
let n = len(parts)
let wholepath = '' " used for symlink check
while i < n
let wholepath .= parts[i]
" Shorten part, if necessary:
" TODO: use pathshorten(fnamemodify(path, ':~')) as fallback?!
if i < n-1 && len(bufname) > maxlen && len(parts[i]) > maxlen_of_parts
" Let's see if there are dots or hyphens to truncate at, e.g.
" 'vim-pkg-debian' => 'v-p-dâ¦'
let w = split(parts[i], '\ze[_-]')
if len(w) > 1
let parts[i] = ''
for j in w
if len(j) > maxlen_of_subparts-1
let parts[i] .= j[0:max([maxlen_of_subparts-2, 1])] "."â¦"
else
let parts[i] .= j
endif
endfor
else
let parts[i] = parts[i][0:max([maxlen_of_parts-2, 1])].'â¦'
endif
endif
let i += 1
endwhile
let r = join(parts, '')
if len(r) > maxlen
" echom len(r) maxlen
let i = 0
let n -= 1
while i < n && len(join(parts, '')) > maxlen
if i > 0 || parts[i][0] != '~'
let j = 0
let parts[i] = matchstr(parts[i], '.\{-}\w')
" if i == 0 && parts[i][0] != '/'
" let parts[i] = parts[i][0]
" else
" let parts[i] = matchstr(parts[i], 1)
" endif
endif
let i += 1
endwhile
let r = join(parts, '')
endif
let g:_cache_shorten_filename[cache_key] = r
" echom "ShortenFilename" r
return r
endfunction "}}}
" Shorten filename, and append suffix(es), e.g. for modified buffers. {{{2
fun! ShortenFilenameWithSuffix(...)
let r = call('ShortenFilename', a:000)
if &modified
let r .= ',+'
endif
return r
endfun
" }}}
" Opens an edit command with the path of the currently edited file filled in
" Normal mode: <Leader>e
nnoremap <Leader>ee :e <C-R>=expand("%:p:h") . "/" <CR>
nnoremap <Leader>EE :sp <C-R>=expand("%:p:h") . "/" <CR>
" gt: next tab or buffer (source: http://j.mp/dotvimrc)
" enhanced to support range (via v:count)
fun! MyGotoNextTabOrBuffer(...)
let c = a:0 ? a:1 : v:count
exec (c ? c : '') . (tabpagenr('$') == 1 ? 'bn' : 'tabnext')
endfun
fun! MyGotoPrevTabOrBuffer()
exec (v:count ? v:count : '') . (tabpagenr('$') == 1 ? 'bp' : 'tabprevious')
endfun
nnoremap <silent> <Plug>NextTabOrBuffer :<C-U>call MyGotoNextTabOrBuffer()<CR>
nnoremap <silent> <Plug>PrevTabOrBuffer :<C-U>call MyGotoPrevTabOrBuffer()<CR>
" Ctrl-Space: split into new tab.
" Disables diff mode, which gets taken over from the old buffer.
nnoremap <C-Space> :tab sp \| set nodiff<cr>
nnoremap <A-Space> :tabnew<cr>
" For terminal.
nnoremap <C-@> :tab sp \| set nodiff<cr>
" Opens a tab edit command with the path of the currently edited file filled in
map <Leader>te :tabe <C-R>=expand("%:p:h") . "/" <CR>
map <a-o> <C-W>o
" Avoid this to be done accidentally (when zooming is meant). ":on" is more
" explicit.
map <C-W><C-o> <Nop>
" does not work, even with lilyterm.. :/
" TODO: <C-1>..<C-0> for tabs; not possible; only certain C-sequences get
" through to the terminal Vim
" nmap <C-Insert> :tabnew<cr>
" nmap <C-Del> :tabclose<cr>
nmap <A-Del> :tabclose<cr>
" nmap <C-1> 1gt<cr>
" Prev/next tab.
nmap <C-PageUp> <Plug>PrevTabOrBuffer
nmap <C-PageDown> <Plug>NextTabOrBuffer
map <A-,> <Plug>PrevTabOrBuffer
map <A-.> <Plug>NextTabOrBuffer
map <C-S-Tab> <Plug>PrevTabOrBuffer
map <C-Tab> <Plug>NextTabOrBuffer
" Switch to most recently used tab.
" Source: http://stackoverflow.com/a/2120168/15690
fun! MyGotoMRUTab()
-if !exists('g:mrutab')
- let g:mrutab = 1
-endif
-if tabpagenr('$') == 1
- echomsg "There is only one tab!"
- return
-endif
-if g:mrutab > tabpagenr('$') || g:mrutab == tabpagenr()
- let g:mrutab = tabpagenr() > 1 ? tabpagenr()-1 : tabpagenr('$')
-endif
-exe "tabn ".g:mrutab
+ if !exists('g:mrutab')
+ let g:mrutab = 1
+ endif
+ if tabpagenr('$') == 1
+ echomsg "There is only one tab!"
+ return
+ endif
+ if g:mrutab > tabpagenr('$') || g:mrutab == tabpagenr()
+ let g:mrutab = tabpagenr() > 1 ? tabpagenr()-1 : tabpagenr('$')
+ endif
+ exe "tabn ".g:mrutab
endfun
" Overrides Vim's gh command (start select-mode, but I don't use that).
" It can be simulated using v<C-g> also.
nnoremap <silent> gh :call MyGotoMRUTab()<CR>
" nnoremap ° :call MyGotoMRUTab()<CR>
" nnoremap <C-^> :call MyGotoMRUTab()<CR>
augroup MyTL
-au!
-au TabLeave * let g:mrutab = tabpagenr()
+ au!
+ au TabLeave * let g:mrutab = tabpagenr()
augroup END
" Map <A-1> .. <A-9> to goto tab or buffer.
for i in range(9)
exec 'nmap <M-' .(i+1).'> :call MyGotoNextTabOrBuffer('.(i+1).')<cr>'
endfor
fun! MyGetNonDefaultServername()
" Not for gvim in general (uses v:servername by default), and the global
" server ("G").
let sname = v:servername
if len(sname)
if has('nvim')
if sname !~# '^/tmp/nvim'
let sname = substitute(fnamemodify(v:servername, ':t:r'), '^nvim-', '', '')
return sname
endif
elseif sname !~# '\v^GVIM.*' " && sname =~# '\v^G\d*$'
return sname
endif
endif
return ''
endfun
fun! MyGetSessionName()
" Use / auto-set g:MySessionName
if !len(get(g:, "MySessionName", ""))
if len(v:this_session)
let g:MySessionName = fnamemodify(v:this_session, ':t:r')
elseif len($TERM_INSTANCE_NAME)
let g:MySessionName = substitute($TERM_INSTANCE_NAME, '^vim-', '', '')
else
return ''
end
endif
return g:MySessionName
endfun
" titlestring handling, with tmux support {{{
" Set titlestring, used to set terminal title (pane title in tmux).
set title
" Setup titlestring on BufEnter, when v:servername is available.
fun! MySetupTitleString()
let title = 'â '
let session_name = MyGetSessionName()
if len(session_name)
let title .= '['.session_name.'] '
else
" Add non-default servername to titlestring.
let sname = MyGetNonDefaultServername()
if len(sname)
let title .= '['.sname.'] '
endif
endif
" Call the function and use its result, rather than including it.
" (for performance reasons).
let title .= substitute(
\ ShortenFilenameWithSuffix('%', 15).' ('.ShortenPath(getcwd()).')',
\ '%', '%%', 'g')
if len(s:my_context)
let title .= ' {'.s:my_context.'}'
endif
" Easier to type/find than the unicode symbol prefix.
let title .= ' - vim'
" Append $_TERM_TITLE_SUFFIX (e.g. user@host) to title (set via zsh, used
" with SSH).
if len($_TERM_TITLE_SUFFIX)
let title .= $_TERM_TITLE_SUFFIX
endif
" Setup tmux window name, see ~/.dotfiles/oh-my-zsh/lib/termsupport.zsh.
if len($TMUX)
\ && (!len($_tmux_name_reset) || $_tmux_name_reset != $TMUX . '_' . $TMUX_PANE)
let tmux_auto_rename=systemlist('tmux show-window-options -t '.$TMUX_PANE.' -v automatic-rename 2>/dev/null')
" || $(tmux show-window-options -t $TMUX_PANE | grep '^automatic-rename' | cut -f2 -d\ )
" echom string(tmux_auto_rename)
if !len(tmux_auto_rename) || tmux_auto_rename[0] != "off"
" echom "Resetting tmux name to 0."
call system('tmux set-window-option -t '.$TMUX_PANE.' -q automatic-rename off')
call system('tmux rename-window -t '.$TMUX_PANE.' 0')
endif
endif
let &titlestring = title
" Set icon text according to &titlestring (used for minimized windows).
let &iconstring = '(v) '.&titlestring
endfun
augroup vimrc_title
au!
" XXX: might not get called with fugitive buffers (title is the (closed) fugitive buffer).
autocmd BufEnter,BufWritePost * call MySetupTitleString()
if exists('##TextChanged')
autocmd TextChanged * call MySetupTitleString()
endif
augroup END
" Make Vim set the window title according to &titlestring.
if !has('gui_running') && empty(&t_ts)
if len($TMUX)
let &t_ts = "\e]2;"
let &t_fs = "\007"
elseif &term =~ "^screen.*"
let &t_ts="\ek"
let &t_fs="\e\\"
endif
endif
fun! MySetSessionName(name)
let g:MySessionName = a:name
call MySetupTitleString()
endfun
"}}}
" Inserts the path of the currently edited file into a command
" Command mode: Ctrl+P
" cmap <C-P> <C-R>=expand("%:p:h") . "/" <CR>
" Change to current file's dir
nnoremap <Leader>cd :lcd <C-R>=expand('%:p:h')<CR><CR>
" yankstack, see also unite's history/yank {{{1
if &rtp =~ '\<yankstack\>'
" Do not map s/S (used by vim-sneak).
" let g:yankstack_yank_keys = ['c', 'C', 'd', 'D', 's', 'S', 'x', 'X', 'y', 'Y']
let g:yankstack_yank_keys = ['c', 'C', 'd', 'D', 'x', 'X', 'y', 'Y']
" Setup yankstack now to make yank/paste related mappings work.
call yankstack#setup()
endif
" Command-line maps to act on the current search (with incsearch). {{{
" E.g. '?foo$m' will move the matched line to where search started.
" Source: http://www.reddit.com/r/vim/comments/1yfzg2/does_anyone_actually_use_easymotion/cfkaxw5
" NOTE: with vim-oblique, '?' and '/' are mapped, and not in getcmdtype().
fun! MyCmdMapNotForColon(from, to, ...)
let init = a:0 ? 0 : 1
if init
exec printf('cnoremap <expr> %s MyCmdMapNotForColon("%s", "%s", 1)',
\ a:from, a:from, a:to)
return
endif
if index([':', '>', '@', '-', '='], getcmdtype()) == 0
return a:from
endif
return a:to
endfun
call MyCmdMapNotForColon('$d', "<CR>:delete<CR>``")
call MyCmdMapNotForColon('$m', "<CR>:move''<CR>")
call MyCmdMapNotForColon('$c', "<CR>:copy''<CR>")
call MyCmdMapNotForColon('$t', "<CR>:t''<CR>") " synonym for :copy
" Allow to quickly enter a single $.
cnoremap $$ $
" }}}
" sneak {{{1
" Overwrite yankstack with sneak maps.
" Ref: https://github.com/maxbrunsfeld/vim-yankstack/issues/39
nmap s <Plug>Sneak_s
nmap S <Plug>Sneak_S
xmap s <Plug>Sneak_s
xmap S <Plug>Sneak_S
omap s <Plug>Sneak_s
omap S <Plug>Sneak_S
" Use streak mode, also for Sneak_f/Sneak_t.
let g:sneak#streak=2
let g:sneak#s_next = 1 " clever-s
let g:sneak#target_labels = "sfjktunbqz/SFKGHLTUNBRMQZ?"
" Replace 'f' with inclusive 1-char Sneak.
nmap f <Plug>Sneak_f
nmap F <Plug>Sneak_F
xmap f <Plug>Sneak_f
xmap F <Plug>Sneak_F
omap f <Plug>Sneak_f
omap F <Plug>Sneak_F
" Replace 't' with exclusive 1-char Sneak.
nmap t <Plug>Sneak_t
nmap T <Plug>Sneak_T
xmap t <Plug>Sneak_t
xmap T <Plug>Sneak_T
omap t <Plug>Sneak_t
omap T <Plug>Sneak_T
" IDEA: just use 'f' for sneak, leaving 's' at its default.
" nmap f <Plug>Sneak_s
" nmap F <Plug>Sneak_S
" xmap f <Plug>Sneak_s
" xmap F <Plug>Sneak_S
" omap f <Plug>Sneak_s
" omap F <Plug>Sneak_S
" }}}1
" GoldenView {{{1
let g:goldenview__enable_default_mapping = 0
let g:goldenview__enable_at_startup = 0
" 1. split to tiled windows
nmap <silent> g<C-L> <Plug>GoldenViewSplit
" " 2. quickly switch current window with the main pane
" " and toggle back
nmap <silent> <F9> <Plug>GoldenViewSwitchMain
nmap <silent> <S-F9> <Plug>GoldenViewSwitchToggle
" " 3. jump to next and previous window
nmap <silent> <C-N> <Plug>GoldenViewNext
nmap <silent> <C-P> <Plug>GoldenViewPrevious
" }}}
" Duplicate a selection in visual mode
vmap D y'>p
" Press Shift+P while in visual mode to replace the selection without
" overwriting the default register
vmap P p :call setreg('"', getreg('0')) <CR>
" This is an alternative that also works in block mode, but the deleted
" text is lost and it only works for putting the current register.
"vnoremap p "_dp
" imap <C-L> <Space>=><Space>
" Toggle settings (see also vim-unimpaired).
" No pastetoggle: use `yo`/`yO` from unimpaired. Triggers also Neovim issue #6716.
" set pastetoggle=<leader>sp
nnoremap <leader>sc :ColorToggle<cr>
nnoremap <leader>sq :QuickfixsignsToggle<cr>
nnoremap <leader>si :IndentGuidesToggle<cr>
" Toggle mouse.
nnoremap <leader>sm :exec 'set mouse='.(&mouse == 'a' ? '' : 'a')<cr>:set mouse?<cr>
" OLD: Ack/Ag setup, handled via ag plugin {{{
" Use Ack instead of Grep when available
" if executable("ack")
" set grepprg=ack\ -H\ --nogroup\ --nocolor\ --ignore-dir=tmp\ --ignore-dir=coverage
" elseif executable("ack-grep")
" set grepprg=ack-grep\ -H\ --nogroup\ --nocolor\ --ignore-dir=tmp\ --ignore-dir=coverage
" else
" this is for Windows/cygwin and to add -H
" '$*' is not passed to the shell, but used by Vim
set grepprg=grep\ -nH\ $*\ /dev/null
" endif
if executable("ag")
let g:ackprg = 'ag --nogroup --nocolor --column'
" command alias, http://stackoverflow.com/a/3879737/15690
" if re-used, use a function
" cnoreabbrev <expr> Ag ((getcmdtype() is# ':' && getcmdline() is# 'Ag')?('Ack'):('Ag'))
endif
" 1}}}
" Automatic line numbers {{{
" NOTE: relativenumber might slow Vim down: https://code.google.com/p/vim/issues/detail?id=311
set norelativenumber
fun! MyAutoSetNumberSettings(...)
if get(w:, 'my_default_number_manually_set')
return
endif
let s:my_auto_number_ignore_OptionSet = 1
if a:0
exec 'setl' a:1
elseif &ft =~# 'qf\|cram\|vader'
setl number
elseif index(['nofile', 'terminal'], &buftype) != -1
\ || index(['help', 'fugitiveblame', 'fzf'], &ft) != -1
\ || bufname("%") =~ '^__'
setl nonumber
elseif winwidth(".") > 90
setl number
else
setl nonumber
endif
unlet s:my_auto_number_ignore_OptionSet
endfun
fun! MySetDefaultNumberSettingsSet()
if !exists('s:my_auto_number_ignore_OptionSet')
" echom "Manually set:" expand("<amatch>").":" v:option_old "=>" v:option_new
let w:my_auto_number_manually_set = 1
endif
endfun
augroup vimrc_number_setup
au!
au VimResized,FileType,BufWinEnter * call MyAutoSetNumberSettings()
if exists('##OptionSet')
au OptionSet number,relativenumber call MySetDefaultNumberSettingsSet()
endif
au CmdwinEnter * call MyAutoSetNumberSettings('number norelativenumber')
augroup END
fun! MyOnVimResized()
noautocmd WindoNodelay call MyAutoSetNumberSettings()
QfResizeWindows
endfun
nnoremap <silent> <c-w>= :wincmd =<cr>:call MyOnVimResized()<cr>
fun! MyWindoNoDelay(range, command)
" 100ms by default!
let s = g:ArgsAndMore_AfterCommand
let g:ArgsAndMore_AfterCommand = ''
call ArgsAndMore#Windo('', a:command)
let g:ArgsAndMore_AfterCommand = s
endfun
command! -nargs=1 -complete=command WindoNodelay call MyWindoNoDelay('', <q-args>)
augroup vimrc_on_resize
au!
au VimResized * WindoNodelay call MyOnVimResized()
augroup END
let &showbreak = '⪠'
set cpoptions+=n " Use line column for wrapped text / &showbreak.
function! CycleLineNr()
" states: [start] => norelative/number => relative/number (=> relative/nonumber) => nonumber/norelative
if exists('+relativenumber')
if &relativenumber
" if &number
" set relativenumber nonumber
" else
set norelativenumber nonumber
" endif
else
if &number
set number relativenumber
if !&number " Older Vim.
set relativenumber
endif
else
" init:
set norelativenumber number
endif
endif
" if &number | set relativenumber | elseif &relativenumber | set norelativenumber | else | set number | endif
else
set number!
endif
call SetNumberWidth()
endfunction
function! SetNumberWidth()
" NOTE: 'numberwidth' will get expanded by Vim automatically to fit the last line
if &number
if has('float')
let &l:numberwidth = float2nr(ceil(log10(line('$'))))
endif
elseif exists('+relativenumber') && &relativenumber
set numberwidth=2
endif
endfun
nnoremap <leader>sa :call CycleLineNr()<CR>
" Toggle numbers, but with relativenumber turned on
fun! ToggleLineNr()
if &number
if exists('+relativenumber')
set norelativenumber
endif
set nonumber
else
if exists('+relativenumber')
set relativenumber
endif
set number
endif
endfun
" map according to unimpaired, mnemonic "a on the left, like numbers".
nnoremap coa :call ToggleLineNr()<cr>
" Allow cursor to move anywhere in all modes.
nnoremap cov :set <C-R>=empty(&virtualedit) ? 'virtualedit=all' : 'virtualedit='<CR><CR>
"}}}
" Completion options.
" Do not use longest, but make Ctrl-P work directly.
set completeopt=menuone
" set completeopt+=preview " experimental
set wildmode=list:longest,list:full
" set complete+=kspell " complete from spell checking
" set dictionary+=spell " very useful (via C-X C-K), but requires ':set spell' once
" NOTE: gets handled dynamically via cursorcross plugin.
" set cursorline
" highlight CursorLine guibg=lightblue ctermbg=lightgray
" via http://www.reddit.com/r/programming/comments/7yk4i/vim_settings_per_directory/c07rk9d
" :au! BufRead,BufNewFile *path/to/project/*.* setlocal noet
" Maps for jk and kj to act as Esc (idempotent in normal mode).
" NOTE: jk moves to the right after Esc, leaving the cursor at the current position.
fun! MyRightWithoutError()
if col(".") < len(getline("."))
normal! l
endif
endfun
inoremap <silent> jk <esc>:call MyRightWithoutError()<cr>
" cno jk <c-c>
ino kj <esc>
" cno kj <c-c>
ino jh <esc>
" Improve the Esc key: good for `i`, does not work for `a`.
" Source: http://vim.wikia.com/wiki/Avoid_the_escape_key#Improving_the_Esc_key
" inoremap <Esc> <Esc>`^
" close tags (useful for html)
" NOTE: not required/used; avoid imap for leader.
" imap <Leader>/ </<C-X><C-O>
nnoremap <Leader>a :Ag<space>
nnoremap <Leader>A :Ag!<space>
" Make those behave like ci' , ci"
nnoremap ci( f(ci(
nnoremap ci{ f{ci{
nnoremap ci[ f[ci[
" NOTE: occupies `c`.
" vnoremap ci( f(ci(
" vnoremap ci{ f{ci{
" vnoremap ci[ f[ci[
" 'goto buffer'; NOTE: overwritten with Unite currently.
nnoremap gb :ls<CR>:b
function! MyIfToVarDump()
normal yyP
s/\mif\>/var_dump/
s/\m\s*\(&&\|||\)\s*/, /ge
s/\m{\s*$/; die();/
endfunction
" Toggle fold under cursor. {{{
fun! MyToggleFold()
if !&foldenable
echom "Folds are not enabled."
endif
let level = foldlevel('.')
echom "Current foldlevel:" level
if level == 0
return
endif
if foldclosed('.') > 0
" Open recursively
norm! zA
else
" Close only one level.
norm! za
endif
endfun
nnoremap <Leader><space> :call MyToggleFold()<cr>
vnoremap <Leader><space> zf
" }}}
" Easily switch between different fold methods {{{
" Source: https://github.com/pydave/daveconfig/blob/master/multi/vim/.vim/bundle/foldtoggle/plugin/foldtoggle.vim
nnoremap <Leader>sf :call ToggleFold()<CR>
function! ToggleFold()
if !exists("b:fold_toggle_options")
" By default, use the main three. I rarely use custom expressions or
" manual and diff is just for diffing.
let b:fold_toggle_options = ["syntax", "indent", "marker"]
if len(&foldexpr)
let b:fold_toggle_options += ["expr"]
endif
endif
" Find the current setting in the list
let i = match(b:fold_toggle_options, &foldmethod)
" Advance to the next setting
let i = (i + 1) % len(b:fold_toggle_options)
let old_method = &l:foldmethod
let &l:foldmethod = b:fold_toggle_options[i]
echom 'foldmethod: ' . old_method . " => " . &l:foldmethod
endfunction
function! FoldParagraphs()
setlocal foldmethod=expr
setlocal fde=getline(v:lnum)=~'^\\s*$'&&getline(v:lnum+1)=~'\\S'?'<1':1
endfunction
command! FoldParagraphs call FoldParagraphs()
" }}}
" Map S-Insert to insert the "*" register literally.
if has('gui')
" nmap <S-Insert> <C-R><C-o>*
" map! <S-Insert> <C-R><C-o>*
nmap <S-Insert> <MiddleMouse>
map! <S-Insert> <MiddleMouse>
endif
" swap previously selected text with currently selected one (via http://vim.wikia.com/wiki/Swapping_characters,_words_and_lines#Visual-mode_swapping)
vnoremap <C-X> <Esc>`.``gvP``P
" Easy indentation in visual mode
" This keeps the visual selection active after indenting.
" Usually the visual selection is lost after you indent it.
"vmap > >gv
"vmap < <gv
|
blueyed/dotfiles | a8014a8c60d73e15c41a40c395de29a8a52d924f | add usr/bin/p-cache-git | diff --git a/usr/bin/p-cache-git b/usr/bin/p-cache-git
new file mode 100755
index 0000000..c16f0b2
--- /dev/null
+++ b/usr/bin/p-cache-git
@@ -0,0 +1,40 @@
+#!/bin/sh
+# Wrapper around git in .pytest_cache/v/cache.
+#
+# This is meant to be useful to stash/save/restore the cache, e.g. when using
+# the `--lf` (last-failed) mode etc.
+#
+# NOTE: you can also use `git -C .pytest_cache/v/cache â¦` directly, of course..
+#
+# TODO:
+# - short action names to stash/pop?
+# - completion (IIRC this requires fix for -C in zsh?)
+
+set -e
+# set -x
+
+error() {
+ echo "$@"
+ exit 64
+}
+
+root=".pytest_cache/v/cache"
+cdup="$(git rev-parse --show-cdup)"
+if [ -n "$cdup" ]; then
+ root="$cdup/$root"
+fi
+
+if ! [ -d "$root" ]; then
+ error "Directory $root does not exist"
+fi
+
+cd "$root"
+
+if ! [ -e ".git" ]; then
+ git init .
+ git commit --allow-empty -m "init"
+ git add --all .
+ git commit -m "initial state"
+fi
+
+git "$@"
|
blueyed/dotfiles | e536c9cb158518793a690c8b4825a6f5cffeabd3 | vim: update ftplugin/gitcommit.vim | diff --git a/vim/ftplugin/gitcommit.vim b/vim/ftplugin/gitcommit.vim
index 4fcd499..4fc1727 100644
--- a/vim/ftplugin/gitcommit.vim
+++ b/vim/ftplugin/gitcommit.vim
@@ -1,20 +1,25 @@
" Setup windows for Git commit message editing.
" It scrolls to "Changes" in the buffer, splits the window etc.
" This allows for reviewing the diff (from `git commit -v`) while editing the
" commit message easily.
-if get(b:, 'fugitive_type', '') !=# 'index' " Skip with fugitive :Gstatus
+if has_key(b:, 'b:fugitive_commit_arguments')
+ \ || get(b:, 'fugitive_type', '') !=# 'index' " Skip with fugitive :Gstatus
+ if !(tabpagenr('$') == 1 && winnr('$') == 1)
+ " Only with single windows (for Q mapping at least).
+ finish
+ endif
let b:my_auto_scrolloff=0
setlocal foldmethod=syntax foldlevel=1 nohlsearch spell spl=de,en sw=2 scrolloff=0
augroup vimrc_gitcommit
autocmd BufWinEnter <buffer>
- \ exe 'g/^# \(Changes not staged\|Untracked files\)/norm! zc'
- \ | silent! exe '?^# Changes to be committed:'
+ \ exe 'keeppatterns g/^# \(Changes not staged\|Untracked files\)/norm! zc'
+ \ | silent! exe 'keeppatterns ?^# Changes to be committed:'
\ | exe 'norm! zt'
\ | belowright exe max([5, min([10, (winheight(0) / 3)])]).'split'
\ | exe 'normal! gg'
\ | if has('vim_starting') | exe 'autocmd VimEnter * nested 2wincmd w' | endif
\ | exe 'augroup vimrc_gitcommit | exe "au!" | augroup END'
\ | map <buffer> Q :qall<CR>
augroup END
endif
|
blueyed/dotfiles | 856eb3192ce662deab5677bc3dd930b92763f0bd | add make-tags | diff --git a/usr/bin/make-tags b/usr/bin/make-tags
new file mode 100755
index 0000000..db3afff
--- /dev/null
+++ b/usr/bin/make-tags
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+rg --files | ctags --links=no -L - "$@"
|
blueyed/dotfiles | 3ee6624ed94fd983e80b1a5fc73922d96c9f5baa | vimrc: proper guicursor setting | diff --git a/vimrc b/vimrc
index 2b0b68b..6717499 100644
--- a/vimrc
+++ b/vimrc
@@ -117,1025 +117,1025 @@ if 1 " has('eval') / `let` may not be available.
if filereadable(s:neobundle_default_cache_file)
call delete(s:neobundle_default_cache_file)
endif
if filereadable(g:neobundle#cache_file)
call delete(g:neobundle#cache_file)
endif
let g:neobundle#cache_file = s:vim_cache.'/neobundle.cache'.s:cache_key
" }}}
if neobundle#load_cache($MYVIMRC)
" NeoBundles list - here be dragons! {{{
fun! MyNeoBundleWrapper(cmd_args, default, light)
let lazy = g:MyRcProfile == "light" ? a:light : a:default
if lazy == -1
return
endif
if lazy
exec 'NeoBundleLazy ' . a:cmd_args
else
exec 'NeoBundle ' . a:cmd_args
endif
endfun
com! -nargs=+ MyNeoBundle call MyNeoBundleWrapper(<q-args>, 1, 1)
com! -nargs=+ MyNeoBundleLazy call MyNeoBundleWrapper(<q-args>, 1, 1)
com! -nargs=+ MyNeoBundleNeverLazy call MyNeoBundleWrapper(<q-args>, 0, 0)
com! -nargs=+ MyNeoBundleNoLazyForDefault call MyNeoBundleWrapper(<q-args>, 0, 1)
com! -nargs=+ MyNeoBundleNoLazyNotForLight call MyNeoBundleWrapper(<q-args>, 0, -1)
if s:use_ycm
MyNeoBundleNoLazyForDefault 'blueyed/YouCompleteMe' , {
\ 'build': {
\ 'unix': './install.sh --clang-completer --system-libclang'
\ .' || ./install.sh --clang-completer',
\ },
\ 'augroup': 'youcompletemeStart',
\ 'autoload': { 'filetypes': ['c', 'vim'], 'commands': 'YcmCompleter' }
\ }
endif
MyNeoBundleLazy 'davidhalter/jedi-vim', '', {
\ 'directory': 'jedi',
\ 'autoload': { 'filetypes': ['python'], 'commands': ['Pyimport'] }}
" Generate NeoBundle statements from .gitmodules.
" (migration from pathogen to neobundle).
" while read p url; do \
" echo "NeoBundle '${url#*://github.com/}', { 'directory': '${${p##*/}%.url}' }"; \
" done < <(git config -f .gitmodules --get-regexp 'submodule.vim/bundle/\S+.(url)' | sort)
MyNeoBundle 'tpope/vim-abolish'
MyNeoBundle 'mileszs/ack.vim'
MyNeoBundle 'tpope/vim-afterimage'
MyNeoBundleNoLazyForDefault 'ervandew/ag'
MyNeoBundleNoLazyForDefault 'gabesoft/vim-ags'
MyNeoBundleNoLazyForDefault 'blueyed/vim-airline'
MyNeoBundleNoLazyForDefault 'vim-airline/vim-airline-themes'
MyNeoBundle 'vim-scripts/bufexplorer.zip', { 'name': 'bufexplorer' }
MyNeoBundleNoLazyForDefault 'qpkorr/vim-bufkill'
MyNeoBundle 'vim-scripts/cmdline-completion', {
\ 'autoload': {'mappings': [['c', '<Plug>CmdlineCompletion']]}}
MyNeoBundle 'kchmck/vim-coffee-script'
MyNeoBundle 'chrisbra/colorizer'
\, { 'autoload': { 'commands': ['ColorToggle'] } }
MyNeoBundle 'chrisbra/vim-diff-enhanced'
\, { 'autoload': { 'commands': ['CustomDiff', 'PatienceDiff'] } }
MyNeoBundle 'chrisbra/vim-zsh', {
\ 'autoload': {'filetypes': ['zsh']} }
" MyNeoBundle 'lilydjwg/colorizer'
MyNeoBundle 'JulesWang/css.vim'
MyNeoBundleNoLazyForDefault 'ctrlpvim/ctrlp.vim'
MyNeoBundleNoLazyForDefault 'JazzCore/ctrlp-cmatcher'
MyNeoBundle 'mtth/cursorcross.vim'
\, { 'autoload': { 'insert': 1, 'filetypes': 'all' } }
MyNeoBundleLazy 'tpope/vim-endwise', {
\ 'autoload': {'filetypes': ['lua','elixir','ruby','sh','zsh','vb','vbnet','aspvbs','vim','c','cpp','xdefaults','objc','matlab']} }
MyNeoBundle 'blueyed/cyclecolor'
MyNeoBundleLazy 'Raimondi/delimitMate'
\, { 'autoload': { 'insert': 1, 'filetypes': 'all' }}
" MyNeoBundleNeverLazy 'cohama/lexima.vim'
" MyNeoBundleNoLazyForDefault 'raymond-w-ko/detectindent'
MyNeoBundleNoLazyForDefault 'roryokane/detectindent'
MyNeoBundleNoLazyForDefault 'tpope/vim-dispatch'
MyNeoBundleNoLazyForDefault 'radenling/vim-dispatch-neovim'
MyNeoBundle 'jmcomets/vim-pony', { 'directory': 'django-pony' }
MyNeoBundle 'xolox/vim-easytags', {
\ 'autoload': { 'commands': ['UpdateTags'] },
\ 'depends': [['xolox/vim-misc', {'name': 'vim-misc'}]]}
MyNeoBundleNoLazyForDefault 'tpope/vim-eunuch'
MyNeoBundleNoLazyForDefault 'tommcdo/vim-exchange'
MyNeoBundle 'int3/vim-extradite'
MyNeoBundle 'jmcantrell/vim-fatrat'
MyNeoBundleNoLazyForDefault 'kopischke/vim-fetch'
MyNeoBundleNoLazyForDefault 'kopischke/vim-stay'
MyNeoBundle 'thinca/vim-fontzoom'
MyNeoBundleNoLazyForDefault 'idanarye/vim-merginal'
MyNeoBundle 'mkomitee/vim-gf-python'
MyNeoBundle 'mattn/gist-vim', {
\ 'depends': [['mattn/webapi-vim']]}
MyNeoBundle 'jaxbot/github-issues.vim'
MyNeoBundle 'gregsexton/gitv'
MyNeoBundleNeverLazy 'jamessan/vim-gnupg'
MyNeoBundle 'google/maktaba'
MyNeoBundle 'blueyed/grep.vim'
MyNeoBundle 'mbbill/undotree', {
\ 'autoload': {'command_prefix': 'Undotree'}}
MyNeoBundle 'tpope/vim-haml'
MyNeoBundle 'nathanaelkane/vim-indent-guides'
" MyNeoBundle 'ivanov/vim-ipython'
" MyNeoBundle 'johndgiese/vipy'
MyNeoBundle 'vim-scripts/keepcase.vim'
" NOTE: sets eventsignore+=FileType globally.. use a own snippet instead.
" NOTE: new patch from author.
MyNeoBundleNoLazyForDefault 'vim-scripts/LargeFile'
" MyNeoBundleNoLazyForDefault 'mhinz/vim-hugefile'
" MyNeoBundle 'groenewege/vim-less'
MyNeoBundleNoLazyForDefault 'embear/vim-localvimrc'
MyNeoBundle 'xolox/vim-lua-ftplugin', {
\ 'autoload': {'filetypes': 'lua'},
\ 'depends': [['xolox/vim-misc', {'name': 'vim-misc'}]]}
MyNeoBundle 'raymond-w-ko/vim-lua-indent', {
\ 'autoload': {'filetypes': 'lua'}}
if has('ruby')
MyNeoBundleNoLazyForDefault 'sjbach/lusty'
endif
MyNeoBundle 'vim-scripts/mail.tgz', { 'name': 'mail', 'directory': 'mail_tgz' }
MyNeoBundle 'tpope/vim-markdown'
MyNeoBundle 'nelstrom/vim-markdown-folding'
\, {'autoload': {'filetypes': 'markdown'}}
MyNeoBundle 'Shougo/neomru.vim'
MyNeoBundleLazy 'blueyed/nerdtree', {
\ 'augroup' : 'NERDTreeHijackNetrw' }
MyNeoBundle 'blueyed/nginx.vim'
MyNeoBundleLazy 'tyru/open-browser.vim', {
\ 'autoload': { 'mappings': '<Plug>(openbrowser' } }
MyNeoBundle 'kana/vim-operator-replace'
MyNeoBundleNoLazyForDefault 'kana/vim-operator-user'
MyNeoBundle 'vim-scripts/pac.vim'
MyNeoBundle 'mattn/pastebin-vim'
MyNeoBundle 'shawncplus/phpcomplete.vim'
MyNeoBundle '2072/PHP-Indenting-for-VIm', { 'name': 'php-indent' }
MyNeoBundle 'greyblake/vim-preview'
MyNeoBundleNoLazyForDefault 'tpope/vim-projectionist'
MyNeoBundleNoLazyForDefault 'dbakker/vim-projectroot'
" MyNeoBundle 'dbakker/vim-projectroot', {
" \ 'autoload': {'commands': 'ProjectRootGuess'}}
MyNeoBundle 'fs111/pydoc.vim'
\ , {'autoload': {'filetypes': ['python']} }
MyNeoBundle 'alfredodeza/pytest.vim'
MyNeoBundle '5long/pytest-vim-compiler'
\ , {'autoload': {'filetypes': ['python']} }
MyNeoBundle 'hynek/vim-python-pep8-indent'
\ , {'autoload': {'filetypes': ['python']} }
" MyNeoBundle 'Chiel92/vim-autoformat'
" \ , {'autoload': {'filetypes': ['python']} }
MyNeoBundleNoLazyForDefault 'tomtom/quickfixsigns_vim'
MyNeoBundleNoLazyForDefault 't9md/vim-quickhl'
MyNeoBundle 'aaronbieber/vim-quicktask'
MyNeoBundle 'tpope/vim-ragtag'
\ , {'autoload': {'filetypes': ['html', 'smarty', 'php', 'htmldjango']} }
MyNeoBundle 'tpope/vim-rails'
MyNeoBundle 'vim-scripts/Rainbow-Parenthsis-Bundle'
MyNeoBundle 'thinca/vim-ref'
MyNeoBundle 'tpope/vim-repeat'
MyNeoBundle 'inkarkat/runVimTests'
" MyNeoBundleLazy 'tpope/vim-scriptease', {
" \ 'autoload': {'mappings': 'zS', 'filetypes': 'vim', 'commands': ['Runtime']} }
MyNeoBundleNoLazyForDefault 'tpope/vim-scriptease'
MyNeoBundle 'xolox/vim-session', {
\ 'autoload': {'commands': ['SessionOpen', 'OpenSession']}
\, 'depends': [['xolox/vim-misc', {'name': 'vim-misc'}]]
\, 'augroup': 'PluginSession' }
" For PHP:
" MyNeoBundle 'blueyed/smarty.vim', {
" \ 'autoload': {'filetypes': 'smarty'}}
MyNeoBundleNeverLazy 'justinmk/vim-sneak'
MyNeoBundle 'rstacruz/sparkup'
\ , {'autoload': {'filetypes': ['html', 'htmldjango', 'smarty']}}
MyNeoBundle 'tpope/vim-speeddating'
MyNeoBundle 'AndrewRadev/splitjoin.vim'
MyNeoBundleNoLazyForDefault 'AndrewRadev/undoquit.vim'
MyNeoBundleNoLazyForDefault 'EinfachToll/DidYouMean'
MyNeoBundleNoLazyForDefault 'mhinz/vim-startify'
" After startify: https://github.com/mhinz/vim-startify/issues/33
" NeoBundle does not keep the order in the cache though.. :/
MyNeoBundleNoLazyForDefault 'tpope/vim-fugitive'
\, {'augroup': 'fugitive'}
MyNeoBundleNoLazyForDefault 'chrisbra/sudoedit.vim', {
\ 'autoload': {'commands': ['SudoWrite', 'SudoRead']} }
MyNeoBundleNoLazyForDefault 'ervandew/supertab'
MyNeoBundleNoLazyForDefault 'tpope/vim-surround'
MyNeoBundle 'kurkale6ka/vim-swap'
MyNeoBundleNoLazyForDefault "neomake/neomake"
MyNeoBundle 'vim-scripts/syntaxattr.vim'
if executable("tmux")
MyNeoBundle 'Keithbsmiley/tmux.vim', {
\ 'name': 'syntax-tmux',
\ 'autoload': {'filetypes': ['tmux']} }
MyNeoBundleNoLazyForDefault 'blueyed/vim-tmux-navigator'
MyNeoBundleNoLazyForDefault 'tmux-plugins/vim-tmux-focus-events'
MyNeoBundleNoLazyForDefault 'wellle/tmux-complete.vim'
endif
" Dependency
" MyNeoBundle 'godlygeek/tabular'
MyNeoBundle 'junegunn/vim-easy-align'
\ ,{ 'autoload': {'commands': ['EasyAlign', 'LiveEasyAlign']} }
MyNeoBundle 'majutsushi/tagbar'
\ ,{ 'autoload': {'commands': ['TagbarToggle']} }
MyNeoBundle 'tpope/vim-tbone'
MyNeoBundleNoLazyForDefault 'tomtom/tcomment_vim'
" MyNeoBundle 'kana/vim-textobj-user'
MyNeoBundleNoLazyForDefault 'kana/vim-textobj-function'
\ ,{'depends': 'kana/vim-textobj-user'}
MyNeoBundleNoLazyForDefault 'kana/vim-textobj-indent'
\ ,{'depends': 'kana/vim-textobj-user'}
MyNeoBundleNoLazyForDefault 'mattn/vim-textobj-url'
\ ,{'depends': 'kana/vim-textobj-user'}
MyNeoBundle 'bps/vim-textobj-python'
\ ,{'depends': 'kana/vim-textobj-user',
\ 'autoload': {'filetypes': 'python'}}
MyNeoBundleNoLazyForDefault 'inkarkat/argtextobj.vim',
\ {'depends': ['tpope/vim-repeat', 'vim-scripts/ingo-library']}
MyNeoBundleNoLazyForDefault 'vim-scripts/ArgsAndMore',
\ {'depends': ['vim-scripts/ingo-library']}
" MyNeoBundle 'kana/vim-textobj-django-template', 'fix'
MyNeoBundle 'mjbrownie/django-template-textobjects'
\ , {'autoload': {'filetypes': ['htmldjango']} }
MyNeoBundle 'vim-scripts/parameter-text-objects'
" paulhybryant/vim-textobj-path " ap/ip (next path w/o basename), aP/iP (prev)
" kana/vim-textobj-syntax " ay/iy
MyNeoBundle 'tomtom/tinykeymap_vim'
MyNeoBundle 'tomtom/tmarks_vim'
MyNeoBundleNoLazyForDefault 'tomtom/tmru_vim', { 'depends':
\ [['tomtom/tlib_vim', { 'directory': 'tlib' }]]}
MyNeoBundle 'vim-scripts/tracwiki'
MyNeoBundle 'tomtom/ttagecho_vim'
" UltiSnips cannot be set as lazy (https://github.com/Shougo/neobundle.vim/issues/335).
MyNeoBundleNoLazyForDefault 'SirVer/ultisnips'
" MyNeoBundle 'honza/vim-snippets'
MyNeoBundleNoLazyForDefault 'blueyed/vim-snippets'
MyNeoBundleNeverLazy 'tpope/vim-unimpaired'
MyNeoBundle 'Shougo/unite-outline'
MyNeoBundleNoLazyForDefault 'Shougo/unite.vim'
MyNeoBundle 'vim-scripts/vcscommand.vim'
MyNeoBundleLazy 'joonty/vdebug', {
\ 'autoload': { 'commands': 'VdebugStart' }}
MyNeoBundle 'vim-scripts/viewoutput'
MyNeoBundleNoLazyForDefault 'Shougo/vimfiler.vim'
MyNeoBundle 'xolox/vim-misc', { 'name': 'vim-misc' }
MyNeoBundle 'tpope/vim-capslock'
MyNeoBundle 'sjl/splice.vim' " Sophisticated mergetool.
" Enhanced omnifunc for ft=vim.
MyNeoBundle 'c9s/vimomni.vim'
MyNeoBundle 'inkarkat/VimTAP', { 'name': 'VimTAP' }
" Try VimFiler instead; vinegar maps "." (https://github.com/tpope/vim-repeat/issues/19#issuecomment-59454216).
" MyNeoBundle 'tpope/vim-vinegar'
MyNeoBundle 'jmcantrell/vim-virtualenv'
\, { 'autoload': {'commands': 'VirtualEnvActivate'} }
MyNeoBundle 'tyru/visualctrlg.vim'
MyNeoBundle 'nelstrom/vim-visual-star-search'
MyNeoBundle 'mattn/webapi-vim'
MyNeoBundle 'gcmt/wildfire.vim'
MyNeoBundle 'sukima/xmledit'
" Expensive on startup, not used much
" (autoload issue: https://github.com/actionshrimp/vim-xpath/issues/7).
MyNeoBundleLazy 'actionshrimp/vim-xpath', {
\ 'autoload': {'commands': ['XPathSearchPrompt']}}
MyNeoBundle 'guns/xterm-color-table.vim'
MyNeoBundleNoLazyForDefault 'maxbrunsfeld/vim-yankstack'
MyNeoBundle 'klen/python-mode'
" MyNeoBundle 'chrisbra/Recover.vim'
MyNeoBundleNoLazyForDefault 'blueyed/vim-diminactive'
MyNeoBundleNoLazyForDefault 'blueyed/vim-smartinclude'
" Previously disabled plugins:
MyNeoBundle 'MarcWeber/vim-addon-nix'
\, {'name': 'nix', 'autoload': {'filetypes': ['nix']}
\, 'depends': [
\ ['MarcWeber/vim-addon-mw-utils', { 'directory': 'mw-utils' }],
\ ['MarcWeber/vim-addon-actions', { 'directory': 'actions' }],
\ ['MarcWeber/vim-addon-completion', { 'directory': 'completion' }],
\ ['MarcWeber/vim-addon-goto-thing-at-cursor', { 'directory': 'goto-thing-at-cursor' }],
\ ['MarcWeber/vim-addon-errorformats', { 'directory': 'errorformats' }],
\ ]}
MyNeoBundleLazy 'szw/vim-maximizer'
\ , {'autoload': {'commands': 'MaximizerToggle'}}
" Colorschemes.
" MyNeoBundle 'vim-scripts/Atom', '', 'colors', { 'name': 'colorscheme-atom' }
MyNeoBundleNeverLazy 'chriskempson/base16-vim', '', 'colors', { 'name': 'colorscheme-base16' }
" MyNeoBundle 'rking/vim-detailed', '', 'colors', { 'name': 'colorscheme-detailed' }
" MyNeoBundle 'nanotech/jellybeans.vim', '', 'colors', { 'name': 'colorscheme-jellybeans' }
" MyNeoBundle 'tpope/vim-vividchalk', '', 'colors', { 'name': 'colorscheme-vividchalk' }
" MyNeoBundle 'nielsmadan/harlequin', '', 'colors', { 'name': 'colorscheme-harlequin' }
" MyNeoBundle 'gmarik/ingretu', '', 'colors', { 'name': 'colorscheme-ingretu' }
" MyNeoBundle 'vim-scripts/molokai', '', 'colors', { 'name': 'colorscheme-molokai' }
" MyNeoBundle 'vim-scripts/tir_black', '', 'colors', { 'name': 'colorscheme-tir_black' }
" MyNeoBundle 'blueyed/xoria256.vim', '', 'colors', { 'name': 'colorscheme-xoria256' }
" MyNeoBundle 'vim-scripts/xterm16.vim', '', 'colors', { 'name': 'colorscheme-xterm16' }
" MyNeoBundle 'vim-scripts/Zenburn', '', 'colors', { 'name': 'colorscheme-zenburn' }
" MyNeoBundle 'whatyouhide/vim-gotham', '', 'colors', { 'name': 'colorscheme-gotham' }
" EXPERIMENTAL
" MyNeoBundle 'atweiden/vim-betterdigraphs', { 'directory': 'betterdigraphs' }
MyNeoBundle 'chrisbra/unicode.vim', { 'type__depth': 1 }
MyNeoBundle 'xolox/vim-colorscheme-switcher'
MyNeoBundle 't9md/vim-choosewin'
MyNeoBundleNeverLazy 'junegunn/vim-oblique/', { 'depends':
\ [['junegunn/vim-pseudocl']]}
MyNeoBundleNoLazyForDefault 'Konfekt/fastfold'
MyNeoBundleNoLazyNotForLight 'junegunn/vader.vim', {
\ 'autoload': {'commands': 'Vader'} }
MyNeoBundleNoLazyForDefault 'ryanoasis/vim-webdevicons'
MyNeoBundle 'mjbrownie/vim-htmldjango_omnicomplete'
\ , {'autoload': {'filetypes': ['htmldjango']} }
MyNeoBundle 'othree/html5.vim'
\ , {'autoload': {'filetypes': ['html', 'htmldjango']} }
MyNeoBundleLazy 'lambdalisue/vim-pyenv'
" \ , {'depends': ['blueyed/YouCompleteMe']
" \ , 'autoload': {'filetypes': ['python', 'htmldjango']} }
" Problems with <a-d> (which is ä), and I prefer <a-hjkl>.
" MyNeoBundleNoLazyForDefault 'tpope/vim-rsi'
MyNeoBundleNoLazyForDefault 'junegunn/fzf.vim'
MyNeoBundleLazy 'chase/vim-ansible-yaml'
\ , {'autoload': {'filetypes': ['yaml', 'ansible']} }
" MyNeoBundleLazy 'mrk21/yaml-vim'
" \ , {'autoload': {'filetypes': ['yaml', 'ansible']} }
" Manual bundles.
MyNeoBundleLazy 'eclim', '', 'manual'
" \ , {'autoload': {'filetypes': ['htmldjango']} }
" MyNeoBundle 'neobundle', '', 'manual'
" NeoBundleFetch "Shougo/neobundle.vim", {
" \ 'default': 'manual',
" \ 'directory': 'neobundle', }
MyNeoBundleNeverLazy 'blueyed/vim-colors-solarized', { 'name': 'colorscheme-solarized' }
" }}}
NeoBundleSaveCache
endif
call neobundle#end()
filetype plugin indent on
" Use shallow copies by default.
let g:neobundle#types#git#clone_depth = 10
NeoBundleCheck
" Setup a command alias, source: http://stackoverflow.com/a/3879737/15690
fun! SetupCommandAlias(from, to)
exec 'cnoreabbrev <expr> '.a:from
\ .' ((getcmdtype() is# ":" && getcmdline() is# "'.a:from.'")'
\ .'? ("'.a:to.'") : ("'.a:from.'"))'
endfun
call SetupCommandAlias('NBS', 'NeoBundleSource')
if !has('vim_starting')
" Call on_source hook when reloading .vimrc.
call neobundle#call_hook('on_source')
endif
endif
endif
" Settings {{{1
set hidden
if &encoding != 'utf-8' " Skip this on resourcing with Neovim (E905).
set encoding=utf-8
endif
" Prefer unix fileformat
" set fileformat=unix
set fileformats=unix,dos
set noequalalways " do not auto-resize windows when opening/closing them!
set backspace=indent,eol,start " allow backspacing over everything in insert mode
set confirm " ask for confirmation by default (instead of silently failing)
set nosplitright splitbelow
set diffopt+=vertical
set diffopt+=context:1000000 " don't fold
set history=1000
set ruler " show the cursor position all the time
set showcmd " display incomplete commands
set incsearch " do incremental searching
set nowrapscan " do not wrap around when searching.
set writebackup " keep a backup while writing the file (default on)
set backupcopy=yes " important to keep the file descriptor (inotify)
if 1 " has('eval'), and can create the dir dynamically.
set directory=~/tmp/vim/swapfiles// " // => use full path of original file
set backup " enable backup (default off), if 'backupdir' can be created dynamically.
endif
set noautoread " Enabled by default in Neovim; I like to get notified/confirm it.
set nowrap
if has("virtualedit")
set virtualedit+=block
endif
set autoindent " always set autoindenting on (fallback after 'indentexpr')
set numberwidth=1 " Initial default, gets adjusted dynamically.
" Formatting {{{
set tabstop=8
set shiftwidth=2
set noshiftround " for `>`/`<` not behaving like i_CTRL-T/-D
set expandtab
" }}}
if has('autocmd')
augroup vimrc_indent
au!
au FileType make setlocal ts=2
augroup END
augroup vimrc_iskeyword
au!
" Remove '-' and ':' from keyword characters (to highlight e.g. 'width:â¦' and 'font-size:foo' correctly)
" XXX: should get fixed in syntax/css.vim probably!
au FileType css setlocal iskeyword-=-:
augroup END
augroup VimrcColorColumn
au!
au ColorScheme * if expand('<amatch>') == 'solarized'
\ | set colorcolumn=80 | else | set colorcolumn= | endif
augroup END
endif
set isfname-== " remove '=' from filename characters; for completion of FOO=/path/to/file
set laststatus=2 " Always display the statusline
set noshowmode " Should be indicated by statusline (color), and would remove any echom output (e.g. current tag).
" use short timeout after Escape sequence in terminal mode (for keycodes)
set ttimeoutlen=10
set timeoutlen=2000
set updatetime=750 " Used for CursorHold and writing swap files.
" Format options {{{2
set formatoptions+=r " Insert comment leader after hitting <Enter>
set formatoptions+=o " Insert comment leader after hitting o or O in normal mode
set formatoptions+=t " Auto-wrap text using textwidth
set formatoptions+=c " Autowrap comments using textwidth
" set formatoptions+=b " Do not wrap if you modify a line after textwidth; handled by 'l' already?!
set formatoptions+=l " do not wrap lines that have been longer when starting insert mode already
set formatoptions+=q " Allow formatting of comments with "gq".
set formatoptions+=t " Auto-wrap text using textwidth
set formatoptions+=n " Recognize numbered lists
if v:version > 703 || v:version == 703 && has("patch541")
" Delete comment character when joining commented lines
set formatoptions+=j
endif
" }}}
if exists('+breakindent')
set breakindent
set breakindentopt=min:20,shift:0,sbr
endif
set linebreak " Wrap only at chars in 'breakat'.
set synmaxcol=1000 " don't syntax-highlight long lines (default: 3000)
set guioptions-=e " Same tabline as with terminal (allows for setting colors).
set guioptions-=m " no menu with gvim
set guioptions-=a " do not mess with X selection when visual selecting text.
set guioptions+=A " make modeless selections available in the X clipboard.
set guioptions+=c " Use console dialogs instead of popup dialogs for simple choices.
set guicursor& " explicitly enable it for rxvt-unicode (not in Nvim's os_term_is_nice).
-set guicursor=a:blinkon0 " disable cursor blinking.
+let &guicursor .= ',a:blinkon0' " disable cursor blinking.
set viminfo+=% " remember opened files and restore on no-args start (poor man's crash recovery)
set viminfo+=! " keep global uppercase variables. Used by localvimrc.
if has('shada')
" Bump ' to 1000 (from 100) for v:oldfiles.
set shada=!,'1000,<50,s10,h,%,r/mnt/
endif
set selectmode=
set mousemodel=popup " extend/popup/pupup_setpos
set keymodel-=stopsel " do not stop visual selection with cursor keys
set selection=inclusive
" set clipboard=unnamed
" Do not mess with X selection by default (only in modeless mode).
if !has('nvim')
set clipboard-=autoselect
set clipboard+=autoselectml
endif
if has('mouse')
set mouse=nvi " Enable mouse (not for command line mode)
if !has('nvim')
" Make mouse work with Vim in tmux
try
set ttymouse=sgr
catch
set ttymouse=xterm2
endtry
endif
endif
set showmatch " show matching pairs
set matchtime=3
" Jump to matching bracket when typing the closing one.
" Deactivated, causes keys to be ignored when typed too fast (?).
"inoremap } }<Left><c-o>%<c-o>:sleep 500m<CR><c-o>%<c-o>a
"inoremap ] ]<Left><c-o>%<c-o>:sleep 500m<CR><c-o>%<c-o>a
"inoremap ) )<Left><c-o>%<c-o>:sleep 500m<CR><c-o>%<c-o>a
set sessionoptions+=unix,slash " for unix/windows compatibility
set nostartofline " do not go to start of line automatically when moving
" Use both , and Space as leader.
if 1 " has('eval')
let mapleader = ","
endif
" But not for imap!
nmap <space> <Leader>
vmap <space> <Leader>
" scrolloff: number of lines visible above/below the cursor.
" Special handling for &bt!="" and &diff.
set scrolloff=3
if has('autocmd')
fun! MyAutoScrollOff() " {{{
if exists('b:no_auto_scrolloff')
return
endif
if &ft == 'help'
let scrolloff = 999
elseif &buftype != ""
" Especially with quickfix (mouse jumping, more narrow).
let scrolloff = 0
elseif &diff
let scrolloff = 10
else
let scrolloff = 3
endif
if &scrolloff != scrolloff
let &scrolloff = scrolloff
endif
endfun
augroup set_scrolloff
au!
au BufEnter,WinEnter * call MyAutoScrollOff()
if exists('##TermOpen') " neovim
au TermOpen * set sidescrolloff=0 scrolloff=0
endif
augroup END
" Toggle auto-scrolloff handling.
fun! MyAutoScrollOffToggle()
if exists('b:no_auto_scrolloff')
unlet b:no_auto_scrolloff
call MyAutoScrollOff()
echom "auto-scrolloff: enabled"
else
let b:no_auto_scrolloff=1
let &scrolloff=3
echom "auto-scrolloff: disabled"
endif
endfun
nnoremap <leader>so :call MyAutoScrollOffToggle()<cr>
endif " }}}
set sidescroll=1
set sidescrolloff=10
set commentstring=#\ %s
" 'suffixes' get ignored by tmru
set suffixes+=.tmp
set suffixes+=.pyc
" set suffixes+=.sw?
" case only matters with mixed case expressions
set ignorecase smartcase
set smarttab
" NOTE: ignorecase also affects ":tj"/":tselect"!
" https://github.com/vim/vim/issues/712
if exists('+tagcase')
set tagcase=match
endif
set lazyredraw " No redraws in macros.
set wildmenu
" move cursor instead of selecting entries (wildmenu)
cnoremap <Left> <Space><BS><Left>
cnoremap <Right> <Space><BS><Right>
" consider existing windows (but not tabs) when opening files, e.g. from quickfix
" set switchbuf=useopen
" set switchbuf=split
" Display extra whitespace
" set list listchars=tab:»·,trail:·,eol:¬,nbsp:_,extends:â¯,precedes:â®
" set fillchars=stl:^,stlnc:-,vert:\|,fold:-,diff:-
" set fillchars=vert:\|,fold:·,stl:\ ,stlnc:â,diff:⣿
set fillchars=vert:\ ,fold:\ ,stl:\ ,stlnc:\ ,diff:⣿
" Do not display "Pattern not found" messages during YouCompleteMe completion.
" Patch: https://groups.google.com/forum/#!topic/vim_dev/WeBBjkXE8H8
if 1 && exists(':try')
try
set shortmess+=c
" Catch "Illegal character" (and its translations).
catch /E539: /
endtry
endif
set nolist
set listchars=tab:»·,trail:·,eol:¬,nbsp:_,extends:»,precedes:«
" Experimental: setup listchars diffenrently for insert mode {{{
" fun! MySetupList(mode)
" if a:mode == 'i'
" let b:has_list=&list
" if ! &list
" " set listchars-=eol:¬
" endif
" set list
" else
" if !(exists('b:has_list') && b:has_list)
" set nolist
" endif
" " set listchars+=eol:¬
" endif
" endfun
" augroup trailing
" au!
" au InsertEnter * call MySetupList('i')
" au InsertLeave * call MySetupList('n')
" augroup END
" }}}
" Generic GUI options. {{{2
if has('gui_running')
set guioptions-=T " hide toolbar
if has('vim_starting')
" TODO: dependent on monitor size.
set lines=50 columns=90
endif
set guifont=Ubuntu\ Mono\ For\ Powerline\ 12,DejaVu\ Sans\ Mono\ 10
endif
" }}}1
" Generic mappings. {{{
" Repeat last f/t in opposite direction.
if &rtp =~ '\<sneak\>'
nmap <Leader>; <Plug>SneakPrevious
else
nnoremap <Leader>; ,
endif
nnoremap <Leader><c-l> :redraw!<cr>
" Optimize mappings on German keyboard layout. {{{
" Maps initially inspired by the intl US keyboard layout.
" Not using langmap, because of bugs / issues, e.g.:
" - used with input for LustyBufferGrep
" Not using a function to have this in minimal Vims, too.
" `sunmap` is used to use the key as-is in select mode.
map ö :
sunmap ö
map - /
sunmap -
map _ ?
sunmap _
map ü [
sunmap ü
map + ]
sunmap +
" TODO: ä
" Swap ' and ` keys (` is more useful, but requires shift on a German keyboard) {{{
noremap ' `
sunmap '
noremap ` '
sunmap `
noremap g' g`
sunmap g'
noremap g` g'
sunmap g`
" }}}
" Align/tabularize text.
vmap <Enter> <Plug>(EasyAlign)
if 1 " has('eval') / `let` may not be available.
" Maps to unimpaired mappings by context: diff, loclist or qflist.
" Falls back to "a" for args.
fun! MySetupUnimpairedShortcut()
if &diff
let m = 'c'
" diff-obtain and goto next.
nmap dn do+c
elseif len(getqflist())
let m = 'q'
elseif len(getloclist(0))
let m = 'l'
else
let m = 'n'
endif
if get(b:, '_mysetupunimpairedmaps', '') == m
return
endif
let b:_mysetupunimpairedmaps = m
" Backward.
exec 'nmap <buffer> üü ['.m
exec 'nmap <buffer> +ü ['.m
exec 'nmap <buffer> <Leader>ü ['.m
exec 'nmap <buffer> <A-ü> ['.m
" Forward.
exec 'nmap <buffer> ++ ]'.m
exec 'nmap <buffer> ü+ ]'.m
exec 'nmap <buffer> <Leader>+ ]'.m
exec 'nmap <buffer> <A-+> ]'.m
" AltGr-o and AltGr-p
exec 'nmap <buffer> ø ['.m
exec 'nmap <buffer> þ ]'.m
endfun
augroup vimrc_setupunimpaired
au!
au BufEnter,VimEnter * call MySetupUnimpairedShortcut()
augroup END
" Quit with Q, exit with C-q.
" (go to tab on the left).
fun! MyQuitWindow()
let t = tabpagenr()
let nb_tabs = tabpagenr('$')
let was_last_tab = t == nb_tabs
if &ft != 'qf' && getcmdwintype() == ''
lclose
endif
" Turn off diff mode for all other windows.
if &diff && !exists('w:fugitive_diff_restore')
WindoNodelay diffoff
endif
if &bt == 'terminal'
" 'confirm' does not work: https://github.com/neovim/neovim/issues/4651
q
else
confirm q
endif
if ! was_last_tab && nb_tabs != tabpagenr('$') && tabpagenr() > 1
tabprevious
endif
endfun
nnoremap <silent> Q :call MyQuitWindow()<cr>
nnoremap <silent> <C-Q> :confirm qall<cr>
" Use just "q" in special buffers.
if has('autocmd')
augroup vimrc_special_q
au!
autocmd FileType help,startify nnoremap <buffer> q :confirm q<cr>
augroup END
endif
" }}}
" Close preview and quickfix windows.
nnoremap <silent> <C-W>z :wincmd z<Bar>cclose<Bar>lclose<CR>
" fzf.vim {{{
" Insert mode completion
imap <Leader><c-x><c-k> <plug>(fzf-complete-word)
imap <Leader><c-x><c-f> <plug>(fzf-complete-path)
imap <c-x><c-j> <plug>(fzf-complete-file-ag)
imap <Leader><c-x><c-l> <plug>(fzf-complete-line)
let g:fzf_command_prefix = 'FZF'
let g:fzf_layout = { 'window': 'execute (tabpagenr()-1)."tabnew"' }
" TODO: see /home/daniel/.dotfiles/vim/neobundles/fzf/plugin/fzf.vim
" let g:fzf_nvim_statusline = 0
function! s:fzf_statusline()
let bg_dim = &bg == 'dark' ? 18 : 21
exec 'highlight fzf1 ctermfg=1 ctermbg='.bg_dim
exec 'highlight fzf2 ctermfg=2 ctermbg='.bg_dim
exec 'highlight fzf3 ctermfg=7 ctermbg='.bg_dim
setlocal statusline=%#fzf1#\ >\ %#fzf2#fz%#fzf3#f
endfunction
augroup vimrc_quickfixsigns
au!
autocmd FileType help,fzf,ref-* let b:noquickfixsigns = 1
if exists('##TermOpen')
autocmd TermOpen * let b:noquickfixsigns = 1
endif
augroup END
augroup vimrc_fzf
au!
autocmd User FzfStatusLine call <SID>fzf_statusline()
augroup END
" }}}
let tmux_navigator_no_mappings = 1
if has('vim_starting')
if &rtp =~ '\<tmux-navigator\>'
nnoremap <silent> <c-h> :TmuxNavigateLeft<cr>
nnoremap <silent> <c-j> :TmuxNavigateDown<cr>
nnoremap <silent> <c-k> :TmuxNavigateUp<cr>
nnoremap <silent> <c-l> :TmuxNavigateRight<cr>
" nnoremap <silent> <c-\> :TmuxNavigatePrevious<cr>
else
nnoremap <C-h> <c-w>h
nnoremap <C-j> <c-w>j
nnoremap <C-k> <c-w>k
nnoremap <C-l> <c-w>l
" nnoremap <C-\> <c-w>j
endif
endif
if exists(':tnoremap') && has('vim_starting') " Neovim
" Exit.
tnoremap <Esc> <C-\><C-n>
" <c-space> does not work (https://github.com/neovim/neovim/issues/3101).
tnoremap <C-@> <C-\><C-n>:tab sp<cr>:startinsert<cr>
let g:terminal_scrollback_buffer_size = 100000 " current max
nnoremap <Leader>cx :sp \| :term p --testmon<cr>
nnoremap <Leader>cX :sp \| :term p -k
" Add :Term equivalent to :term, but with ":new" instead of ":enew".
fun! <SID>SplitTerm(...) abort
let cmd = ['zsh', '-i']
if a:0
let cmd += ['-c', join(a:000)]
endif
new
call termopen(cmd)
startinsert
endfun
com! -nargs=* -complete=shellcmd Term call <SID>SplitTerm(<f-args>)
" Open term in current file's dir.
nnoremap <Leader>gt :sp \| exe 'lcd' expand('%:p:h') \| :term<cr>
endif
let g:my_full_name = "Daniel Hahler"
let g:snips_author = g:my_full_name
" TAB is used for general completion.
let g:UltiSnipsExpandTrigger="<c-j>"
let g:UltiSnipsJumpForwardTrigger="<c-j>"
let g:UltiSnipsJumpBackwardTrigger="<c-k>"
let g:UltiSnipsListSnippets = "<c-b>"
let g:UltiSnipsEditSplit='context'
" let g:UltiSnips.always_use_first_snippet = 1
augroup UltiSnipsConfig
au!
au FileType smarty UltiSnipsAddFiletypes smarty.html.javascript.php
au FileType html UltiSnipsAddFiletypes html.javascript.php
augroup END
if !exists('g:UltiSnips') | let g:UltiSnips = {} | endif
let g:UltiSnips.load_early = 1
let g:UltiSnips.UltiSnips_ft_filter = {
\ 'default' : {'filetypes': ["FILETYPE", "all"] },
\ 'html' : {'filetypes': ["html", "javascript", "all"] },
\ 'python' : {'filetypes': ["python", "django", "all"] },
\ 'htmldjango' : {'filetypes': ["python", "django", "html", "all"] },
\ }
let g:UltiSnips.snipmate_ft_filter = {
\ 'default' : {'filetypes': ["FILETYPE", "_"] },
\ 'html' : {'filetypes': ["html", "javascript", "_"] },
\ 'python' : {'filetypes': ["python", "django", "_"] },
\ 'htmldjango' : {'filetypes': ["python", "django", "html", "_"] },
\ }
"\ 'html' : {'filetypes': ["html", "javascript"], 'dir-regex': '[._]vim$' },
if has('win32') || has('win64')
" replace ~/vimfiles with ~/.vim in runtimepath
" let &runtimepath = join( map( split(&rtp, ','), 'substitute(v:val, escape(expand("~/vimfiles"), "\\"), escape(expand("~/.vim"), "\\"), "g")' ), "," )
let &runtimepath = substitute(&runtimepath, '\('.escape($HOME, '\').'\)vimfiles\>', '\1.vim', 'g')
endif
" Sparkup (insert mode) maps. Default: <c-e>/<c-n>, both used by Vim.
let g:sparkupExecuteMapping = '<Leader><c-e>'
" '<c-n>' by default!
let g:sparkupNextMapping = '<Leader><c-n>'
" Syntastic {{{2
let g:syntastic_enable_signs=1
let g:syntastic_check_on_wq=1 " Only for active filetypes.
let g:syntastic_auto_loc_list=1
let g:syntastic_always_populate_loc_list=1
" let g:syntastic_echo_current_error=0 " TEST: faster?!
let g:syntastic_mode_map = {
\ 'mode': 'passive',
\ 'active_filetypes': ['ruby', 'php', 'lua', 'python', 'sh', 'zsh'],
\ 'passive_filetypes': [] }
let g:syntastic_error_symbol='â'
let g:syntastic_warning_symbol='â '
let g:syntastic_aggregate_errors = 0
let g:syntastic_python_checkers = ['python', 'frosted', 'flake8', 'pep8']
" let g:syntastic_php_checkers = ['php']
let g:syntastic_loc_list_height = 1 " handled via qf-resize autocommand
" See 'syntastic_quiet_messages' and 'syntastic_<filetype>_<checker>_quiet_messages'
" let g:syntastic_quiet_messages = {
" \ "level": "warnings",
" \ "type": "style",
" \ "regex": '\m\[C03\d\d\]',
" \ "file": ['\m^/usr/include/', '\m\c\.h$'] }
let g:syntastic_quiet_messages = { "level": [], "type": ["style"] }
fun! SyntasticToggleQuiet(k, v, scope)
let varname = a:scope."syntastic_quiet_messages"
if !exists(varname) | exec 'let '.varname.' = { "level": [], "type": ["style"] }' | endif
exec 'let idx = index('.varname.'[a:k], a:v)'
if idx == -1
exec 'call add('.varname.'[a:k], a:v)'
echom 'Syntastic: '.a:k.':'.a:v.' disabled (filtered).'
else
exec 'call remove('.varname.'[a:k], idx)'
echom 'Syntastic: '.a:k.':'.a:v.' enabled (not filtered).'
endif
endfun
command! SyntasticToggleWarnings call SyntasticToggleQuiet('level', 'warnings', "g:")
command! SyntasticToggleStyle call SyntasticToggleQuiet('type', 'style', "g:")
command! SyntasticToggleWarningsBuffer call SyntasticToggleQuiet('level', 'warnings', "b:")
command! SyntasticToggleStyleBuffer call SyntasticToggleQuiet('type', 'style', "b:")
fun! MySyntasticCheckAll()
let save = g:syntastic_quiet_messages
let g:syntastic_quiet_messages = { "level": [], 'type': [] }
SyntasticCheck
let g:syntastic_quiet_messages = save
endfun
command! MySyntasticCheckAll call MySyntasticCheckAll()
" Source: https://github.com/scrooloose/syntastic/issues/1361#issuecomment-82312541
function! SyntasticDisableToggle()
if !exists('s:syntastic_disabled')
let s:syntastic_disabled = 0
endif
if !s:syntastic_disabled
let s:modemap_save = deepcopy(g:syntastic_mode_map)
let g:syntastic_mode_map['active_filetypes'] = []
let g:syntastic_mode_map['mode'] = 'passive'
let s:syntastic_disabled = 1
SyntasticReset
echom "Syntastic disabled."
else
let g:syntastic_mode_map = deepcopy(s:modemap_save)
let s:syntastic_disabled = 0
echom "Syntastic enabled."
endif
endfunction
command! SyntasticDisableToggle call SyntasticDisableToggle()
" Neomake {{{
let g:neomake_open_list = 2
let g:neomake_list_height = 1 " handled via qf-resize autocommand
" let g:neomake_verbose = 3
" let g:neomake_logfile = '/tmp/neomake.log'
let g:neomake_tempfile_enabled = 1
let g:neomake_vim_enabled_makers = ['vint'] " vimlint is slow and too picky(?).
let g:neomake_python_enabled_makers = ['python', 'flake8']
let g:neomake_c_enabled_makers = []
augroup vimrc_neomake
|
blueyed/dotfiles | 3d3a476e85d5404cd8e9f49c9ff8dc0a2aae660a | git: aliases: update desc, add last-tag | diff --git a/config/git/config b/config/git/config
index 6cb555c..b53b937 100644
--- a/config/git/config
+++ b/config/git/config
@@ -1,216 +1,217 @@
# vim: ft=gitconfig
[user]
name = Daniel Hahler
email = [email protected]
[init]
templatedir = ~/.config/git/template
[alias]
# NOTE: I am using full aliases for most of this, e.g. "ga" for "git add".
amend = commit --amend -v
# use "aliases" instead of "alias", which is used by hub; ref: https://github.com/defunkt/hub/issues/303
aliases = !git config --get-regexp '^alias\\.' | sed -e 's/^alias\\.//' -e 's/ / /' | sort
cp = cherry-pick
dd = !git difftool --no-prompt --tool=my-icdiff
dsf = !git diff --color $@ | diff-so-fancy
- desc = describe --all --always
+ desc = describe --always
dv = !git diff -w "$@" | vim -R -
f = fetch
+ last-tag = describe --abbrev=0 --tags --first-parent
# Used (verbatim/resolved) for internal dirty status in shell theme (â).
ls-untracked = ls-files --other --directory --exclude-standard
m = merge
mf = merge --ff-only
ma = merge --abort
mm = merge --no-edit
mmm = merge -X theirs --no-edit
# preview/temp merge
mp = merge --no-commit
rb = rebase -i @{u}
rba = rebase --abort
rbc = rebase --continue
rbi = rebase --interactive
rbs = rebase --skip
rl = reflog @{now}
rlf = reflog --pretty=reflog
s = status
st = status
sm = submodule
sta = stash --keep-index
sts = stash show -p
stp = stash pop
stl = stash list --format=\"%gd: %ci - %gs\"
up = !git fetch && git rebase
showtrackedignored = ! cd \"${GIT_PREFIX}\" && untracked_list=$(git rev-parse --git-dir)/ignored-untracked.txt && git ls-files -o -i --exclude-standard >\"${untracked_list}\" && GIT_INDEX_FILE=\"\" git ls-files -o -i --exclude-standard | grep -Fvxf \"${untracked_list}\" && rm -rf \"${untracked_list}\"
# Diff stash with working tree.
# This is used to decide, if a stash can be savely dropped.
stash-diff = !zsh -c 'bcompare =(git stash show -p --no-prefix) =(git diff --no-prefix)'
cfg = !$EDITOR $(readlink -f ~/.gitconfig)
# Based on http://haacked.com/archive/2014/07/28/github-flow-aliases/.
# wipe: reset --hard with savepoint.
wipe = "!f() { rev=$(git rev-parse ${1-HEAD}); \
git add -A && git commit --allow-empty -qm 'WIPE SAVEPOINT' \
&& git reset $rev --hard; }; f"
# Merge file contents from another branch.
# Source: http://stackoverflow.com/a/24544974/15690
mergetool-file = "!sh -c 'git show $1:$2 > $2.theirs \
&& git show $(git merge-base $1 $(git rev-parse HEAD)):$2 > $2.base \
&& bcompare $2.theirs $2 $2.base $2 && { rm -f $2.theirs; rm -f $2.base; }' -"
[browser "open-in-running-browser"]
cmd = open-in-running-browser
[web]
browser = open-in-running-browser
[color]
diff = auto
status = auto
branch = auto
ui = true
[color "branch"]
current = green
# current = yellow reverse
local = normal
remote = blue
[color "decorate"]
# bold green by default.
branch = green
# bold red by default.
remoteBranch = bold green
# default: bold yellow.
# tag = green
# default: bold magenta.
# stash = red
# default: bold cyan.
# HEAD = green bold
# default: bold blue.
# grafted =
[color "diff"]
meta = yellow bold
commit = green bold
frag = magenta bold
old = red bold
new = green bold
whitespace = red reverse
[color "diff-highlight"]
# oldNormal = red bold
# oldHighlight = red bold 52
# newNormal = green bold
# newHighlight = green bold 22
[color "status"]
added = yellow
changed = green
untracked = cyan
[core]
# use default..
# whitespace=fix,-indent-with-non-tab,trailing-space,cr-at-eol,blank-at-eol
# -F: --quit-if-one-screen: Quit if entire file fits on first screen.
# -X: --no-init: Don't use termcap init/deinit strings.
# pager = less --no-init --quit-if-one-screen -+S
pager = less -S --no-init --quit-if-one-screen
# -+F/-+X to override LESS selectively?! (http://stackoverflow.com/a/18781512/15690)
# pager = less -+F -+X
[diff]
tool = vimdiff
guitool = bc3
mnemonicprefix = true
compactionHeuristic = true
[difftool "my-icdiff"]
cmd = icdiff --line-numbers --head 5000 "$LOCAL" "$REMOTE"
[difftool "bc3"]
cmd = bcompare $LOCAL $REMOTE
[difftool]
prompt = false
[difftool "vimdiff"]
path = nvim
[merge]
tool = vimdiff
# http://sjl.bitbucket.org/splice.vim/
# tool = splice
stat = true
ff = no
# Insert common ancestor in conflict hunks.
conflictstyle = diff3
[mergetool "splice"]
cmd = "vim -f $BASE $LOCAL $REMOTE $MERGED -c 'SpliceInit'"
trustExitCode = true
[mergetool "bc3"]
# Not required (anymore?)?!
# cmd = bcompare $LOCAL $REMOTE $BASE $MERGED
trustExitCode = true
[merge "dpkg-mergechangelogs"]
name = debian/changelog merge driver
driver = dpkg-mergechangelogs -m %O %A %B %A
# "git-meld":
[treediff]
tool = bc3
[treediff "bc3"]
cmd = bcompare
[log]
abbrevCommit = true
decorate = short
[pretty]
# reflog, with relative date (but for commits, not reflog entries!):
reflog = %C(auto)%h %<|(17)%gd %<|(31)%C(blue)%cr%C(reset) %gs (%s)
[push]
# "simple" not available with Git 1.7.10 (Debian stable), "current" is similar.
default = simple
[interactive]
# Requires perl-term-readkey (Arch) / libterm-readkey-perl (Debian).
singlekey = true
[url "[email protected]:"]
insteadOf = github:
[url "git://github.com/"]
insteadOf = gitpub:
[github]
user = blueyed
[diff "odf"]
binary = true
textconv = odt2txt
[url "ssh://[email protected]/"]
pushInsteadOf = git://github.com/
pushInsteadOf = https://github.com/
[diff-so-fancy]
# changeHunkIndicators = false
stripLeadingSymbols = false
markEmptyLines = false
[pager]
dd = true
dsf = true
icdiff = true
status = true
diff = ~/.dotfiles/lib/diff-so-fancy/diff-so-fancy | $(git config core.pager)
log = ~/.dotfiles/lib/diff-so-fancy/diff-so-fancy | $(git config core.pager)
show = ~/.dotfiles/lib/diff-so-fancy/diff-so-fancy | $(git config core.pager)
[sendemail]
confirm = always
[rerere]
enabled = true
[rebase]
autosquash = 1
[grep]
patternType = perl
lineNumber = true
# TODO: should be set for Tk/tcl globally probably?!
[gui]
fontui = -family \"Liberation Sans\" -size 10 -weight normal -slant roman -underline 0 -overstrike 0
fontdiff = -family \"Liberation Mono\" -size 8 -weight normal -slant roman -underline 0 -overstrike 0
|
blueyed/dotfiles | 001ace8cd6c72151ba6880991e83aa2d481547ae | vimrc: update MyLCDToProjectRoot etc | diff --git a/vimrc b/vimrc
index 20163de..2b0b68b 100644
--- a/vimrc
+++ b/vimrc
@@ -1173,1025 +1173,1026 @@ catch
echom 'Neomake: failed to setup automake: '.v:exception
function! NeomakeCheck(fname) abort
if !get(g:, 'neomake_check_on_wq', 0) && get(w:, 'neomake_quitting_win', 0)
return
endif
if bufnr(a:fname) != bufnr('%')
" Not invoked for the current buffer. This happens for ':w /tmp/foo'.
return
endif
if get(b:, 'neomake_disabled', get(t:, 'neomake_disabled', get(g:, 'neomake_disabled', 0)))
return
endif
let s:windows_before = [tabpagenr(), winnr('$')]
if get(b:, '_my_neomake_checked_tick') == b:changedtick
return
endif
call neomake#Make(1, [])
let b:_my_neomake_checked_tick = b:changedtick
endfun
augroup neomake_check
au!
autocmd BufWritePost * call NeomakeCheck(expand('<afile>'))
if exists('##QuitPre')
autocmd QuitPre * if winnr('$') == 1 | let w:neomake_quitting_win = 1 | endif
endif
augroup END
endtry
" }}}
" gist-vim {{{2
let g:gist_detect_filetype = 1
" }}}
" tinykeymap: used to move between signs from quickfixsigns and useful by itself. {{{2
let g:tinykeymap#mapleader = '<Leader>k'
let g:tinykeymap#timeout = 0 " default: 5000s (ms)
let g:tinykeymap#conflict = 1
" Exit also with 'q'.
let g:tinykeymap#break_key = 113
" Default "*"; exluded "para_move" from tlib.
" List: :echo globpath(&rtp, 'autoload/tinykeymap/map/*.vim')
let g:tinykeymaps_default = [
\ 'buffers', 'diff', 'filter', 'lines', 'loc', 'qfl', 'tabs', 'undo',
\ 'windows', 'quickfixsigns',
\ ]
" \ 'para_move',
" }}}
" fontzoom {{{
let g:fontzoom_no_default_key_mappings = 1
nmap <A-+> <Plug>(fontzoom-larger)
nmap <A--> <Plug>(fontzoom-smaller)
" }}}
" Call bcompare with current and alternate file.
command! BC call system('bcompare '.shellescape(expand('%')).' '.shellescape(expand('#')).'&')
" YouCompleteMe {{{
" This needs to be the Python that YCM was built against. (set in ~/.zshrc.local).
if filereadable($PYTHON_YCM)
let g:ycm_path_to_python_interpreter = $PYTHON_YCM
" let g:ycm_path_to_python_interpreter = 'python-in-terminal'
endif
let g:ycm_filetype_blacklist = {
\ 'python' : 1,
\ 'ycmblacklisted': 1
\}
let g:ycm_complete_in_comments = 1
let g:ycm_complete_in_strings = 1
let g:ycm_collect_identifiers_from_comments_and_strings = 1
let g:ycm_extra_conf_globlist = ['~/src/awesome/.ycm_extra_conf.py']
" Jump mappings, overridden in Python mode with jedi-vim.
nnoremap <leader>j :YcmCompleter GoToDefinition<CR>
nnoremap <leader>gj :YcmCompleter GoToDeclaration<CR>
fun! MySetupPythonMappings()
nnoremap <buffer> <leader>j :call jedi#goto_definitions()<CR>
nnoremap <buffer> <leader>gj :call jedi#goto_assignments()<CR>
endfun
augroup vimrc_jump_maps
au!
au FileType python call MySetupPythonMappings()
augroup END
" Deactivated: causes huge RAM usage (YCM issue 595)
" let g:ycm_collect_identifiers_from_tags_files = 1
" EXPERIMENTAL: auto-popups and experimenting with SuperTab
" NOTE: this skips the following map setup (also for C-n):
" ' pumvisible() ? "\<C-p>" : "\' . key .'"'
let g:ycm_key_list_select_completion = []
let g:ycm_key_list_previous_completion = []
let g:ycm_semantic_triggers = {
\ 'c' : ['->', '.'],
\ 'objc' : ['->', '.'],
\ 'ocaml' : ['.', '#'],
\ 'cpp,objcpp' : ['->', '.', '::'],
\ 'perl' : ['->'],
\ 'php' : ['->', '::'],
\ 'cs,java,javascript,d,vim,python,perl6,scala,vb,elixir,go' : ['.'],
\ 'ruby' : ['.', '::'],
\ 'lua' : ['.', ':'],
\ 'erlang' : [':'],
\ }
" Tags (configure this before easytags, except when using easytags_dynamic_files)
" Look for tags file in parent directories, upto "/"
set tags=./tags;/
" CR and BS mapping: call various plugins manually. {{{
let g:endwise_no_mappings = 1 " NOTE: must be unset instead of 0
let g:cursorcross_no_map_CR = 1
let g:cursorcross_no_map_BS = 1
let g:delimitMate_expand_cr = 0
let g:SuperTabCrMapping = 0 " Skip SuperTab CR map setup (skipped anyway for expr mapping)
let g:cursorcross_mappings = 0 " No generic mappings for cursorcross.
" Force delimitMate mapping (gets skipped if mapped already).
fun! My_CR_map()
" "<CR>" via delimitMateCR
if len(maparg('<Plug>delimitMateCR', 'i'))
let r = "\<Plug>delimitMateCR"
else
let r = "\<CR>"
endif
if len(maparg('<Plug>CursorCrossCR', 'i'))
" requires vim 704
let r .= "\<Plug>CursorCrossCR"
endif
if len(maparg('<Plug>DiscretionaryEnd', 'i'))
let r .= "\<Plug>DiscretionaryEnd"
endif
return r
endfun
imap <expr> <CR> My_CR_map()
fun! My_BS_map()
" "<BS>" via delimitMateBS
if len(maparg('<Plug>delimitMateBS', 'i'))
let r = "\<Plug>delimitMateBS"
else
let r = "\<BS>"
endif
if len(maparg('<Plug>CursorCrossBS', 'i'))
" requires vim 704
let r .= "\<Plug>CursorCrossBS"
endif
return r
endfun
imap <expr> <BS> My_BS_map()
" For endwise.
imap <C-X><CR> <CR><Plug>AlwaysEnd
" }}}
" github-issues
" Trigger API request(s) only when completion is used/invoked.
let g:gissues_lazy_load = 1
" Add tags from $VIRTUAL_ENV
if $VIRTUAL_ENV != ""
let &tags = $VIRTUAL_ENV.'/tags,' . &tags
endif
" syntax mode setup
let php_sql_query = 1
let php_htmlInStrings = 1
" let php_special_functions = 0
" let php_alt_comparisons = 0
" let php_alt_assignByReference = 0
" let PHP_outdentphpescape = 1
let g:PHP_autoformatcomment = 0 " do not set formatoptions/comments automatically (php-indent bundle / vim runtime)
let g:php_noShortTags = 1
" always use Smarty comments in smarty files
" NOTE: for {php} it's useful
let g:tcommentGuessFileType_smarty = 0
endif
if &t_Co == 8
" Allow color schemes to do bright colors without forcing bold. (vim-sensible)
if $TERM !~# '^linux'
set t_Co=16
endif
" Fix t_Co: hack to enable 256 colors with e.g. "screen-bce" on CentOS 5.4;
" COLORTERM=lilyterm used for LilyTerm (set TERM=xterm).
" Do not match "screen" in Linux VT
" if (&term[0:6] == "screen-" || len($COLORTERM))
" set t_Co=256
" endif
endif
" Local dirs"{{{1
set backupdir=~/.local/share/vim/backups
if ! isdirectory(expand(&backupdir))
call mkdir( &backupdir, 'p', 0700 )
endif
if 1
let s:xdg_cache_home = $XDG_CACHE_HOME
if !len(s:xdg_cache_home)
let s:xdg_cache_home = expand('~/.cache')
endif
let s:vimcachedir = s:xdg_cache_home . '/vim'
let g:tlib_cache = s:vimcachedir . '/tlib'
let s:xdg_config_home = $XDG_CONFIG_HOME
if !len(s:xdg_config_home)
let s:xdg_config_home = expand('~/.config')
endif
let s:vimconfigdir = s:xdg_config_home . '/vim'
let g:session_directory = s:vimconfigdir . '/sessions'
let g:startify_session_dir = g:session_directory
let g:startify_change_to_dir = 0
let s:xdg_data_home = $XDG_DATA_HOME
if !len(s:xdg_data_home)
let s:xdg_data_home = expand('~/.local/share')
endif
let s:vimsharedir = s:xdg_data_home . '/vim'
let &viewdir = s:vimsharedir . '/views'
let g:yankring_history_dir = s:vimsharedir
let g:yankring_max_history = 500
" let g:yankring_min_element_length = 2 " more that 1 breaks e.g. `xp`
" Move yankring history from old location, if any..
let s:old_yankring = expand('~/yankring_history_v2.txt')
if filereadable(s:old_yankring)
execute '!mv -i '.s:old_yankring.' '.s:vimsharedir
endif
" Transfer any old (default) tmru files db to new (default) location.
let g:tlib_persistent = s:vimsharedir
let s:old_tmru_file = expand('~/.cache/vim/tlib/tmru/files')
let s:global_tmru_file = s:vimsharedir.'/tmru/files'
let s:new_tmru_file_dir = fnamemodify(s:global_tmru_file, ':h')
if ! isdirectory(s:new_tmru_file_dir)
call mkdir(s:new_tmru_file_dir, 'p', 0700)
endif
if filereadable(s:old_tmru_file)
execute '!mv -i '.shellescape(s:old_tmru_file).' '.shellescape(s:global_tmru_file)
" execute '!rm -r '.shellescape(g:tlib_cache)
endif
end
let s:check_create_dirs = [s:vimcachedir, g:tlib_cache, s:vimconfigdir, g:session_directory, s:vimsharedir, &directory]
if has('persistent_undo')
let &undodir = s:vimsharedir . '/undo'
set undofile
call add(s:check_create_dirs, &undodir)
endif
for s:create_dir in s:check_create_dirs
" Remove trailing slashes, especially for &directory.
let s:create_dir = substitute(s:create_dir, '/\+$', '', '')
if ! isdirectory(s:create_dir)
if match(s:create_dir, ',') != -1
echohl WarningMsg | echom "WARN: not creating dir: ".s:create_dir | echohl None
continue
endif
echom "Creating dir: ".s:create_dir
call mkdir(s:create_dir, 'p', 0700 )
endif
endfor
" }}}
if has("user_commands")
" Themes
" Airline:
let g:airline#extensions#disable_rtp_load = 1
let g:airline_extensions_add = ['neomake']
let g:airline_powerline_fonts = 1
" to test
let g:airline#extensions#branch#use_vcscommand = 1
let g:airline#extensions#branch#displayed_head_limit = 7
let g:airline#extensions#hunks#non_zero_only = 1
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#show_buffers = 0
let g:airline#extensions#tabline#tab_nr_type = '[__tabnr__.%{len(tabpagebuflist(__tabnr__))}]'
let g:airline#extensions#tmuxline#enabled = 1
let g:airline#extensions#whitespace#enabled = 0
let g:airline#extensions#tagbar#enabled = 0
let g:airline#extensions#tagbar#flags = 'f' " full hierarchy of tag (with scope), see tagbar-statusline
" see airline-predefined-parts
" let r += ['%{ShortenFilename(fnamemodify(bufname("%"), ":~:."), winwidth(0)-50)}']
" function! AirlineInit()
" " let g:airline_section_a = airline#section#create(['mode', ' ', 'foo'])
" " let g:airline_section_b = airline#section#create_left(['ffenc','file'])
" " let g:airline_section_c = airline#section#create(['%{getcwd()}'])
" endfunction
" au VimEnter * call AirlineInit()
" jedi-vim (besides YCM with jedi library) {{{1
" let g:jedi#force_py_version = 3
let g:jedi#auto_vim_configuration = 0
let g:jedi#goto_assignments_command = '' " dynamically done for ft=python.
let g:jedi#goto_definitions_command = '' " dynamically done for ft=python.
let g:jedi#rename_command = 'cR'
let g:jedi#usages_command = 'gr'
let g:jedi#completions_enabled = 1
" Unite/ref and pydoc are more useful.
let g:jedi#documentation_command = '<Leader>_K'
" Manually setup jedi's call signatures.
let g:jedi#show_call_signatures = 1
if &rtp =~ '\<jedi\>'
augroup JediSetup
au!
au FileType python call jedi#configure_call_signatures()
augroup END
endif
let g:jedi#auto_close_doc = 1
" if g:jedi#auto_close_doc
" " close preview if its still open after insert
" autocmd InsertLeave <buffer> if pumvisible() == 0|pclose|endif
" end
" }}}1
endif
" Enable syntax {{{1
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
" if (&t_Co > 2 || has("gui_running")) && !exists("syntax_on")
if (&t_Co > 2 || has("gui_running"))
if !exists("syntax_on")
syntax on " after 'filetype plugin indent on' (?!), but not on reload.
endif
set nohlsearch
" Improved syntax handling of TODO etc.
au Syntax * syn match MyTodo /\v<(FIXME|NOTE|TODO|OPTIMIZE|XXX):/
\ containedin=.*Comment,vimCommentTitle
hi def link MyTodo Todo
endif
if 1 " has('eval')
" Color scheme (after 'syntax on') {{{1
" Use light/dark background based on day/night period (according to
" get-daytime-period (uses redshift))
fun! SetBgAccordingToShell(...)
let variant = a:0 ? a:1 : ""
if len(variant) && variant != "auto"
let bg = variant
elseif len($TMUX)
let bg = system('tmux show-env MY_X_THEME_VARIANT') == "MY_X_THEME_VARIANT=light\n" ? 'light' : 'dark'
elseif len($MY_X_THEME_VARIANT)
let bg = $MY_X_THEME_VARIANT
else
" let daytime = system('get-daytime-period')
let daytime_file = expand('/tmp/redshift-period')
if filereadable(daytime_file)
let daytime = readfile(daytime_file)[0]
if daytime == 'Daytime'
let bg = "light"
else
let bg = "dark"
endif
else
let bg = "dark"
endif
endif
if bg != &bg
let &bg = bg
doautocmd <nomodeline> ColorScheme
endif
endfun
command! -nargs=? Autobg call SetBgAccordingToShell(<q-args>)
fun! ToggleBg()
let &bg = &bg == 'dark' ? 'light' : 'dark'
endfun
nnoremap <Leader>sb :call ToggleBg()<cr>
" Colorscheme: prefer solarized with 16 colors (special palette).
let g:solarized_hitrail=0 " using MyWhitespaceSetup instead.
let g:solarized_menu=0
" Use corresponding theme from $BASE16_THEME, if set up in the shell.
" BASE16_THEME should be in sudoer's env_keep for "sudo vi".
if len($BASE16_THEME)
let base16colorspace=&t_Co
if $BASE16_THEME =~ '^solarized'
let s:use_colorscheme = 'solarized'
let g:solarized_base16=1
let g:airline_theme = 'solarized'
else
let s:use_colorscheme = 'base16-'.substitute($BASE16_THEME, '\.\(dark\|light\)$', '', '')
endif
let g:solarized_termtrans=1
elseif has('gui_running')
let s:use_colorscheme = "solarized"
let g:solarized_termcolors=256
else
" Check for dumb terminal.
if ($TERM !~ '256color' )
let s:use_colorscheme = "default"
else
let s:use_colorscheme = "solarized"
let g:solarized_termcolors=256
endif
endif
" Airline: do not use powerline symbols with linux/screen terminal.
" NOTE: xterm-256color gets setup for tmux/screen with $DISPLAY.
if (index(["linux", "screen"], $TERM) != -1)
let g:airline_powerline_fonts = 0
endif
fun! s:MySetColorscheme()
" Set s:use_colorscheme, called through GUIEnter for gvim.
try
exec 'NeoBundleSource colorscheme-'.s:use_colorscheme
exec 'colorscheme' s:use_colorscheme
catch
echom "Failed to load colorscheme: " v:exception
endtry
endfun
if has('vim_starting')
call SetBgAccordingToShell($MY_X_THEME_VARIANT)
endif
if has('gui_running')
au GUIEnter * nested call s:MySetColorscheme()
else
call s:MySetColorscheme()
endif
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd") " Autocommands {{{1
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcEx
au!
" Handle large files, based on LargeFile plugin.
let g:LargeFile = 5 " 5mb
autocmd BufWinEnter * if get(b:, 'LargeFile_mode') || line2byte(line("$") + 1) > 1000000
\ | echom "vimrc: handling large file."
\ | set syntax=off
\ | let &ft = &ft.".ycmblacklisted"
\ | endif
" Enable soft-wrapping for text files
au FileType text,markdown,html,xhtml,eruby,vim setlocal wrap linebreak nolist
au FileType mail,markdown,gitcommit setlocal spell
au FileType json setlocal equalprg=json_pp
" XXX: only works for whole files
" au FileType css setlocal equalprg=csstidy\ -\ --silent=true\ --template=default
" For all text files set 'textwidth' to 78 characters.
" au FileType text setlocal textwidth=78
" Follow symlinks when opening a file {{{
" NOTE: this happens with directory symlinks anyway (due to Vim's chdir/getcwd
" magic when getting filenames).
" Sources:
" - https://github.com/tpope/vim-fugitive/issues/147#issuecomment-7572351
" - http://www.reddit.com/r/vim/comments/yhsn6/is_it_possible_to_work_around_the_symlink_bug/c5w91qw
function! MyFollowSymlink(...)
if exists('w:no_resolve_symlink') && w:no_resolve_symlink
return
endif
if &ft == 'help'
return
endif
let fname = a:0 ? a:1 : expand('%')
if fname =~ '^\w\+:/'
" Do not mess with 'fugitive://' etc.
return
endif
let fname = simplify(fname)
let resolvedfile = resolve(fname)
if resolvedfile == fname
return
endif
let resolvedfile = fnameescape(resolvedfile)
let sshm = &shm
set shortmess+=A " silence ATTENTION message about swap file (would get displayed twice)
redraw " Redraw now, to avoid hit-enter prompt.
exec 'file ' . resolvedfile
let &shm=sshm
unlet! b:git_dir
call fugitive#detect(resolvedfile)
if &modifiable
" Only display a note when editing a file, especially not for `:help`.
redraw " Redraw now, to avoid hit-enter prompt.
echomsg 'Resolved symlink: =>' resolvedfile
endif
endfunction
command! -bar FollowSymlink call MyFollowSymlink()
command! ToggleFollowSymlink let w:no_resolve_symlink = !get(w:, 'no_resolve_symlink', 0) | echo "w:no_resolve_symlink =>" w:no_resolve_symlink
-au BufReadPost * nested call MyFollowSymlink(expand('%'))
+" au BufWinEnter * nested call MyFollowSymlink(expand('%'))
+nnoremap <Leader>gf :FollowSymlink<cr>
" Automatically load .vimrc source when saved
au BufWritePost $MYVIMRC,~/.dotfiles/vimrc,$MYVIMRC.local source $MYVIMRC
au BufWritePost $MYGVIMRC,~/.dotfiles/gvimrc source $MYGVIMRC
" if (has("gui_running"))
" au FocusLost * stopinsert
" endif
" autocommands for fugitive {{{2
" Source: http://vimcasts.org/episodes/fugitive-vim-browsing-the-git-object-database/
au User Fugitive
\ if fugitive#buffer().type() =~# '^\%(tree\|blob\)' |
\ nnoremap <buffer> .. :edit %:h<CR> |
\ endif
au BufReadPost fugitive://* set bufhidden=delete
" Expand tabs for Debian changelog. This is probably not the correct way.
au BufNewFile,BufRead */debian/changelog,changelog.dch set expandtab
" Ignore certain files with vim-stay.
au BufNewFile,BufRead */.git/addp-hunk-edit.diff let b:stay_ignore = 1
" Python
" irrelevant, using python-pep8-indent
" let g:pyindent_continue = '&sw * 1'
" let g:pyindent_open_paren = '&sw * 1'
" let g:pyindent_nested_paren = '&sw'
" python-mode
let g:pymode_options = 0 " do not change relativenumber
let g:pymode_indent = 0 " use vim-python-pep8-indent (upstream of pymode)
let g:pymode_lint = 0 " prefer syntastic; pymode has problems when PyLint was invoked already before VirtualEnvActivate..!?!
let g:pymode_virtualenv = 0 " use virtualenv plugin (required for pylint?!)
let g:pymode_doc = 0 " use pydoc
let g:pymode_rope_completion = 0 " use YouCompleteMe instead (python-jedi)
let g:pymode_syntax_space_errors = 0 " using MyWhitespaceSetup
let g:pymode_trim_whitespaces = 0
let g:pymode_debug = 0
let g:pymode_rope = 0
let g:pydoc_window_lines=0.5 " use 50% height
let g:pydoc_perform_mappings=0
" let python_space_error_highlight = 1 " using MyWhitespaceSetup
" C
au FileType C setlocal formatoptions-=c formatoptions-=o formatoptions-=r
fu! Select_c_style()
if search('^\t', 'n', 150)
setlocal shiftwidth=8 noexpandtab
el
setlocal shiftwidth=4 expandtab
en
endf
au FileType c call Select_c_style()
au FileType make setlocal noexpandtab
" Disable highlighting of markdownError (Ref: https://github.com/tpope/vim-markdown/issues/79).
autocmd FileType markdown hi link markdownError NONE
augroup END
" Trailing whitespace highlighting {{{2
" Map to toogle EOLWS syntax highlighting
noremap <silent> <leader>se :let g:MyAuGroupEOLWSactive = (synIDattr(synIDtrans(hlID("EOLWS")), "bg", "cterm") == -1)<cr>
\:call MyAuGroupEOLWS(mode())<cr>
let g:MyAuGroupEOLWSactive = 0
function! MyAuGroupEOLWS(mode)
if g:MyAuGroupEOLWSactive && &buftype == ''
hi EOLWS ctermbg=red guibg=red
syn clear EOLWS
" match whitespace not preceded by a backslash
if a:mode == "i"
syn match EOLWS excludenl /[\\]\@<!\s\+\%#\@!$/ containedin=ALL
else
syn match EOLWS excludenl /[\\]\@<!\s\+$\| \+\ze\t/ containedin=ALLBUT,gitcommitDiff |
endif
else
syn clear EOLWS
hi clear EOLWS
endif
endfunction
augroup vimrcExEOLWS
au!
" highlight EOLWS ctermbg=red guibg=red
" based on solarizedTrailingSpace
highlight EOLWS term=underline cterm=underline ctermfg=1
au InsertEnter * call MyAuGroupEOLWS("i")
" highlight trailing whitespace, space before tab and tab not at the
" beginning of the line (except in comments), only for normal buffers:
au InsertLeave,BufWinEnter * call MyAuGroupEOLWS("n")
" fails with gitcommit: filetype | syn match EOLWS excludenl /[^\t]\zs\t\+/ containedin=ALLBUT,gitcommitComment
" add this for Python (via python_highlight_all?!):
" au FileType python
" \ if g:MyAuGroupEOLWSactive |
" \ syn match EOLWS excludenl /^\t\+/ containedin=ALL |
" \ endif
augroup END "}}}
" automatically save and reload viminfo across Vim instances
" Source: http://vimhelp.appspot.com/vim_faq.txt.html#faq-17.3
augroup viminfo_onfocus
au!
" au FocusLost * wviminfo
" au FocusGained * rviminfo
augroup end
endif " has("autocmd") }}}
" Shorten a given (absolute) file path, via external `shorten_path` script.
" This mainly shortens entries from Zsh's `hash -d` list.
let s:_cache_shorten_path = {}
let s:_has_functional_shorten_path = 1
let s:shorten_path_exe = executable('shorten_path')
\ ? 'shorten_path'
\ : filereadable(expand("$HOME/.dotfiles/usr/bin/shorten_path"))
\ ? expand("$HOME/.dotfiles/usr/bin/shorten_path")
\ : expand("/home/$SUDO_USER/.dotfiles/usr/bin/shorten_path")
function! ShortenPath(path, ...)
if !len(a:path) || !s:_has_functional_shorten_path
return a:path
endif
let base = a:0 ? a:1 : ""
let annotate = a:0 > 1 ? a:2 : 0
let cache_key = base . ":" . a:path . ":" . annotate
if !exists('s:_cache_shorten_path[cache_key]')
let shorten_path = [s:shorten_path_exe]
if annotate
let shorten_path += ['-a']
endif
let cmd = shorten_path + [a:path, base]
let output = s:systemlist(cmd)
let lastline = empty(output) ? '' : output[-1]
let s:_cache_shorten_path[cache_key] = lastline
if v:shell_error
try
let tmpfile = tempname()
let system_cmd = join(map(copy(cmd), 'fnameescape(v:val)'))
call system(system_cmd.' 2>'.tmpfile)
if v:shell_error == 127
let s:_has_functional_shorten_path = 0
endif
echohl ErrorMsg
echom printf('There was a problem running %s: %s (%d)',
\ cmd, join(readfile(tmpfile), "\n"), v:shell_error)
echohl None
return a:path
finally
call delete(tmpfile)
endtry
endif
endif
return s:_cache_shorten_path[cache_key]
endfun
function! My_get_qfloclist_type(bufnr)
let isLoc = getbufvar(a:bufnr, 'isLoc', -1) " via vim-qf.
if isLoc != -1
return isLoc ? 'll' : 'qf'
endif
" A hacky way to distinguish qf from loclist windows/buffers.
" https://github.com/vim-airline/vim-airline/blob/83b6dd11a8829bbd934576e76bfbda6559ed49e1/autoload/airline/extensions/quickfix.vim#L27-L43.
" Changes:
" - Caching!
" - Match opening square bracket at least. Apart from that it could be
" localized.
" if &ft !=# 'qf'
" return ''
" endif
let type = getbufvar(a:bufnr, 'my_qfloclist_type', '')
if type != ''
return type
endif
redir => buffers
silent ls -
redir END
let type = 'unknown'
for buf in split(buffers, '\n')
if match(buf, '\v^\s*'.a:bufnr.'\s\S+\s+"\[') > -1
if match(buf, '\cQuickfix') > -1
let type = 'qf'
break
else
let type = 'll'
break
endif
endif
endfor
call setbufvar(a:bufnr, 'my_qfloclist_type', type)
return type
endfunction
function! s:systemlist(l) abort
if !has('nvim')
let cmd = join(map(copy(a:l), 'fnameescape(v:val)'))
else
let cmd = a:l
endif
return systemlist(cmd)
endfunction
" Shorten a given filename by truncating path segments.
let g:_cache_shorten_filename = {}
let g:_cache_shorten_filename_git = {}
function! ShortenString(s, maxlen)
if len(a:s) <= a:maxlen
return a:s
endif
return a:s[0:a:maxlen-1] . 'â¦'
endfunction
function! ShortenFilename(...) " {{{
" Args: bufname ('%' for default), maxlength, cwd
let cwd = a:0 > 2 ? a:3 : getcwd()
" Maxlen from a:2 (used for cache key) and caching.
let maxlen = a:0>1 ? a:2 : max([10, winwidth(0)-50])
" get bufname from a:1, defaulting to bufname('%') {{{
if a:0 && type(a:1) == type('') && a:1 !=# '%'
let bufname = expand(a:1) " tilde-expansion.
else
if !a:0 || a:1 == '%'
let bufnr = bufnr('%')
else
let bufnr = a:1
endif
let bufname = bufname(bufnr)
let ft = getbufvar(bufnr, '&filetype')
if !len(bufname)
if ft == 'qf'
let type = My_get_qfloclist_type(bufnr)
" XXX: uses current window. Also not available after ":tab split".
let qf_title = get(w:, 'quickfix_title', '')
if qf_title != ''
return ShortenString('['.type.'] '.qf_title, maxlen)
elseif type == 'll'
let alt_name = expand('#')
" For location lists the alternate file is the corresponding buffer
" and the quickfix list does not have an alternate buffer
" (but not always)!?!
if len(alt_name)
return '[loc] '.ShortenFilename(alt_name, maxlen-5)
endif
return '[loc]'
endif
return '[qf]'
else
let bt = getbufvar(bufnr, '&buftype')
if bt != '' && ft != ''
" Use &ft for name (e.g. with 'startify' and quickfix windows).
" if &ft == 'qf'
" let alt_name = expand('#')
" if len(alt_name)
" return '[loc] '.ShortenFilename(alt_name)
" else
" return '[qf]'
" endif
let alt_name = expand('#')
if len(alt_name)
return '['.&ft.'] '.ShortenFilename(expand('#'))
else
return '['.&ft.']'
endif
else
" TODO: get Vim's original "[No Name]" somehow
return '[No Name]'
endif
endif
end
if ft ==# 'help'
return '[?] '.fnamemodify(bufname, ':t')
endif
if bufname =~# '^__'
return bufname
endif
" '^\[ref-\w\+:.*\]$'
if bufname =~# '^\[.*\]$'
return bufname
endif
endif
" }}}
" {{{ fugitive
if bufname =~# '^fugitive:///'
let [gitdir, fug_path] = split(bufname, '//')[1:2]
" Caching based on bufname and timestamp of gitdir.
let git_ftime = getftime(gitdir)
if exists('g:_cache_shorten_filename_git[bufname]')
\ && g:_cache_shorten_filename_git[bufname][0] == git_ftime
let [commit_name, fug_type, fug_path]
\ = g:_cache_shorten_filename_git[bufname][1:-1]
else
let fug_buffer = fugitive#buffer(bufname)
let fug_type = fug_buffer.type()
" if fug_path =~# '^\x\{7,40\}\>'
let commit = matchstr(fug_path, '\v\w*')
if len(commit) > 1
let git_argv = ['git', '--git-dir='.gitdir]
let commit = systemlist(git_argv + ['rev-parse', '--short', commit])[0]
let commit_name = systemlist(git_argv + ['name-rev', '--name-only', commit])[0]
if commit_name !=# 'undefined'
" Remove current branch name (master~4 => ~4).
let HEAD = get(systemlist(git_argv + ['symbolic-ref', '--quiet', '--short', 'HEAD']), 0, '')
let len_HEAD = len(HEAD)
if len_HEAD > len(commit_name) && commit_name[0:len_HEAD-1] == HEAD
let commit_name = commit_name[len_HEAD:-1]
endif
" let commit .= '('.commit_name.')'
let commit_name .= '('.commit.')'
else
let commit_name = commit
endif
else
let commit_name = commit
endif
" endif
if fug_type !=# 'commit'
let fug_path = substitute(fug_path, '\v\w*/', '', '')
if len(fug_path)
let fug_path = ShortenFilename(fug_buffer.repo().tree(fug_path))
endif
else
let fug_path = 'NOT_USED'
endif
" Set cache.
let g:_cache_shorten_filename_git[bufname]
\ = [git_ftime, commit_name, fug_type, fug_path]
endif
if fug_type ==# 'blob'
return 'λ:' . commit_name . ':' . fug_path
elseif fug_type ==# 'file'
return 'λ:' . fug_path . '@' . commit_name
elseif fug_type ==# 'commit'
" elseif fug_path =~# '^\x\{7,40\}\>'
let work_tree = fugitive#buffer(bufname).repo().tree()
if cwd[0:len(work_tree)-1] == work_tree
let rel_work_tree = ''
else
let rel_work_tree = ShortenPath(fnamemodify(work_tree.'/', ':.'))
endif
return 'λ:' . rel_work_tree . '@' . commit_name
endif
throw "fug_type: ".fug_type." not handled: ".fug_path
endif " }}}
" Check for cache (avoiding fnamemodify): {{{
let cache_key = bufname.'::'.cwd.'::'.maxlen
if has_key(g:_cache_shorten_filename, cache_key)
return g:_cache_shorten_filename[cache_key]
endif
" Make path relative first, which might not work with the result from
" `shorten_path`.
let rel_path = fnamemodify(bufname, ":.")
let bufname = ShortenPath(rel_path, cwd, 1)
" }}}
" Loop over all segments/parts, to mark symlinks.
" XXX: symlinks get resolved currently anyway!?
" NOTE: consider using another method like http://stackoverflow.com/questions/13165941/how-to-truncate-long-file-path-in-vim-powerline-statusline
let maxlen_of_parts = 7 " including slash/dot
let maxlen_of_subparts = 1 " split at hypen/underscore; including split
let s:PS = exists('+shellslash') ? (&shellslash ? '/' : '\') : "/"
let parts = split(bufname, '\ze['.escape(s:PS, '\').']')
let i = 0
let n = len(parts)
let wholepath = '' " used for symlink check
while i < n
let wholepath .= parts[i]
" Shorten part, if necessary:
" TODO: use pathshorten(fnamemodify(path, ':~')) as fallback?!
if i < n-1 && len(bufname) > maxlen && len(parts[i]) > maxlen_of_parts
" Let's see if there are dots or hyphens to truncate at, e.g.
" 'vim-pkg-debian' => 'v-p-dâ¦'
let w = split(parts[i], '\ze[_-]')
if len(w) > 1
let parts[i] = ''
for j in w
if len(j) > maxlen_of_subparts-1
let parts[i] .= j[0:max([maxlen_of_subparts-2, 1])] "."â¦"
else
let parts[i] .= j
endif
endfor
else
let parts[i] = parts[i][0:max([maxlen_of_parts-2, 1])].'â¦'
endif
endif
let i += 1
endwhile
let r = join(parts, '')
if len(r) > maxlen
" echom len(r) maxlen
let i = 0
let n -= 1
while i < n && len(join(parts, '')) > maxlen
if i > 0 || parts[i][0] != '~'
let j = 0
let parts[i] = matchstr(parts[i], '.\{-}\w')
" if i == 0 && parts[i][0] != '/'
" let parts[i] = parts[i][0]
" else
" let parts[i] = matchstr(parts[i], 1)
" endif
endif
let i += 1
endwhile
let r = join(parts, '')
endif
let g:_cache_shorten_filename[cache_key] = r
" echom "ShortenFilename" r
return r
endfunction "}}}
" Shorten filename, and append suffix(es), e.g. for modified buffers. {{{2
fun! ShortenFilenameWithSuffix(...)
let r = call('ShortenFilename', a:000)
if &modified
let r .= ',+'
endif
return r
endfun
" }}}
" Opens an edit command with the path of the currently edited file filled in
" Normal mode: <Leader>e
nnoremap <Leader>ee :e <C-R>=expand("%:p:h") . "/" <CR>
nnoremap <Leader>EE :sp <C-R>=expand("%:p:h") . "/" <CR>
" gt: next tab or buffer (source: http://j.mp/dotvimrc)
" enhanced to support range (via v:count)
fun! MyGotoNextTabOrBuffer(...)
let c = a:0 ? a:1 : v:count
exec (c ? c : '') . (tabpagenr('$') == 1 ? 'bn' : 'tabnext')
endfun
fun! MyGotoPrevTabOrBuffer()
exec (v:count ? v:count : '') . (tabpagenr('$') == 1 ? 'bp' : 'tabprevious')
endfun
nnoremap <silent> <Plug>NextTabOrBuffer :<C-U>call MyGotoNextTabOrBuffer()<CR>
nnoremap <silent> <Plug>PrevTabOrBuffer :<C-U>call MyGotoPrevTabOrBuffer()<CR>
" Ctrl-Space: split into new tab.
" Disables diff mode, which gets taken over from the old buffer.
nnoremap <C-Space> :tab sp \| set nodiff<cr>
nnoremap <A-Space> :tabnew<cr>
" For terminal.
nnoremap <C-@> :tab sp \| set nodiff<cr>
" Opens a tab edit command with the path of the currently edited file filled in
map <Leader>te :tabe <C-R>=expand("%:p:h") . "/" <CR>
map <a-o> <C-W>o
" Avoid this to be done accidentally (when zooming is meant). ":on" is more
" explicit.
map <C-W><C-o> <Nop>
" does not work, even with lilyterm.. :/
" TODO: <C-1>..<C-0> for tabs; not possible; only certain C-sequences get
" through to the terminal Vim
" nmap <C-Insert> :tabnew<cr>
" nmap <C-Del> :tabclose<cr>
nmap <A-Del> :tabclose<cr>
" nmap <C-1> 1gt<cr>
" Prev/next tab.
nmap <C-PageUp> <Plug>PrevTabOrBuffer
nmap <C-PageDown> <Plug>NextTabOrBuffer
map <A-,> <Plug>PrevTabOrBuffer
map <A-.> <Plug>NextTabOrBuffer
map <C-S-Tab> <Plug>PrevTabOrBuffer
map <C-Tab> <Plug>NextTabOrBuffer
" Switch to most recently used tab.
" Source: http://stackoverflow.com/a/2120168/15690
fun! MyGotoMRUTab()
if !exists('g:mrutab')
let g:mrutab = 1
endif
if tabpagenr('$') == 1
echomsg "There is only one tab!"
return
endif
if g:mrutab > tabpagenr('$') || g:mrutab == tabpagenr()
let g:mrutab = tabpagenr() > 1 ? tabpagenr()-1 : tabpagenr('$')
endif
exe "tabn ".g:mrutab
endfun
" Overrides Vim's gh command (start select-mode, but I don't use that).
" It can be simulated using v<C-g> also.
nnoremap <silent> gh :call MyGotoMRUTab()<CR>
" nnoremap ° :call MyGotoMRUTab()<CR>
" nnoremap <C-^> :call MyGotoMRUTab()<CR>
augroup MyTL
au!
au TabLeave * let g:mrutab = tabpagenr()
augroup END
" Map <A-1> .. <A-9> to goto tab or buffer.
for i in range(9)
exec 'nmap <M-' .(i+1).'> :call MyGotoNextTabOrBuffer('.(i+1).')<cr>'
endfor
@@ -2263,1031 +2264,1038 @@ let title .= ' - vim'
" with SSH).
if len($_TERM_TITLE_SUFFIX)
let title .= $_TERM_TITLE_SUFFIX
endif
" Setup tmux window name, see ~/.dotfiles/oh-my-zsh/lib/termsupport.zsh.
if len($TMUX)
\ && (!len($_tmux_name_reset) || $_tmux_name_reset != $TMUX . '_' . $TMUX_PANE)
let tmux_auto_rename=systemlist('tmux show-window-options -t '.$TMUX_PANE.' -v automatic-rename 2>/dev/null')
" || $(tmux show-window-options -t $TMUX_PANE | grep '^automatic-rename' | cut -f2 -d\ )
" echom string(tmux_auto_rename)
if !len(tmux_auto_rename) || tmux_auto_rename[0] != "off"
" echom "Resetting tmux name to 0."
call system('tmux set-window-option -t '.$TMUX_PANE.' -q automatic-rename off')
call system('tmux rename-window -t '.$TMUX_PANE.' 0')
endif
endif
let &titlestring = title
" Set icon text according to &titlestring (used for minimized windows).
let &iconstring = '(v) '.&titlestring
endfun
augroup vimrc_title
au!
" XXX: might not get called with fugitive buffers (title is the (closed) fugitive buffer).
autocmd BufEnter,BufWritePost * call MySetupTitleString()
if exists('##TextChanged')
autocmd TextChanged * call MySetupTitleString()
endif
augroup END
" Make Vim set the window title according to &titlestring.
if !has('gui_running') && empty(&t_ts)
if len($TMUX)
let &t_ts = "\e]2;"
let &t_fs = "\007"
elseif &term =~ "^screen.*"
let &t_ts="\ek"
let &t_fs="\e\\"
endif
endif
fun! MySetSessionName(name)
let g:MySessionName = a:name
call MySetupTitleString()
endfun
"}}}
" Inserts the path of the currently edited file into a command
" Command mode: Ctrl+P
" cmap <C-P> <C-R>=expand("%:p:h") . "/" <CR>
" Change to current file's dir
nnoremap <Leader>cd :lcd <C-R>=expand('%:p:h')<CR><CR>
" yankstack, see also unite's history/yank {{{1
if &rtp =~ '\<yankstack\>'
" Do not map s/S (used by vim-sneak).
" let g:yankstack_yank_keys = ['c', 'C', 'd', 'D', 's', 'S', 'x', 'X', 'y', 'Y']
let g:yankstack_yank_keys = ['c', 'C', 'd', 'D', 'x', 'X', 'y', 'Y']
" Setup yankstack now to make yank/paste related mappings work.
call yankstack#setup()
endif
" Command-line maps to act on the current search (with incsearch). {{{
" E.g. '?foo$m' will move the matched line to where search started.
" Source: http://www.reddit.com/r/vim/comments/1yfzg2/does_anyone_actually_use_easymotion/cfkaxw5
" NOTE: with vim-oblique, '?' and '/' are mapped, and not in getcmdtype().
fun! MyCmdMapNotForColon(from, to, ...)
let init = a:0 ? 0 : 1
if init
exec printf('cnoremap <expr> %s MyCmdMapNotForColon("%s", "%s", 1)',
\ a:from, a:from, a:to)
return
endif
if index([':', '>', '@', '-', '='], getcmdtype()) == 0
return a:from
endif
return a:to
endfun
call MyCmdMapNotForColon('$d', "<CR>:delete<CR>``")
call MyCmdMapNotForColon('$m', "<CR>:move''<CR>")
call MyCmdMapNotForColon('$c', "<CR>:copy''<CR>")
call MyCmdMapNotForColon('$t', "<CR>:t''<CR>") " synonym for :copy
" Allow to quickly enter a single $.
cnoremap $$ $
" }}}
" sneak {{{1
" Overwrite yankstack with sneak maps.
" Ref: https://github.com/maxbrunsfeld/vim-yankstack/issues/39
nmap s <Plug>Sneak_s
nmap S <Plug>Sneak_S
xmap s <Plug>Sneak_s
xmap S <Plug>Sneak_S
omap s <Plug>Sneak_s
omap S <Plug>Sneak_S
" Use streak mode, also for Sneak_f/Sneak_t.
let g:sneak#streak=2
let g:sneak#s_next = 1 " clever-s
let g:sneak#target_labels = "sfjktunbqz/SFKGHLTUNBRMQZ?"
" Replace 'f' with inclusive 1-char Sneak.
nmap f <Plug>Sneak_f
nmap F <Plug>Sneak_F
xmap f <Plug>Sneak_f
xmap F <Plug>Sneak_F
omap f <Plug>Sneak_f
omap F <Plug>Sneak_F
" Replace 't' with exclusive 1-char Sneak.
nmap t <Plug>Sneak_t
nmap T <Plug>Sneak_T
xmap t <Plug>Sneak_t
xmap T <Plug>Sneak_T
omap t <Plug>Sneak_t
omap T <Plug>Sneak_T
" IDEA: just use 'f' for sneak, leaving 's' at its default.
" nmap f <Plug>Sneak_s
" nmap F <Plug>Sneak_S
" xmap f <Plug>Sneak_s
" xmap F <Plug>Sneak_S
" omap f <Plug>Sneak_s
" omap F <Plug>Sneak_S
" }}}1
" GoldenView {{{1
let g:goldenview__enable_default_mapping = 0
let g:goldenview__enable_at_startup = 0
" 1. split to tiled windows
nmap <silent> g<C-L> <Plug>GoldenViewSplit
" " 2. quickly switch current window with the main pane
" " and toggle back
nmap <silent> <F9> <Plug>GoldenViewSwitchMain
nmap <silent> <S-F9> <Plug>GoldenViewSwitchToggle
" " 3. jump to next and previous window
nmap <silent> <C-N> <Plug>GoldenViewNext
nmap <silent> <C-P> <Plug>GoldenViewPrevious
" }}}
" Duplicate a selection in visual mode
vmap D y'>p
" Press Shift+P while in visual mode to replace the selection without
" overwriting the default register
vmap P p :call setreg('"', getreg('0')) <CR>
" This is an alternative that also works in block mode, but the deleted
" text is lost and it only works for putting the current register.
"vnoremap p "_dp
" imap <C-L> <Space>=><Space>
" Toggle settings (see also vim-unimpaired).
" No pastetoggle: use `yo`/`yO` from unimpaired. Triggers also Neovim issue #6716.
" set pastetoggle=<leader>sp
nnoremap <leader>sc :ColorToggle<cr>
nnoremap <leader>sq :QuickfixsignsToggle<cr>
nnoremap <leader>si :IndentGuidesToggle<cr>
" Toggle mouse.
nnoremap <leader>sm :exec 'set mouse='.(&mouse == 'a' ? '' : 'a')<cr>:set mouse?<cr>
" OLD: Ack/Ag setup, handled via ag plugin {{{
" Use Ack instead of Grep when available
" if executable("ack")
" set grepprg=ack\ -H\ --nogroup\ --nocolor\ --ignore-dir=tmp\ --ignore-dir=coverage
" elseif executable("ack-grep")
" set grepprg=ack-grep\ -H\ --nogroup\ --nocolor\ --ignore-dir=tmp\ --ignore-dir=coverage
" else
" this is for Windows/cygwin and to add -H
" '$*' is not passed to the shell, but used by Vim
set grepprg=grep\ -nH\ $*\ /dev/null
" endif
if executable("ag")
let g:ackprg = 'ag --nogroup --nocolor --column'
" command alias, http://stackoverflow.com/a/3879737/15690
" if re-used, use a function
" cnoreabbrev <expr> Ag ((getcmdtype() is# ':' && getcmdline() is# 'Ag')?('Ack'):('Ag'))
endif
" 1}}}
" Automatic line numbers {{{
" NOTE: relativenumber might slow Vim down: https://code.google.com/p/vim/issues/detail?id=311
set norelativenumber
fun! MyAutoSetNumberSettings(...)
if get(w:, 'my_default_number_manually_set')
return
endif
let s:my_auto_number_ignore_OptionSet = 1
if a:0
exec 'setl' a:1
elseif &ft =~# 'qf\|cram\|vader'
setl number
elseif index(['nofile', 'terminal'], &buftype) != -1
\ || index(['help', 'fugitiveblame', 'fzf'], &ft) != -1
\ || bufname("%") =~ '^__'
setl nonumber
elseif winwidth(".") > 90
setl number
else
setl nonumber
endif
unlet s:my_auto_number_ignore_OptionSet
endfun
fun! MySetDefaultNumberSettingsSet()
if !exists('s:my_auto_number_ignore_OptionSet')
" echom "Manually set:" expand("<amatch>").":" v:option_old "=>" v:option_new
let w:my_auto_number_manually_set = 1
endif
endfun
augroup vimrc_number_setup
au!
au VimResized,FileType,BufWinEnter * call MyAutoSetNumberSettings()
if exists('##OptionSet')
au OptionSet number,relativenumber call MySetDefaultNumberSettingsSet()
endif
au CmdwinEnter * call MyAutoSetNumberSettings('number norelativenumber')
augroup END
fun! MyOnVimResized()
noautocmd WindoNodelay call MyAutoSetNumberSettings()
QfResizeWindows
endfun
nnoremap <silent> <c-w>= :wincmd =<cr>:call MyOnVimResized()<cr>
fun! MyWindoNoDelay(range, command)
" 100ms by default!
let s = g:ArgsAndMore_AfterCommand
let g:ArgsAndMore_AfterCommand = ''
call ArgsAndMore#Windo('', a:command)
let g:ArgsAndMore_AfterCommand = s
endfun
command! -nargs=1 -complete=command WindoNodelay call MyWindoNoDelay('', <q-args>)
augroup vimrc_on_resize
au!
au VimResized * WindoNodelay call MyOnVimResized()
augroup END
let &showbreak = '⪠'
set cpoptions+=n " Use line column for wrapped text / &showbreak.
function! CycleLineNr()
" states: [start] => norelative/number => relative/number (=> relative/nonumber) => nonumber/norelative
if exists('+relativenumber')
if &relativenumber
" if &number
" set relativenumber nonumber
" else
set norelativenumber nonumber
" endif
else
if &number
set number relativenumber
if !&number " Older Vim.
set relativenumber
endif
else
" init:
set norelativenumber number
endif
endif
" if &number | set relativenumber | elseif &relativenumber | set norelativenumber | else | set number | endif
else
set number!
endif
call SetNumberWidth()
endfunction
function! SetNumberWidth()
" NOTE: 'numberwidth' will get expanded by Vim automatically to fit the last line
if &number
if has('float')
let &l:numberwidth = float2nr(ceil(log10(line('$'))))
endif
elseif exists('+relativenumber') && &relativenumber
set numberwidth=2
endif
endfun
nnoremap <leader>sa :call CycleLineNr()<CR>
" Toggle numbers, but with relativenumber turned on
fun! ToggleLineNr()
if &number
if exists('+relativenumber')
set norelativenumber
endif
set nonumber
else
if exists('+relativenumber')
set relativenumber
endif
set number
endif
endfun
" map according to unimpaired, mnemonic "a on the left, like numbers".
nnoremap coa :call ToggleLineNr()<cr>
" Allow cursor to move anywhere in all modes.
nnoremap cov :set <C-R>=empty(&virtualedit) ? 'virtualedit=all' : 'virtualedit='<CR><CR>
"}}}
" Completion options.
" Do not use longest, but make Ctrl-P work directly.
set completeopt=menuone
" set completeopt+=preview " experimental
set wildmode=list:longest,list:full
" set complete+=kspell " complete from spell checking
" set dictionary+=spell " very useful (via C-X C-K), but requires ':set spell' once
" NOTE: gets handled dynamically via cursorcross plugin.
" set cursorline
" highlight CursorLine guibg=lightblue ctermbg=lightgray
" via http://www.reddit.com/r/programming/comments/7yk4i/vim_settings_per_directory/c07rk9d
" :au! BufRead,BufNewFile *path/to/project/*.* setlocal noet
" Maps for jk and kj to act as Esc (idempotent in normal mode).
" NOTE: jk moves to the right after Esc, leaving the cursor at the current position.
fun! MyRightWithoutError()
if col(".") < len(getline("."))
normal! l
endif
endfun
inoremap <silent> jk <esc>:call MyRightWithoutError()<cr>
" cno jk <c-c>
ino kj <esc>
" cno kj <c-c>
ino jh <esc>
" Improve the Esc key: good for `i`, does not work for `a`.
" Source: http://vim.wikia.com/wiki/Avoid_the_escape_key#Improving_the_Esc_key
" inoremap <Esc> <Esc>`^
" close tags (useful for html)
" NOTE: not required/used; avoid imap for leader.
" imap <Leader>/ </<C-X><C-O>
nnoremap <Leader>a :Ag<space>
nnoremap <Leader>A :Ag!<space>
" Make those behave like ci' , ci"
nnoremap ci( f(ci(
nnoremap ci{ f{ci{
nnoremap ci[ f[ci[
" NOTE: occupies `c`.
" vnoremap ci( f(ci(
" vnoremap ci{ f{ci{
" vnoremap ci[ f[ci[
" 'goto buffer'; NOTE: overwritten with Unite currently.
nnoremap gb :ls<CR>:b
function! MyIfToVarDump()
normal yyP
s/\mif\>/var_dump/
s/\m\s*\(&&\|||\)\s*/, /ge
s/\m{\s*$/; die();/
endfunction
" Toggle fold under cursor. {{{
fun! MyToggleFold()
if !&foldenable
echom "Folds are not enabled."
endif
let level = foldlevel('.')
echom "Current foldlevel:" level
if level == 0
return
endif
if foldclosed('.') > 0
" Open recursively
norm! zA
else
" Close only one level.
norm! za
endif
endfun
nnoremap <Leader><space> :call MyToggleFold()<cr>
vnoremap <Leader><space> zf
" }}}
" Easily switch between different fold methods {{{
" Source: https://github.com/pydave/daveconfig/blob/master/multi/vim/.vim/bundle/foldtoggle/plugin/foldtoggle.vim
nnoremap <Leader>sf :call ToggleFold()<CR>
function! ToggleFold()
if !exists("b:fold_toggle_options")
" By default, use the main three. I rarely use custom expressions or
" manual and diff is just for diffing.
let b:fold_toggle_options = ["syntax", "indent", "marker"]
if len(&foldexpr)
let b:fold_toggle_options += ["expr"]
endif
endif
" Find the current setting in the list
let i = match(b:fold_toggle_options, &foldmethod)
" Advance to the next setting
let i = (i + 1) % len(b:fold_toggle_options)
let old_method = &l:foldmethod
let &l:foldmethod = b:fold_toggle_options[i]
echom 'foldmethod: ' . old_method . " => " . &l:foldmethod
endfunction
function! FoldParagraphs()
setlocal foldmethod=expr
setlocal fde=getline(v:lnum)=~'^\\s*$'&&getline(v:lnum+1)=~'\\S'?'<1':1
endfunction
command! FoldParagraphs call FoldParagraphs()
" }}}
" Map S-Insert to insert the "*" register literally.
if has('gui')
" nmap <S-Insert> <C-R><C-o>*
" map! <S-Insert> <C-R><C-o>*
nmap <S-Insert> <MiddleMouse>
map! <S-Insert> <MiddleMouse>
endif
" swap previously selected text with currently selected one (via http://vim.wikia.com/wiki/Swapping_characters,_words_and_lines#Visual-mode_swapping)
vnoremap <C-X> <Esc>`.``gvP``P
" Easy indentation in visual mode
" This keeps the visual selection active after indenting.
" Usually the visual selection is lost after you indent it.
"vmap > >gv
"vmap < <gv
" Make `<leader>gp` select the last pasted text
" (http://vim.wikia.com/wiki/Selecting_your_pasted_text).
nnoremap <expr> <leader>gp '`[' . strpart(getregtype(), 0, 1) . '`]'
" select last inserted text
" nnoremap gV `[v`]
nmap gV <leader>gp
if 1 " has('eval') {{{1
" Strip trailing whitespace {{{2
function! StripWhitespace(line1, line2, ...)
let s_report = &report
let &report=0
let pattern = a:0 ? a:1 : '[\\]\@<!\s\+$'
if exists('*winsaveview')
let oldview = winsaveview()
else
let save_cursor = getpos(".")
endif
exe 'keepjumps keeppatterns '.a:line1.','.a:line2.'substitute/'.pattern.'//e'
if exists('oldview')
if oldview != winsaveview()
redraw
echohl WarningMsg | echomsg 'Trimmed whitespace.' | echohl None
endif
call winrestview(oldview)
else
call setpos('.', save_cursor)
endif
let &report = s_report
endfunction
command! -range=% -nargs=0 -bar Untrail keepjumps call StripWhitespace(<line1>,<line2>)
" Untrail, for pastes from tmux (containing border).
command! -range=% -nargs=0 -bar UntrailSpecial keepjumps call StripWhitespace(<line1>,<line2>,'[\\]\@<!\s\+â\?$')
nnoremap <leader>st :Untrail<CR>
" Source/execute current line/selection/operator-pending. {{{
" This uses a temporary file instead of "exec", which does not handle
" statements after "endfunction".
fun! SourceViaFile() range
let tmpfile = tempname()
call writefile(getbufline(bufnr('%'), a:firstline, a:lastline), tmpfile)
exe "source" tmpfile
if &verbose
echom "Sourced ".(a:lastline - a:firstline + 1)." lines."
endif
endfun
command! -range SourceThis <line1>,<line2>call SourceViaFile()
map <Leader>< <Plug>(operator-source)
nnoremap <Leader><< :call SourceViaFile()<cr>
if &rtp =~ '\<operator-user\>'
call operator#user#define('source', 'Op_source_via_file')
" call operator#user#define_ex_command('source', 'SourceThis')
function! Op_source_via_file(motion_wiseness)
" execute (line("']") - line("'[") + 1) 'wincmd' '_'
'[,']call SourceViaFile()
endfunction
endif
" }}}
" Shortcut for <C-r>= in cmdline.
fun! RR(...)
return call(ProjectRootGuess, a:000)
endfun
command! RR ProjectRootLCD
command! RRR ProjectRootCD
" Follow symlink and lcd to root.
fun! MyLCDToProjectRoot()
let oldcwd = getcwd()
+ let oldldir = haslocaldir()
+ let oldtdir = haslocaldir(-1)
FollowSymlink
- ProjectRootLCD
- if oldcwd != getcwd()
- echom "lcd:" oldcwd "=>" getcwd()
+ call projectroot#cd('', a:cd)
+ if oldcwd != getcwd() || oldldir != haslocaldir() || oldtdir != haslocaldir(-1)
+ echom a:cd.' '.fnamemodify(getcwd(), ':~')
+ \ .' (from '.(oldldir ? 'local' : oldtdir ? 'tab-local' : 'global')
+ \ .(oldcwd != getcwd() ? ' '.fnamemodify(oldcwd, ':~') : '').')'
endif
endfun
-nnoremap <silent> <Leader>fr :call MyLCDToProjectRoot()<cr>
+nnoremap <silent> <Leader>cdr :call MyCDToProjectRoot('lcd')<cr>
+nnoremap <silent> <Leader>cdR :call MyCDToProjectRoot('tcd')<cr>
+" Change to current file's dir
+nnoremap <Leader>cdf :lcd <C-R>=expand('%:p:h')<CR><CR>
" Toggle pattern (typically a char) at the end of line(s). {{{2
function! MyToggleLastChar(pat)
let view = winsaveview()
try
keepjumps keeppatterns exe 's/\([^'.escape(a:pat,'/').']\)$\|^$/\1'.escape(a:pat,'/').'/'
catch /^Vim\%((\a\+)\)\=:E486: Pattern not found/
keepjumps keeppatterns exe 's/'.escape(a:pat, '/').'$//'
finally
call winrestview(view)
endtry
endfunction
if has('vim_starting')
noremap <unique> <Leader>,; :call MyToggleLastChar(';')<cr>
noremap <unique> <Leader>,: :call MyToggleLastChar(':')<cr>
noremap <unique> <Leader>,, :call MyToggleLastChar(',')<cr>
noremap <unique> <Leader>,. :call MyToggleLastChar('.')<cr>
noremap <unique> <Leader>,qa :call MyToggleLastChar(' # noqa')<cr>
endif
" use 'en_us' also to work around matchit considering 'en' as 'endif'
set spl=de,en_us
" Toggle spellang: de => en => de,en
fun! MyToggleSpellLang()
if &spl == 'de,en'
set spl=en
elseif &spl == 'en'
set spl=de
else
set spl=de,en
endif
echo "Set spl to ".&spl
endfun
nnoremap <Leader>ss :call MyToggleSpellLang()<cr>
" Grep in the current (potential unsaved) buffer {{{2
" NOTE: obsolete with Unite.
command! -nargs=1 GrepCurrentBuffer call GrepCurrentBuffer('<args>')
fun! GrepCurrentBuffer(q)
let save_cursor = getpos(".")
let save_errorformat = &errorformat
try
set errorformat=%f:%l:%m
cexpr []
exe 'g/'.escape(a:q, '/').'/caddexpr expand("%") . ":" . line(".") . ":" . getline(".")'
cw
finally
call setpos('.', save_cursor)
let &errorformat = save_errorformat
endtry
endfunction
" nnoremap <leader><space> :GrepCurrentBuffer <C-r><C-w><cr>
" Commands to disable (and re-enable) all other tests in the current file. {{{2
command! DisableOtherTests call DisableOtherTests()
fun! DisableOtherTests()
let save_cursor = getpos(".")
try
%s/function test_/function ttest_/
call setpos('.', save_cursor)
call search('function ttest_', 'b')
normal wx
finally
call setpos('.', save_cursor)
endtry
endfun
command! EnableAllTests call EnableAllTests()
fun! EnableAllTests()
let save_cursor = getpos(".")
try
%s/function ttest_/function test_/
finally
call setpos('.', save_cursor)
endtry
endfun
" Twiddle case of chars / visual selection. {{{2
" source http://vim.wikia.com/wiki/Switching_case_of_characters
function! TwiddleCase(str)
if a:str ==# toupper(a:str)
let result = tolower(a:str)
elseif a:str ==# tolower(a:str)
let result = substitute(a:str,'\(\<\w\+\>\)', '\u\1', 'g')
else
let result = toupper(a:str)
endif
return result
endfunction
vnoremap ~ ygv"=TwiddleCase(@")<CR>Pgv
" }}}2
" Exit if the last window is a controlling one (NERDTree, qf). {{{2
" Note: vim-qf has something similar (but simpler).
function! s:QuitIfOnlyControlWinLeft()
if winnr("$") != 1
return
endif
" Alt Source: https://github.com/scrooloose/nerdtree/issues/21#issuecomment-3348390
" autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif
if (exists("t:NERDTreeBufName") && bufwinnr(t:NERDTreeBufName) != -1)
\ || &buftype == 'quickfix'
" NOTE: problematic with Unite's directory, when opening a file:
" :Unite from startify, then quitting Unite quits Vim; also with TMRU from
" startify.
" \ || &ft == 'startify'
q
endif
endfunction
augroup my_QuitIfOnlyControlWinLeft
au!
au BufEnter * nested call s:QuitIfOnlyControlWinLeft()
augroup END
" }}}2
" Check for file modifications automatically
" (current buffer only)
" Use :NoAutoChecktime to disable it (uses b:autochecktime)
fun! MyAutoCheckTime()
" only check timestamp for normal files
if &buftype != '' | return | endif
if ! exists('b:autochecktime') || b:autochecktime
checktime %
let b:autochecktime = 1
endif
endfun
augroup MyAutoChecktime
au!
" NOTE: nested is required for Neovim to trigger FileChangedShellPost
" autocommand with :checktime.
au FocusGained,BufEnter,CursorHold,InsertEnter * nested call MyAutoCheckTime()
augroup END
command! NoAutoChecktime let b:autochecktime=0
command! ToggleAutoChecktime let b:autochecktime=!get(b:, 'autochecktime', 0) | echom "b:autochecktime:" b:autochecktime
" vcscommand: only used as lib for detection (e.g. with airline). {{{1
" Setup b:VCSCommandVCSType.
function! SetupVCSType()
try
call VCSCommandGetVCSType(bufnr('%'))
catch /No suitable plugin/
endtry
endfunction
" do not call it automatically for now: vcscommands behaves weird (changing
" dirs), and slows simple scrolling (?) down (that might be quickfixsigns
" though)
if exists("*VCSCommandVCSType")
"au BufRead * call SetupVCSType()
endif
let g:VCSCommandDisableMappings = 1
" }}}1
" Open Windows explorer and select current file
if executable('explorer.exe')
command! Winexplorer :!start explorer.exe /e,/select,"%:p:gs?/?\\?"
endif
" do not pick last item automatically (non-global: g:tmru_world.tlib_pick_last_item)
let g:tlib_pick_last_item = 1
let g:tlib_inputlist_match = 'cnf'
let g:tmruSize = 2000
let g:tmru_resolve_method = '' " empty: ask, 'read' or 'write'.
let g:tlib#cache#purge_days = 365
let g:tmru_world = {}
let g:tmru_world.cache_var = 'g:tmru_cache'
let g:tmru#drop = 0 " do not `:drop` to files in existing windows. XXX: should use/follow &switchbuf maybe?! XXX: not documented
" Easytags
let g:easytags_on_cursorhold = 0 " disturbing, at least on work machine
let g:easytags_cmd = 'ctags'
let g:easytags_suppress_ctags_warning = 1
" let g:easytags_dynamic_files = 1
let g:easytags_resolve_links = 1
let g:easytags_async = 1
let g:detectindent_preferred_indent = 2 " used for sw and ts if only tabs
let g:detectindent_preferred_expandtab = 1
let g:detectindent_min_indent = 2
let g:detectindent_max_indent = 4
let g:detectindent_max_lines_to_analyse = 100
" command-t plugin {{{
let g:CommandTMaxFiles=50000
let g:CommandTMaxHeight=20
" NOTE: find finder does not skip g:CommandTWildIgnore for scanning!
" let g:CommandTFileScanner='find'
if has("autocmd") && exists(":CommandTFlush") && has("ruby")
" this is required for Command-T to pickup the setting(s)
au VimEnter * CommandTFlush
endif
if (has("gui_running"))
" use Alt-T in GUI mode
map <A-t> :CommandT<CR>
endif
map <leader>tt :CommandT<CR>
map <leader>t. :execute "CommandT ".expand("%:p:h")<cr>
map <leader>t :CommandT<space>
map <leader>tb :CommandTBuffer<CR>
" }}}
" Setup completefunc / base completion. {{{
" (used as fallback (manual)).
" au FileType python set completefunc=eclim#python#complete#CodeComplete
if !s:use_ycm && has("autocmd") && exists("+omnifunc")
augroup vimrc_base_omnifunc
au!
if &rtp =~ '\<eclim\>'
au FileType * if index(
\ ["php", "javascript", "css", "python", "xml", "java", "html"], &ft) != -1 |
\ let cf="eclim#".&ft."#complete#CodeComplete" |
\ exec 'setlocal omnifunc='.cf |
\ endif
" function! eclim#php#complete#CodeComplete(findstart, base)
" function! eclim#javascript#complete#CodeComplete(findstart, base)
" function! eclim#css#complete#CodeComplete(findstart, base)
" function! eclim#python#complete#CodeComplete(findstart, base) " {{{
" function! eclim#xml#complete#CodeComplete(findstart, base)
" function! eclim#java#complete#CodeComplete(findstart, base) " {{{
" function! eclim#java#ant#complete#CodeComplete(findstart, base)
" function! eclim#html#complete#CodeComplete(findstart, base)
else
au FileType css setlocal omnifunc=csscomplete#CompleteCSS
au FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags
au FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS
au FileType python setlocal omnifunc=pythoncomplete#Complete
au FileType xml setlocal omnifunc=xmlcomplete#CompleteTags
"au FileType ruby setlocal omnifunc=rubycomplete#Complete
endif
au FileType htmldjango set omnifunc=htmldjangocomplete#CompleteDjango
" Use syntaxcomplete, if there is no better omnifunc.
autocmd Filetype *
\ if &omnifunc == "" |
\ setlocal omnifunc=syntaxcomplete#Complete |
\ endif
augroup END
endif
" }}}
" supertab.vim {{{
if &rtp =~ '\<supertab\>'
" "context" appears to trigger path/file lookup?!
" let g:SuperTabDefaultCompletionType = 'context'
" let g:SuperTabContextDefaultCompletionType = "<c-p>"
" let g:SuperTabContextTextFileTypeExclusions =
" \ ['htmldjango', 'htmljinja', 'javascript', 'sql']
" auto select the first result when using 'longest'
"let g:SuperTabLongestHighlight = 1 " triggers bug with single match (https://github.com/ervandew/supertab/commit/e026bebf1b7113319fc7831bc72d0fb6e49bd087#commitcomment-297471)
" let g:SuperTabLongestEnhanced = 1 " involves mappings; requires
" completeopt =~ longest
let g:SuperTabClosePreviewOnPopupClose = 1
let g:SuperTabNoCompleteAfter = ['^', '\s']
" map <c-space> to <c-p> completion (useful when supertab 'context'
" defaults to something else).
" imap <nul> <c-r>=SuperTabAlternateCompletion("\<lt>c-p>")<cr>
" Setup completion with SuperTab: default to omnifunc (YouCompleteMe),
" then completefunc.
if s:use_ycm
" Call YouCompleteMe always (semantic).
" Let &completefunc untouched (eclim).
" Use autocommand to override any other automatic setting from filetypes.
" Use SuperTab chaining to fallback to "<C-p>".
" autocmd FileType *
" \ let g:ycm_set_omnifunc = 0 |
" \ set omnifunc=youcompleteme#OmniComplete
" let g:SuperTabDefaultCompletionType = "<c-x><c-o>"
fun! CompleteViaSuperTab(findstart, base)
let old = g:ycm_min_num_of_chars_for_completion
" 0 would trigger/force semantic completion (results in everything after
" a dot also).
let g:ycm_min_num_of_chars_for_completion = 1
let r = youcompleteme#Complete(a:findstart, a:base)
let g:ycm_min_num_of_chars_for_completion = old
return r
endfun
" completefunc is used by SuperTab's chaining.
" let ycm_set_completefunc = 0
autocmd FileType *
\ call SuperTabChain("CompleteViaSuperTab", "<c-p>") |
\ call SuperTabSetDefaultCompletionType("<c-x><c-u>") |
" Let SuperTab trigger YCM always.
" call SuperTabChain('youcompleteme#OmniComplete', "<c-p>") |
" let g:SuperTabChain = ['youcompleteme#Complete', "<c-p>"]
" set completefunc=SuperTabCodeComplete
" let g:SuperTabDefaultCompletionType = "<c-x><c-u>"
" autocmd FileType *
" \ call SuperTabChain('youcompleteme#Complete', "<c-p>") |
" \ call SuperTabSetDefaultCompletionType("<c-x><c-u>") |
else
let g:SuperTabDefaultCompletionType = "<c-p>"
autocmd FileType *
\ if &omnifunc != '' |
\ call SuperTabChain(&omnifunc, "<c-p>") |
\ call SuperTabSetDefaultCompletionType("<c-x><c-u>") |
\ elseif &completefunc != '' |
\ call SuperTabChain(&completefunc, "<c-p>") |
\ call SuperTabSetDefaultCompletionType("<c-x><c-u>") |
\ endif
endif
endif
" }}}
let g:LustyExplorerSuppressRubyWarning = 1 " suppress warning when vim-ruby is not installed
let g:EclimLargeFileEnabled = 0
let g:EclimCompletionMethod = 'completefunc' " Default, picked up via SuperTab.
" let g:EclimLogLevel = 6
" if exists(":EclimEnable")
" au VimEnter * EclimEnable
" endif
let g:EclimShowCurrentError = 0 " can be really slow, when used with PHP omnicompletion. I am using Syntastic anyway.
let g:EclimSignLevel = 0
let g:EclimLocateFileNonProjectScope = 'ag'
" Disable eclim's validation, prefer Syntastic.
" NOTE: patch pending to do so automatically (in eclim).
" does not work as expected, ref: https://github.com/ervandew/eclim/issues/199
let g:EclimFileTypeValidate = 0
" Disable HTML indenting via eclim, ref: https://github.com/ervandew/eclim/issues/332.
let g:EclimHtmlIndentDisabled = 1
let g:EclimHtmldjangoIndentDisabled = 1
" lua {{{
let g:lua_check_syntax = 0 " done via syntastic
let g:lua_define_omnifunc = 0 " must be enabled also (g:lua_complete_omni=1, but crashes Vim!)
let g:lua_complete_keywords = 0 " interferes with YouCompleteMe
let g:lua_complete_globals = 0 " interferes with YouCompleteMe?
let g:lua_complete_library = 0 " interferes with YouCompleteMe
let g:lua_complete_dynamic = 0 " interferes with YouCompleteMe
let g:lua_complete_omni = 0 " Disabled by default. Likely to crash Vim!
let g:lua_define_completion_mappings = 0
" }}}
" Prepend <leader> to visualctrlg mappings.
let g:visualctrg_no_default_keymappings = 1
silent! vmap <unique> <Leader><C-g> <Plug>(visualctrlg-briefly)
silent! vmap <unique> <Leader>g<C-g> <Plug>(visualctrlg-verbosely)
" Toggle quickfix window, using <Leader>qq. {{{2
" Based on: http://vim.wikia.com/wiki/Toggle_to_open_or_close_the_quickfix_window
nnoremap <Leader>qq :QFix<CR>
nnoremap <Leader>cc :QFix<CR>
command! -bang -nargs=? QFix call QFixToggle(<bang>0)
function! QFixToggle(forced)
if exists("t:qfix_buf") && bufwinnr(t:qfix_buf) != -1 && a:forced == 0
cclose
else
copen
let t:qfix_buf = bufnr("%")
endif
endfunction
" Used to track manual opening of the quickfix, e.g. via `:copen`.
augroup QFixToggle
au!
au BufWinEnter quickfix let g:qfix_buf = bufnr("%")
augroup END
" 2}}}
fun! MyHandleWinClose(event)
if get(t:, '_win_count', 0) > winnr('$')
" NOTE: '<nomodeline>' prevents the modelines to get applied, even if
" there are no autocommands being executed!
" That would cause folds to collaps after closing another window and
" coming back to e.g. this vimrc.
doautocmd <nomodeline> User MyAfterWinClose
endif
let t:_win_count = winnr('$')
endfun
augroup vimrc_user
au!
for e in ['BufWinEnter', 'WinEnter', 'BufDelete', 'BufWinLeave']
exec 'au' e '* call MyHandleWinClose("'.e.'")'
endfor
augroup END
endif " 1}}} eval guard
" Mappings {{{1
" Save.
nnoremap <silent> <C-s> :up<CR>:if &diff \| diffupdate \| endif<cr>
imap <C-s> <Esc><C-s>
" Swap n_CTRL-Z and n_CTRL-Y (qwertz layout; CTRL-Z should be next to CTRL-U).
nnoremap <C-z> <C-y>
nnoremap <C-y> <C-z>
" map! <C-Z> <C-O>:stop<C-M>
" zi: insert one char
" map zi i$<ESC>r
" defined in php-doc.vim
" nnoremap <Leader>d :call PhpDocSingle()<CR>
nnoremap <Leader>n :NERDTree<space>
nnoremap <Leader>n. :execute "NERDTree ".expand("%:p:h")<cr>
nnoremap <Leader>nb :NERDTreeFromBookmark<space>
nnoremap <Leader>nn :NERDTreeToggle<cr>
nnoremap <Leader>no :NERDTreeToggle<space>
nnoremap <Leader>nf :NERDTreeFind<cr>
nnoremap <Leader>nc :NERDTreeClose<cr>
nnoremap <S-F1> :tab<Space>:help<Space>
" ':tag {ident}' - difficult on german keyboard layout and not working in gvim/win32
nnoremap <F2> g<C-]>
" expand abbr (insert mode and command line)
noremap! <F2> <C-]>
nnoremap <F3> :if exists('g:tmru#world')<cr>:let g:tmru#world.restore_from_cache = []<cr>:endif<cr>:TRecentlyUsedFiles<cr>
nnoremap <S-F3> :if exists('g:tmru#world')<cr>:let g:tmru#world.restore_from_cache = ['filter']<cr>:endif<cr>:TRecentlyUsedFiles<cr>
" XXX: mapping does not work (autoclose?!)
" noremap <F3> :CtrlPMRUFiles
fun! MyF5()
if &diff
diffupdate
else
e
endif
endfun
noremap <F5> :call MyF5()<cr>
" noremap <F11> :YRShow<cr>
" if has('gui_running')
" map <silent> <F11> :call system("wmctrl -ir " . v:windowid . " -b toggle,fullscreen")<CR>
" imap <silent> <F11> <Esc><F11>a
" endif
" }}}
" tagbar plugin
nnoremap <silent> <F8> :TagbarToggle<CR>
nnoremap <silent> <Leader><F8> :TagbarOpenAutoClose<CR>
" VimFiler {{{2
let g:vimfiler_as_default_explorer = 1
let g:vimfiler_ignore_filters = ['matcher_ignore_wildignore']
" Netrw {{{2
" Short-circuit detection, which might be even wrong.
let g:netrw_browsex_viewer = 'open-in-running-browser'
" NERDTree {{{2
" Show hidden files *except* the known temp files, system files & VCS files
let NERDTreeHijackNetrw = 0
let NERDTreeShowHidden = 1
let NERDTreeIgnore = []
for suffix in split(&suffixes, ',')
let NERDTreeIgnore += [ escape(suffix, '.~') . '$' ]
endfor
let NERDTreeIgnore += ['^\.bundle$', '^\.bzr$', '^\.git$', '^\.hg$', '^\.sass-cache$', '^\.svn$', '^\.$', '^\.\.$', '^Thumbs\.db$']
let NERDTreeIgnore += ['__pycache__', '.ropeproject']
" }}}
" TODO
" noremap <Up> gk
" noremap <Down> gj
" (Cursor keys should be consistent between insert and normal mode)
" slow!
" inoremap <Up> <C-O>:normal gk<CR>
" inoremap <Down> <C-O>:normal gj<CR>
"
" j,k move by screen line instead of file line.
" nnoremap j gj
" nnoremap k gk
nnoremap <Down> gj
nnoremap <Up> gk
" inoremap <Down> <C-o>gj
" inoremap <Up> <C-o>gk
" XXX: does not keep virtual column! Also adds undo points!
" inoremap <expr> <Down> pumvisible() ? "\<C-n>" : "\<C-o>gj"
" inoremap <expr> <Up> pumvisible() ? "\<C-p>" : "\<C-o>gk"
" Make C-BS and C-Del work like they do in most text editors for the sake of muscle memory {{{2
imap <C-BS> <C-W>
imap <C-Del> <C-O>dw
imap <C-S-Del> <C-O>dW
" Map delete to 'delete to black hole register' (experimental, might use
" `d` instead)
" Join lines, if on last column, delete otherwise (used in insert mode)
" NOTE: de-activated: misbehaves with '""' at end of line (autoclose),
" and deleting across lines works anyway. The registers also do not
" get polluted.. do not remember why I came up with it...
" function! MyDelAcrossEOL()
" echomsg col(".") col("$")
" if col(".") == col("$")
" " XXX: found no way to use '_' register
" call feedkeys("\<Down>\<Home>\<Backspace>")
" else
" normal! "_x
" endif
" return ''
" endfunction
" noremap <Del> "_<Del>
" inoremap <Del> <C-R>=MyDelAcrossEOL()<cr>
" vnoremap <Del> "_<Del>
" " Vaporize delete without overwriting the default register. {{{1
" nnoremap vd "_d
" xnoremap x "_d
" nnoremap vD "_D
" }}}
" Replace without yank {{{
" Source: https://github.com/justinmk/config/blob/master/.vimrc#L743
func! s:replace_without_yank(type)
let sel_save = &selection
|
blueyed/dotfiles | c5a5ca9bccd6548be6378a7497a3a612a82a69c3 | set FZF_DEFAULT_OPTS in a single place (needs no variant) | diff --git a/usr/bin/sh-setup-x-theme b/usr/bin/sh-setup-x-theme
index 6587fa8..93b630a 100755
--- a/usr/bin/sh-setup-x-theme
+++ b/usr/bin/sh-setup-x-theme
@@ -1,268 +1,259 @@
#!/bin/sh
#
# Change X/xrdb theme between light/dark (solarized).
#
# This script's output is meant to be eval'd.
# It is used from my Zsh theme and in ~/.xsessionrc.
# See the theme_variant function for a wrapper arount it.
#
# $1: theme to use: auto/light/dark.
# $2: "save" to save the value to the config file.
#
# MY_X_THEME_VARIANT: set to the effective variant: "light" or "dark".
#
# TODO: query urxvt's current bg and use it for dircolors.
# see ~/bin/query-urxvt and ~/bin/xterm-bg.
config_file=~/.config/x-theme-variant
# set -x
# date >>/tmp/debug-sh-setup-x-theme.log
# exec 2>>/tmp/debug-sh-setup-x-theme.log
debug() {
if [ -n "$DEBUG" ]; then
echo "$(date +%FT%T) [sh-setup-x-theme] $*" >&2
fi
# echo "$(date +%FT%T) [sh-setup-x-theme:$$:$(ps -o cmd= $$)] $@" >> /tmp/debug-sh-setup-x-theme.log
}
get_variant_from_config() {
if [ -n "$TMUX" ]; then
tmux_variant="$(tmux show-env MY_X_THEME_VARIANT 2>/dev/null | cut -d= -f 2)"
config_variant="$tmux_variant"
debug "variant from tmux: $config_variant"
fi
if [ -z "$config_variant" ]; then
if [ -f $config_file ]; then
config_variant=$(cat $config_file)
debug "variant from cfg: $config_variant"
else
debug "Config file ($config_file) does not exist."
fi
if [ -z "$config_variant" ]; then
config_variant=auto
debug "variant from fallback: $config_variant"
fi
fi
}
# Init once and export the value.
# This gets used in Vim to auto-set the background, too.
# Handle options, in this case it does not / should not get sourced.
while [ "${1#-*}" != "$1" ]; do
case "$1" in
-d ) DEBUG=1 ;;
-f ) FORCE=1 ;;
-s ) SHELL_ONLY=1 ;;
-q ) # Query/info.
echo "Current theme variant: MY_X_THEME_VARIANT=$MY_X_THEME_VARIANT."
echo "BASE16_THEME: $BASE16_THEME."
get_variant_from_config
if [ -n "$tmux_variant" ]; then
echo "Theme from tmux: $config_variant."
else
echo "Theme from config: $config_variant."
fi
echo "Use 'auto', 'dark' or 'light' to change it."
exit
;;
*) echo "Unknown option: $1"; exit 1; ;;
esac
shift
done
debug "RUN: $0 $*"
given_variant=$1
debug "Requested variant: $given_variant"
# No argument provided: read config/env.
if [ -z "$given_variant" ]; then
get_variant_from_config
given_variant="$config_variant"
SAVE_VARIANT=0
else
FORCE=1
if [ "$SHELL_ONLY" != 1 ]; then
SAVE_VARIANT=1
fi
fi
variant="$given_variant"
debug "given_variant: $given_variant"
# Refresh terminal stuff (base16, dircolors) in a new urxvt instance.
TTY="$(tty)"
if [ "$FORCE" = 1 ] || [ "$_MY_X_THEME_VARIANT_TTY" != "$TTY" ]; then
REFRESH_TERM=1
fi
echo "export _MY_X_THEME_VARIANT_TTY=\$TTY"
# Get auto-theme from get-daytime-period for "auto",
# and validate value.
case $variant in
auto)
dt_period="$(~/.dotfiles/usr/bin/get-daytime-period)"
if [ "$dt_period" = 'Daytime' ]; then
variant=light
elif [ -n "$dt_period" ]; then
variant=dark
else
echo "get-daytime-period failed. Using 'dark' variant." >&2
variant=dark
fi
debug "=> variant: $variant"
;;
light|dark ) ;;
* ) echo "Invalid variant: $variant" >&2; exit 64
esac
# curbg="$(xrdb -query|sed -n -e '/^\*background:/ {p;q}' | tr -d '[:space:]' | cut -f2 -d:)"
# if [[ $curbg == '#fdf6e3' ]]; then
# if [[ $variant == "dark" ]]; then
# # xrdb -DSOLARIZED_DARK ~/.Xresources
# xrdb -merge ~/.dotfiles/lib/solarized-xresources/Xresources.dark
# changed_xrdb=1
# fi
# elif [[ $variant == "light" ]]; then
# # xrdb -DSOLARIZED_LIGHT ~/.Xresources
# xrdb -merge ~/.dotfiles/lib/solarized-xresources/Xresources.light
# changed_xrdb=1
# fi
if [ -n "$DISPLAY" ] && [ "$USER" != "root" ] && [ "$SHELL_ONLY" != 1 ] \
&& [ -z "$TMUX" ] && hash xrdb 2>/dev/null; then
# Query "mythemevariant" resource, used to hold the current state.
# Unset by default in ~/.Xresources.
cur_xrdb_theme="$(xrdb -query|sed -n -E -e '/mythemevariant:\t/ {s/.*:\t//p;q}')"
debug "cur_xrdb_theme=$cur_xrdb_theme"
if [ "$FORCE" = 1 ] || [ "$cur_xrdb_theme" != "$variant" ]; then
if [ "$variant" = dark ]; then
xrdb -DSOLARIZED_DARK -I"$HOME" -merge ~/.Xresources
elif [ "$variant" = light ]; then
xrdb -DSOLARIZED_LIGHT -I"$HOME" -merge ~/.Xresources
fi
echo "mythemevariant: $variant" | xrdb -merge
echo "Changed X/xrdb theme variant to $variant." >&2
fi
fi
DIRCOLORS_FILE=~/.dotfiles/lib/LS_COLORS/LS_COLORS
# Setup dircolors once.
if [ -n "$DIRCOLORS_FILE" ] \
&& ([ "$REFRESH_TERM" = 1 ] || [ "$DIRCOLORS_SETUP" != "$DIRCOLORS_FILE" ]); then
debug "Setting up DIRCOLORS_FILE=$DIRCOLORS_FILE"
debug "DIRCOLORS_SETUP=$DIRCOLORS_SETUP"
if [ -n "$DIRCOLORS_SETUP" ]; then
debug "Adjusting dircolors for variant=$variant."
else
debug "TODO: dircolors only during .xresources ($(basename "$0"))."
fi
# debug "running: dircolors -b $DIRCOLORS_FILE"
echo "$(dircolors -b $DIRCOLORS_FILE);"
echo "export DIRCOLORS_SETUP=$DIRCOLORS_FILE"
fi
# Used in ~/.vimrc.
echo "export MY_X_THEME_VARIANT=$variant;"
-# Configure colors for fzf.
-if hash fzf 2>/dev/null; then
- if [ -z "$_FZF_DEFAULT_OPTS_BASE" ]; then
- echo "export _FZF_DEFAULT_OPTS_BASE=\"\$FZF_DEFAULT_OPTS\""
- fi
- [ $variant = "light" ] && bg=21 || bg=18
- echo "export FZF_DEFAULT_OPTS='$_FZF_DEFAULT_OPTS_BASE --color 16,bg+:$bg'"
-fi
-
# Update tmux env, after sending escape codes eventually, which the
# "tmux display" might prevent to work correctly (?!). (might be obsolete)
# This also inits it initially.
if [ -n "$TMUX" ]; then # && [ "$SHELL_ONLY" != 1 ]; then
COLORS="$(tput colors)"
if [ "$COLORS" -lt 16 ]; then
debug "SKIP tmux: not enough colors ($COLORS are available (via 'tput colors'); TERM=$TERM)."
else
debug "tmux_variant: $tmux_variant"
tmux_tmp_conf="$(mktemp)"
if [ -z "$tmux_variant" ]; then
echo "echo 'theme-variant: setting tmux env: $variant.'"
tmux_session="$(tmux display-message -p '#S')"
tmux_windows=
for w in $(tmux list-windows -t "$tmux_session" -F '#{window_id}'); do
sed -n "s/ -g//; /^set /p; /^if/p; s/^\s*setw /\0-t $w /p" "$HOME/.dotfiles/lib/tmux-colors-solarized/tmuxcolors-$variant.conf" >> "$tmux_tmp_conf"
done
else
# echo "echo 'theme-variant: styling new tmux window ($variant).'"
tmux_windows=""
sed -n "s/ -g//; /^set /p; /^if/p; s/^\s*setw /\0$tmux_windows/p" "$HOME/.dotfiles/lib/tmux-colors-solarized/tmuxcolors-$variant.conf" > "$tmux_tmp_conf"
fi
echo "tmux set-env MY_X_THEME_VARIANT $variant"
echo "tmux source $tmux_tmp_conf"
echo "rm '$tmux_tmp_conf'"
fi
fi
# Setup base16-shell.
if [ "$REFRESH_TERM" = 1 ] || [ "${BASE16_THEME##*.}" != "$variant" ]; then
if [ "${TERM%%-*}" = 'linux' ]; then
echo "Skipping base16-shell with TERM=linux." >&2
else
echo "base16_theme solarized.$variant"
if [ -n "$TMUX" ]; then
# shellcheck disable=SC2016
echo 'tmux set-environment BASE16_THEME "$BASE16_THEME"'
fi
fi
fi
if [ "$MY_X_THEME_VARIANT" != "$variant" ] || [ "$FORCE" = 1 ]; then
if [ "${COLORTERM#rxvt}" != "$COLORTERM" ]; then
if [ "$variant" = light ]; then
escape_codes='\033]11;#fdf6e3\007 \033]10;#657b83\007 \033]12;#586e75\007 \033]13;#586e75\007 \033]708;#fdf6e3\007 \033]709;#fdf6e3\007'
else
escape_codes='\033]11;#002b36\007 \033]10;#839496\007 \033]12;#93a1a1\007 \033]13;#93a1a1\007 \033]708;#002b36\007 \033]709;#657b83\007'
fi
cat <<EOF
_printf_for_tmux() {
local i="\$1"
if [ -n "\$TMUX" ]; then
i="\\ePtmux;\\e\$i\\e\\\\"
fi
printf '%b' "\$i"
}
EOF
for i in $escape_codes; do
echo "_printf_for_tmux '$i'"
done
fi
fi
if [ "$SAVE_VARIANT" = 1 ]; then
# Save given value.
case $variant in
auto)
if [ -n "$TMUX" ]; then
tmux set-env -u MY_X_THEME_VARIANT
elif [ -f "$config_file" ]; then
rm "$config_file"
fi
;;
light|dark)
if [ -n "$TMUX" ]; then
tmux set-env MY_X_THEME_VARIANT "$variant"
echo "Saved variant=$1 in tmux." >&2
else
echo "$1" > "$config_file"
echo "Saved variant=$1." >&2
fi
;;
* ) echo "Invalid variant: $variant" >&2; exit 64
esac
fi
diff --git a/vimrc b/vimrc
index 65a4d90..20163de 100644
--- a/vimrc
+++ b/vimrc
@@ -1039,1025 +1039,1024 @@ let g:UltiSnips.UltiSnips_ft_filter = {
\ }
let g:UltiSnips.snipmate_ft_filter = {
\ 'default' : {'filetypes': ["FILETYPE", "_"] },
\ 'html' : {'filetypes': ["html", "javascript", "_"] },
\ 'python' : {'filetypes': ["python", "django", "_"] },
\ 'htmldjango' : {'filetypes': ["python", "django", "html", "_"] },
\ }
"\ 'html' : {'filetypes': ["html", "javascript"], 'dir-regex': '[._]vim$' },
if has('win32') || has('win64')
" replace ~/vimfiles with ~/.vim in runtimepath
" let &runtimepath = join( map( split(&rtp, ','), 'substitute(v:val, escape(expand("~/vimfiles"), "\\"), escape(expand("~/.vim"), "\\"), "g")' ), "," )
let &runtimepath = substitute(&runtimepath, '\('.escape($HOME, '\').'\)vimfiles\>', '\1.vim', 'g')
endif
" Sparkup (insert mode) maps. Default: <c-e>/<c-n>, both used by Vim.
let g:sparkupExecuteMapping = '<Leader><c-e>'
" '<c-n>' by default!
let g:sparkupNextMapping = '<Leader><c-n>'
" Syntastic {{{2
let g:syntastic_enable_signs=1
let g:syntastic_check_on_wq=1 " Only for active filetypes.
let g:syntastic_auto_loc_list=1
let g:syntastic_always_populate_loc_list=1
" let g:syntastic_echo_current_error=0 " TEST: faster?!
let g:syntastic_mode_map = {
\ 'mode': 'passive',
\ 'active_filetypes': ['ruby', 'php', 'lua', 'python', 'sh', 'zsh'],
\ 'passive_filetypes': [] }
let g:syntastic_error_symbol='â'
let g:syntastic_warning_symbol='â '
let g:syntastic_aggregate_errors = 0
let g:syntastic_python_checkers = ['python', 'frosted', 'flake8', 'pep8']
" let g:syntastic_php_checkers = ['php']
let g:syntastic_loc_list_height = 1 " handled via qf-resize autocommand
" See 'syntastic_quiet_messages' and 'syntastic_<filetype>_<checker>_quiet_messages'
" let g:syntastic_quiet_messages = {
" \ "level": "warnings",
" \ "type": "style",
" \ "regex": '\m\[C03\d\d\]',
" \ "file": ['\m^/usr/include/', '\m\c\.h$'] }
let g:syntastic_quiet_messages = { "level": [], "type": ["style"] }
fun! SyntasticToggleQuiet(k, v, scope)
let varname = a:scope."syntastic_quiet_messages"
if !exists(varname) | exec 'let '.varname.' = { "level": [], "type": ["style"] }' | endif
exec 'let idx = index('.varname.'[a:k], a:v)'
if idx == -1
exec 'call add('.varname.'[a:k], a:v)'
echom 'Syntastic: '.a:k.':'.a:v.' disabled (filtered).'
else
exec 'call remove('.varname.'[a:k], idx)'
echom 'Syntastic: '.a:k.':'.a:v.' enabled (not filtered).'
endif
endfun
command! SyntasticToggleWarnings call SyntasticToggleQuiet('level', 'warnings', "g:")
command! SyntasticToggleStyle call SyntasticToggleQuiet('type', 'style', "g:")
command! SyntasticToggleWarningsBuffer call SyntasticToggleQuiet('level', 'warnings', "b:")
command! SyntasticToggleStyleBuffer call SyntasticToggleQuiet('type', 'style', "b:")
fun! MySyntasticCheckAll()
let save = g:syntastic_quiet_messages
let g:syntastic_quiet_messages = { "level": [], 'type': [] }
SyntasticCheck
let g:syntastic_quiet_messages = save
endfun
command! MySyntasticCheckAll call MySyntasticCheckAll()
" Source: https://github.com/scrooloose/syntastic/issues/1361#issuecomment-82312541
function! SyntasticDisableToggle()
if !exists('s:syntastic_disabled')
let s:syntastic_disabled = 0
endif
if !s:syntastic_disabled
let s:modemap_save = deepcopy(g:syntastic_mode_map)
let g:syntastic_mode_map['active_filetypes'] = []
let g:syntastic_mode_map['mode'] = 'passive'
let s:syntastic_disabled = 1
SyntasticReset
echom "Syntastic disabled."
else
let g:syntastic_mode_map = deepcopy(s:modemap_save)
let s:syntastic_disabled = 0
echom "Syntastic enabled."
endif
endfunction
command! SyntasticDisableToggle call SyntasticDisableToggle()
" Neomake {{{
let g:neomake_open_list = 2
let g:neomake_list_height = 1 " handled via qf-resize autocommand
" let g:neomake_verbose = 3
" let g:neomake_logfile = '/tmp/neomake.log'
let g:neomake_tempfile_enabled = 1
let g:neomake_vim_enabled_makers = ['vint'] " vimlint is slow and too picky(?).
let g:neomake_python_enabled_makers = ['python', 'flake8']
let g:neomake_c_enabled_makers = []
augroup vimrc_neomake
au!
au BufReadPost ~/.dotfiles/vimrc let b:neomake_disabled = 1
au BufReadPost ~/.dotfiles/vimrc let b:neomake = extend(get(b:, 'neomake', {}), {'disabled': 1})
augroup END
" shellcheck: ignore "Can't follow non-constant source."
let $SHELLCHECK_OPTS='-e SC1090'
nnoremap <Leader>cc :Neomake<CR>
" Setup automake (https://github.com/neomake/neomake/pull/1167).
function! MyOnBattery()
try
return readfile('/sys/class/power_supply/AC/online') == ['0']
catch
return 1
endtry
endfunction
try
let g:neomake = {
\ 'automake': {
\ 'ignore_filetypes': ['startify'],
\ }}
if !has('timers') || MyOnBattery()
call neomake#configure#automake('w')
else
call neomake#configure#automake('nrw', 500)
endif
catch
echom 'Neomake: failed to setup automake: '.v:exception
function! NeomakeCheck(fname) abort
if !get(g:, 'neomake_check_on_wq', 0) && get(w:, 'neomake_quitting_win', 0)
return
endif
if bufnr(a:fname) != bufnr('%')
" Not invoked for the current buffer. This happens for ':w /tmp/foo'.
return
endif
if get(b:, 'neomake_disabled', get(t:, 'neomake_disabled', get(g:, 'neomake_disabled', 0)))
return
endif
let s:windows_before = [tabpagenr(), winnr('$')]
if get(b:, '_my_neomake_checked_tick') == b:changedtick
return
endif
call neomake#Make(1, [])
let b:_my_neomake_checked_tick = b:changedtick
endfun
augroup neomake_check
au!
autocmd BufWritePost * call NeomakeCheck(expand('<afile>'))
if exists('##QuitPre')
autocmd QuitPre * if winnr('$') == 1 | let w:neomake_quitting_win = 1 | endif
endif
augroup END
endtry
" }}}
" gist-vim {{{2
let g:gist_detect_filetype = 1
" }}}
" tinykeymap: used to move between signs from quickfixsigns and useful by itself. {{{2
let g:tinykeymap#mapleader = '<Leader>k'
let g:tinykeymap#timeout = 0 " default: 5000s (ms)
let g:tinykeymap#conflict = 1
" Exit also with 'q'.
let g:tinykeymap#break_key = 113
" Default "*"; exluded "para_move" from tlib.
" List: :echo globpath(&rtp, 'autoload/tinykeymap/map/*.vim')
let g:tinykeymaps_default = [
\ 'buffers', 'diff', 'filter', 'lines', 'loc', 'qfl', 'tabs', 'undo',
\ 'windows', 'quickfixsigns',
\ ]
" \ 'para_move',
" }}}
" fontzoom {{{
let g:fontzoom_no_default_key_mappings = 1
nmap <A-+> <Plug>(fontzoom-larger)
nmap <A--> <Plug>(fontzoom-smaller)
" }}}
" Call bcompare with current and alternate file.
command! BC call system('bcompare '.shellescape(expand('%')).' '.shellescape(expand('#')).'&')
" YouCompleteMe {{{
" This needs to be the Python that YCM was built against. (set in ~/.zshrc.local).
if filereadable($PYTHON_YCM)
let g:ycm_path_to_python_interpreter = $PYTHON_YCM
" let g:ycm_path_to_python_interpreter = 'python-in-terminal'
endif
let g:ycm_filetype_blacklist = {
\ 'python' : 1,
\ 'ycmblacklisted': 1
\}
let g:ycm_complete_in_comments = 1
let g:ycm_complete_in_strings = 1
let g:ycm_collect_identifiers_from_comments_and_strings = 1
let g:ycm_extra_conf_globlist = ['~/src/awesome/.ycm_extra_conf.py']
" Jump mappings, overridden in Python mode with jedi-vim.
nnoremap <leader>j :YcmCompleter GoToDefinition<CR>
nnoremap <leader>gj :YcmCompleter GoToDeclaration<CR>
fun! MySetupPythonMappings()
nnoremap <buffer> <leader>j :call jedi#goto_definitions()<CR>
nnoremap <buffer> <leader>gj :call jedi#goto_assignments()<CR>
endfun
augroup vimrc_jump_maps
au!
au FileType python call MySetupPythonMappings()
augroup END
" Deactivated: causes huge RAM usage (YCM issue 595)
" let g:ycm_collect_identifiers_from_tags_files = 1
" EXPERIMENTAL: auto-popups and experimenting with SuperTab
" NOTE: this skips the following map setup (also for C-n):
" ' pumvisible() ? "\<C-p>" : "\' . key .'"'
let g:ycm_key_list_select_completion = []
let g:ycm_key_list_previous_completion = []
let g:ycm_semantic_triggers = {
\ 'c' : ['->', '.'],
\ 'objc' : ['->', '.'],
\ 'ocaml' : ['.', '#'],
\ 'cpp,objcpp' : ['->', '.', '::'],
\ 'perl' : ['->'],
\ 'php' : ['->', '::'],
\ 'cs,java,javascript,d,vim,python,perl6,scala,vb,elixir,go' : ['.'],
\ 'ruby' : ['.', '::'],
\ 'lua' : ['.', ':'],
\ 'erlang' : [':'],
\ }
" Tags (configure this before easytags, except when using easytags_dynamic_files)
" Look for tags file in parent directories, upto "/"
set tags=./tags;/
" CR and BS mapping: call various plugins manually. {{{
let g:endwise_no_mappings = 1 " NOTE: must be unset instead of 0
let g:cursorcross_no_map_CR = 1
let g:cursorcross_no_map_BS = 1
let g:delimitMate_expand_cr = 0
let g:SuperTabCrMapping = 0 " Skip SuperTab CR map setup (skipped anyway for expr mapping)
let g:cursorcross_mappings = 0 " No generic mappings for cursorcross.
" Force delimitMate mapping (gets skipped if mapped already).
fun! My_CR_map()
" "<CR>" via delimitMateCR
if len(maparg('<Plug>delimitMateCR', 'i'))
let r = "\<Plug>delimitMateCR"
else
let r = "\<CR>"
endif
if len(maparg('<Plug>CursorCrossCR', 'i'))
" requires vim 704
let r .= "\<Plug>CursorCrossCR"
endif
if len(maparg('<Plug>DiscretionaryEnd', 'i'))
let r .= "\<Plug>DiscretionaryEnd"
endif
return r
endfun
imap <expr> <CR> My_CR_map()
fun! My_BS_map()
" "<BS>" via delimitMateBS
if len(maparg('<Plug>delimitMateBS', 'i'))
let r = "\<Plug>delimitMateBS"
else
let r = "\<BS>"
endif
if len(maparg('<Plug>CursorCrossBS', 'i'))
" requires vim 704
let r .= "\<Plug>CursorCrossBS"
endif
return r
endfun
imap <expr> <BS> My_BS_map()
" For endwise.
imap <C-X><CR> <CR><Plug>AlwaysEnd
" }}}
" github-issues
" Trigger API request(s) only when completion is used/invoked.
let g:gissues_lazy_load = 1
" Add tags from $VIRTUAL_ENV
if $VIRTUAL_ENV != ""
let &tags = $VIRTUAL_ENV.'/tags,' . &tags
endif
" syntax mode setup
let php_sql_query = 1
let php_htmlInStrings = 1
" let php_special_functions = 0
" let php_alt_comparisons = 0
" let php_alt_assignByReference = 0
" let PHP_outdentphpescape = 1
let g:PHP_autoformatcomment = 0 " do not set formatoptions/comments automatically (php-indent bundle / vim runtime)
let g:php_noShortTags = 1
" always use Smarty comments in smarty files
" NOTE: for {php} it's useful
let g:tcommentGuessFileType_smarty = 0
endif
if &t_Co == 8
" Allow color schemes to do bright colors without forcing bold. (vim-sensible)
if $TERM !~# '^linux'
set t_Co=16
endif
" Fix t_Co: hack to enable 256 colors with e.g. "screen-bce" on CentOS 5.4;
" COLORTERM=lilyterm used for LilyTerm (set TERM=xterm).
" Do not match "screen" in Linux VT
" if (&term[0:6] == "screen-" || len($COLORTERM))
" set t_Co=256
" endif
endif
" Local dirs"{{{1
set backupdir=~/.local/share/vim/backups
if ! isdirectory(expand(&backupdir))
call mkdir( &backupdir, 'p', 0700 )
endif
if 1
let s:xdg_cache_home = $XDG_CACHE_HOME
if !len(s:xdg_cache_home)
let s:xdg_cache_home = expand('~/.cache')
endif
let s:vimcachedir = s:xdg_cache_home . '/vim'
let g:tlib_cache = s:vimcachedir . '/tlib'
let s:xdg_config_home = $XDG_CONFIG_HOME
if !len(s:xdg_config_home)
let s:xdg_config_home = expand('~/.config')
endif
let s:vimconfigdir = s:xdg_config_home . '/vim'
let g:session_directory = s:vimconfigdir . '/sessions'
let g:startify_session_dir = g:session_directory
let g:startify_change_to_dir = 0
let s:xdg_data_home = $XDG_DATA_HOME
if !len(s:xdg_data_home)
let s:xdg_data_home = expand('~/.local/share')
endif
let s:vimsharedir = s:xdg_data_home . '/vim'
let &viewdir = s:vimsharedir . '/views'
let g:yankring_history_dir = s:vimsharedir
let g:yankring_max_history = 500
" let g:yankring_min_element_length = 2 " more that 1 breaks e.g. `xp`
" Move yankring history from old location, if any..
let s:old_yankring = expand('~/yankring_history_v2.txt')
if filereadable(s:old_yankring)
execute '!mv -i '.s:old_yankring.' '.s:vimsharedir
endif
" Transfer any old (default) tmru files db to new (default) location.
let g:tlib_persistent = s:vimsharedir
let s:old_tmru_file = expand('~/.cache/vim/tlib/tmru/files')
let s:global_tmru_file = s:vimsharedir.'/tmru/files'
let s:new_tmru_file_dir = fnamemodify(s:global_tmru_file, ':h')
if ! isdirectory(s:new_tmru_file_dir)
call mkdir(s:new_tmru_file_dir, 'p', 0700)
endif
if filereadable(s:old_tmru_file)
execute '!mv -i '.shellescape(s:old_tmru_file).' '.shellescape(s:global_tmru_file)
" execute '!rm -r '.shellescape(g:tlib_cache)
endif
end
let s:check_create_dirs = [s:vimcachedir, g:tlib_cache, s:vimconfigdir, g:session_directory, s:vimsharedir, &directory]
if has('persistent_undo')
let &undodir = s:vimsharedir . '/undo'
set undofile
call add(s:check_create_dirs, &undodir)
endif
for s:create_dir in s:check_create_dirs
" Remove trailing slashes, especially for &directory.
let s:create_dir = substitute(s:create_dir, '/\+$', '', '')
if ! isdirectory(s:create_dir)
if match(s:create_dir, ',') != -1
echohl WarningMsg | echom "WARN: not creating dir: ".s:create_dir | echohl None
continue
endif
echom "Creating dir: ".s:create_dir
call mkdir(s:create_dir, 'p', 0700 )
endif
endfor
" }}}
if has("user_commands")
" Themes
" Airline:
let g:airline#extensions#disable_rtp_load = 1
let g:airline_extensions_add = ['neomake']
let g:airline_powerline_fonts = 1
" to test
let g:airline#extensions#branch#use_vcscommand = 1
let g:airline#extensions#branch#displayed_head_limit = 7
let g:airline#extensions#hunks#non_zero_only = 1
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#show_buffers = 0
let g:airline#extensions#tabline#tab_nr_type = '[__tabnr__.%{len(tabpagebuflist(__tabnr__))}]'
let g:airline#extensions#tmuxline#enabled = 1
let g:airline#extensions#whitespace#enabled = 0
let g:airline#extensions#tagbar#enabled = 0
let g:airline#extensions#tagbar#flags = 'f' " full hierarchy of tag (with scope), see tagbar-statusline
" see airline-predefined-parts
" let r += ['%{ShortenFilename(fnamemodify(bufname("%"), ":~:."), winwidth(0)-50)}']
" function! AirlineInit()
" " let g:airline_section_a = airline#section#create(['mode', ' ', 'foo'])
" " let g:airline_section_b = airline#section#create_left(['ffenc','file'])
" " let g:airline_section_c = airline#section#create(['%{getcwd()}'])
" endfunction
" au VimEnter * call AirlineInit()
" jedi-vim (besides YCM with jedi library) {{{1
" let g:jedi#force_py_version = 3
let g:jedi#auto_vim_configuration = 0
let g:jedi#goto_assignments_command = '' " dynamically done for ft=python.
let g:jedi#goto_definitions_command = '' " dynamically done for ft=python.
let g:jedi#rename_command = 'cR'
let g:jedi#usages_command = 'gr'
let g:jedi#completions_enabled = 1
" Unite/ref and pydoc are more useful.
let g:jedi#documentation_command = '<Leader>_K'
" Manually setup jedi's call signatures.
let g:jedi#show_call_signatures = 1
if &rtp =~ '\<jedi\>'
augroup JediSetup
au!
au FileType python call jedi#configure_call_signatures()
augroup END
endif
let g:jedi#auto_close_doc = 1
" if g:jedi#auto_close_doc
" " close preview if its still open after insert
" autocmd InsertLeave <buffer> if pumvisible() == 0|pclose|endif
" end
" }}}1
endif
" Enable syntax {{{1
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
" if (&t_Co > 2 || has("gui_running")) && !exists("syntax_on")
if (&t_Co > 2 || has("gui_running"))
if !exists("syntax_on")
syntax on " after 'filetype plugin indent on' (?!), but not on reload.
endif
set nohlsearch
" Improved syntax handling of TODO etc.
au Syntax * syn match MyTodo /\v<(FIXME|NOTE|TODO|OPTIMIZE|XXX):/
\ containedin=.*Comment,vimCommentTitle
hi def link MyTodo Todo
endif
if 1 " has('eval')
" Color scheme (after 'syntax on') {{{1
" Use light/dark background based on day/night period (according to
" get-daytime-period (uses redshift))
fun! SetBgAccordingToShell(...)
let variant = a:0 ? a:1 : ""
if len(variant) && variant != "auto"
let bg = variant
elseif len($TMUX)
let bg = system('tmux show-env MY_X_THEME_VARIANT') == "MY_X_THEME_VARIANT=light\n" ? 'light' : 'dark'
elseif len($MY_X_THEME_VARIANT)
let bg = $MY_X_THEME_VARIANT
else
" let daytime = system('get-daytime-period')
let daytime_file = expand('/tmp/redshift-period')
if filereadable(daytime_file)
let daytime = readfile(daytime_file)[0]
if daytime == 'Daytime'
let bg = "light"
else
let bg = "dark"
endif
else
let bg = "dark"
endif
endif
if bg != &bg
let &bg = bg
- let $FZF_DEFAULT_OPTS = '--color 16,bg+:' . (bg == 'dark' ? '18' : '21')
doautocmd <nomodeline> ColorScheme
endif
endfun
command! -nargs=? Autobg call SetBgAccordingToShell(<q-args>)
fun! ToggleBg()
let &bg = &bg == 'dark' ? 'light' : 'dark'
endfun
nnoremap <Leader>sb :call ToggleBg()<cr>
" Colorscheme: prefer solarized with 16 colors (special palette).
let g:solarized_hitrail=0 " using MyWhitespaceSetup instead.
let g:solarized_menu=0
" Use corresponding theme from $BASE16_THEME, if set up in the shell.
" BASE16_THEME should be in sudoer's env_keep for "sudo vi".
if len($BASE16_THEME)
let base16colorspace=&t_Co
if $BASE16_THEME =~ '^solarized'
let s:use_colorscheme = 'solarized'
let g:solarized_base16=1
let g:airline_theme = 'solarized'
else
let s:use_colorscheme = 'base16-'.substitute($BASE16_THEME, '\.\(dark\|light\)$', '', '')
endif
let g:solarized_termtrans=1
elseif has('gui_running')
let s:use_colorscheme = "solarized"
let g:solarized_termcolors=256
else
" Check for dumb terminal.
if ($TERM !~ '256color' )
let s:use_colorscheme = "default"
else
let s:use_colorscheme = "solarized"
let g:solarized_termcolors=256
endif
endif
" Airline: do not use powerline symbols with linux/screen terminal.
" NOTE: xterm-256color gets setup for tmux/screen with $DISPLAY.
if (index(["linux", "screen"], $TERM) != -1)
let g:airline_powerline_fonts = 0
endif
fun! s:MySetColorscheme()
" Set s:use_colorscheme, called through GUIEnter for gvim.
try
exec 'NeoBundleSource colorscheme-'.s:use_colorscheme
exec 'colorscheme' s:use_colorscheme
catch
echom "Failed to load colorscheme: " v:exception
endtry
endfun
if has('vim_starting')
call SetBgAccordingToShell($MY_X_THEME_VARIANT)
endif
if has('gui_running')
au GUIEnter * nested call s:MySetColorscheme()
else
call s:MySetColorscheme()
endif
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd") " Autocommands {{{1
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcEx
au!
" Handle large files, based on LargeFile plugin.
let g:LargeFile = 5 " 5mb
autocmd BufWinEnter * if get(b:, 'LargeFile_mode') || line2byte(line("$") + 1) > 1000000
\ | echom "vimrc: handling large file."
\ | set syntax=off
\ | let &ft = &ft.".ycmblacklisted"
\ | endif
" Enable soft-wrapping for text files
au FileType text,markdown,html,xhtml,eruby,vim setlocal wrap linebreak nolist
au FileType mail,markdown,gitcommit setlocal spell
au FileType json setlocal equalprg=json_pp
" XXX: only works for whole files
" au FileType css setlocal equalprg=csstidy\ -\ --silent=true\ --template=default
" For all text files set 'textwidth' to 78 characters.
" au FileType text setlocal textwidth=78
" Follow symlinks when opening a file {{{
" NOTE: this happens with directory symlinks anyway (due to Vim's chdir/getcwd
" magic when getting filenames).
" Sources:
" - https://github.com/tpope/vim-fugitive/issues/147#issuecomment-7572351
" - http://www.reddit.com/r/vim/comments/yhsn6/is_it_possible_to_work_around_the_symlink_bug/c5w91qw
function! MyFollowSymlink(...)
if exists('w:no_resolve_symlink') && w:no_resolve_symlink
return
endif
if &ft == 'help'
return
endif
let fname = a:0 ? a:1 : expand('%')
if fname =~ '^\w\+:/'
" Do not mess with 'fugitive://' etc.
return
endif
let fname = simplify(fname)
let resolvedfile = resolve(fname)
if resolvedfile == fname
return
endif
let resolvedfile = fnameescape(resolvedfile)
let sshm = &shm
set shortmess+=A " silence ATTENTION message about swap file (would get displayed twice)
redraw " Redraw now, to avoid hit-enter prompt.
exec 'file ' . resolvedfile
let &shm=sshm
unlet! b:git_dir
call fugitive#detect(resolvedfile)
if &modifiable
" Only display a note when editing a file, especially not for `:help`.
redraw " Redraw now, to avoid hit-enter prompt.
echomsg 'Resolved symlink: =>' resolvedfile
endif
endfunction
command! -bar FollowSymlink call MyFollowSymlink()
command! ToggleFollowSymlink let w:no_resolve_symlink = !get(w:, 'no_resolve_symlink', 0) | echo "w:no_resolve_symlink =>" w:no_resolve_symlink
au BufReadPost * nested call MyFollowSymlink(expand('%'))
" Automatically load .vimrc source when saved
au BufWritePost $MYVIMRC,~/.dotfiles/vimrc,$MYVIMRC.local source $MYVIMRC
au BufWritePost $MYGVIMRC,~/.dotfiles/gvimrc source $MYGVIMRC
" if (has("gui_running"))
" au FocusLost * stopinsert
" endif
" autocommands for fugitive {{{2
" Source: http://vimcasts.org/episodes/fugitive-vim-browsing-the-git-object-database/
au User Fugitive
\ if fugitive#buffer().type() =~# '^\%(tree\|blob\)' |
\ nnoremap <buffer> .. :edit %:h<CR> |
\ endif
au BufReadPost fugitive://* set bufhidden=delete
" Expand tabs for Debian changelog. This is probably not the correct way.
au BufNewFile,BufRead */debian/changelog,changelog.dch set expandtab
" Ignore certain files with vim-stay.
au BufNewFile,BufRead */.git/addp-hunk-edit.diff let b:stay_ignore = 1
" Python
" irrelevant, using python-pep8-indent
" let g:pyindent_continue = '&sw * 1'
" let g:pyindent_open_paren = '&sw * 1'
" let g:pyindent_nested_paren = '&sw'
" python-mode
let g:pymode_options = 0 " do not change relativenumber
let g:pymode_indent = 0 " use vim-python-pep8-indent (upstream of pymode)
let g:pymode_lint = 0 " prefer syntastic; pymode has problems when PyLint was invoked already before VirtualEnvActivate..!?!
let g:pymode_virtualenv = 0 " use virtualenv plugin (required for pylint?!)
let g:pymode_doc = 0 " use pydoc
let g:pymode_rope_completion = 0 " use YouCompleteMe instead (python-jedi)
let g:pymode_syntax_space_errors = 0 " using MyWhitespaceSetup
let g:pymode_trim_whitespaces = 0
let g:pymode_debug = 0
let g:pymode_rope = 0
let g:pydoc_window_lines=0.5 " use 50% height
let g:pydoc_perform_mappings=0
" let python_space_error_highlight = 1 " using MyWhitespaceSetup
" C
au FileType C setlocal formatoptions-=c formatoptions-=o formatoptions-=r
fu! Select_c_style()
if search('^\t', 'n', 150)
setlocal shiftwidth=8 noexpandtab
el
setlocal shiftwidth=4 expandtab
en
endf
au FileType c call Select_c_style()
au FileType make setlocal noexpandtab
" Disable highlighting of markdownError (Ref: https://github.com/tpope/vim-markdown/issues/79).
autocmd FileType markdown hi link markdownError NONE
augroup END
" Trailing whitespace highlighting {{{2
" Map to toogle EOLWS syntax highlighting
noremap <silent> <leader>se :let g:MyAuGroupEOLWSactive = (synIDattr(synIDtrans(hlID("EOLWS")), "bg", "cterm") == -1)<cr>
\:call MyAuGroupEOLWS(mode())<cr>
let g:MyAuGroupEOLWSactive = 0
function! MyAuGroupEOLWS(mode)
if g:MyAuGroupEOLWSactive && &buftype == ''
hi EOLWS ctermbg=red guibg=red
syn clear EOLWS
" match whitespace not preceded by a backslash
if a:mode == "i"
syn match EOLWS excludenl /[\\]\@<!\s\+\%#\@!$/ containedin=ALL
else
syn match EOLWS excludenl /[\\]\@<!\s\+$\| \+\ze\t/ containedin=ALLBUT,gitcommitDiff |
endif
else
syn clear EOLWS
hi clear EOLWS
endif
endfunction
augroup vimrcExEOLWS
au!
" highlight EOLWS ctermbg=red guibg=red
" based on solarizedTrailingSpace
highlight EOLWS term=underline cterm=underline ctermfg=1
au InsertEnter * call MyAuGroupEOLWS("i")
" highlight trailing whitespace, space before tab and tab not at the
" beginning of the line (except in comments), only for normal buffers:
au InsertLeave,BufWinEnter * call MyAuGroupEOLWS("n")
" fails with gitcommit: filetype | syn match EOLWS excludenl /[^\t]\zs\t\+/ containedin=ALLBUT,gitcommitComment
" add this for Python (via python_highlight_all?!):
" au FileType python
" \ if g:MyAuGroupEOLWSactive |
" \ syn match EOLWS excludenl /^\t\+/ containedin=ALL |
" \ endif
augroup END "}}}
" automatically save and reload viminfo across Vim instances
" Source: http://vimhelp.appspot.com/vim_faq.txt.html#faq-17.3
augroup viminfo_onfocus
au!
" au FocusLost * wviminfo
" au FocusGained * rviminfo
augroup end
endif " has("autocmd") }}}
" Shorten a given (absolute) file path, via external `shorten_path` script.
" This mainly shortens entries from Zsh's `hash -d` list.
let s:_cache_shorten_path = {}
let s:_has_functional_shorten_path = 1
let s:shorten_path_exe = executable('shorten_path')
\ ? 'shorten_path'
\ : filereadable(expand("$HOME/.dotfiles/usr/bin/shorten_path"))
\ ? expand("$HOME/.dotfiles/usr/bin/shorten_path")
\ : expand("/home/$SUDO_USER/.dotfiles/usr/bin/shorten_path")
function! ShortenPath(path, ...)
if !len(a:path) || !s:_has_functional_shorten_path
return a:path
endif
let base = a:0 ? a:1 : ""
let annotate = a:0 > 1 ? a:2 : 0
let cache_key = base . ":" . a:path . ":" . annotate
if !exists('s:_cache_shorten_path[cache_key]')
let shorten_path = [s:shorten_path_exe]
if annotate
let shorten_path += ['-a']
endif
let cmd = shorten_path + [a:path, base]
let output = s:systemlist(cmd)
let lastline = empty(output) ? '' : output[-1]
let s:_cache_shorten_path[cache_key] = lastline
if v:shell_error
try
let tmpfile = tempname()
let system_cmd = join(map(copy(cmd), 'fnameescape(v:val)'))
call system(system_cmd.' 2>'.tmpfile)
if v:shell_error == 127
let s:_has_functional_shorten_path = 0
endif
echohl ErrorMsg
echom printf('There was a problem running %s: %s (%d)',
\ cmd, join(readfile(tmpfile), "\n"), v:shell_error)
echohl None
return a:path
finally
call delete(tmpfile)
endtry
endif
endif
return s:_cache_shorten_path[cache_key]
endfun
function! My_get_qfloclist_type(bufnr)
let isLoc = getbufvar(a:bufnr, 'isLoc', -1) " via vim-qf.
if isLoc != -1
return isLoc ? 'll' : 'qf'
endif
" A hacky way to distinguish qf from loclist windows/buffers.
" https://github.com/vim-airline/vim-airline/blob/83b6dd11a8829bbd934576e76bfbda6559ed49e1/autoload/airline/extensions/quickfix.vim#L27-L43.
" Changes:
" - Caching!
" - Match opening square bracket at least. Apart from that it could be
" localized.
" if &ft !=# 'qf'
" return ''
" endif
let type = getbufvar(a:bufnr, 'my_qfloclist_type', '')
if type != ''
return type
endif
redir => buffers
silent ls -
redir END
let type = 'unknown'
for buf in split(buffers, '\n')
if match(buf, '\v^\s*'.a:bufnr.'\s\S+\s+"\[') > -1
if match(buf, '\cQuickfix') > -1
let type = 'qf'
break
else
let type = 'll'
break
endif
endif
endfor
call setbufvar(a:bufnr, 'my_qfloclist_type', type)
return type
endfunction
function! s:systemlist(l) abort
if !has('nvim')
let cmd = join(map(copy(a:l), 'fnameescape(v:val)'))
else
let cmd = a:l
endif
return systemlist(cmd)
endfunction
" Shorten a given filename by truncating path segments.
let g:_cache_shorten_filename = {}
let g:_cache_shorten_filename_git = {}
function! ShortenString(s, maxlen)
if len(a:s) <= a:maxlen
return a:s
endif
return a:s[0:a:maxlen-1] . 'â¦'
endfunction
function! ShortenFilename(...) " {{{
" Args: bufname ('%' for default), maxlength, cwd
let cwd = a:0 > 2 ? a:3 : getcwd()
" Maxlen from a:2 (used for cache key) and caching.
let maxlen = a:0>1 ? a:2 : max([10, winwidth(0)-50])
" get bufname from a:1, defaulting to bufname('%') {{{
if a:0 && type(a:1) == type('') && a:1 !=# '%'
let bufname = expand(a:1) " tilde-expansion.
else
if !a:0 || a:1 == '%'
let bufnr = bufnr('%')
else
let bufnr = a:1
endif
let bufname = bufname(bufnr)
let ft = getbufvar(bufnr, '&filetype')
if !len(bufname)
if ft == 'qf'
let type = My_get_qfloclist_type(bufnr)
" XXX: uses current window. Also not available after ":tab split".
let qf_title = get(w:, 'quickfix_title', '')
if qf_title != ''
return ShortenString('['.type.'] '.qf_title, maxlen)
elseif type == 'll'
let alt_name = expand('#')
" For location lists the alternate file is the corresponding buffer
" and the quickfix list does not have an alternate buffer
" (but not always)!?!
if len(alt_name)
return '[loc] '.ShortenFilename(alt_name, maxlen-5)
endif
return '[loc]'
endif
return '[qf]'
else
let bt = getbufvar(bufnr, '&buftype')
if bt != '' && ft != ''
" Use &ft for name (e.g. with 'startify' and quickfix windows).
" if &ft == 'qf'
" let alt_name = expand('#')
" if len(alt_name)
" return '[loc] '.ShortenFilename(alt_name)
" else
" return '[qf]'
" endif
let alt_name = expand('#')
if len(alt_name)
return '['.&ft.'] '.ShortenFilename(expand('#'))
else
return '['.&ft.']'
endif
else
" TODO: get Vim's original "[No Name]" somehow
return '[No Name]'
endif
endif
end
if ft ==# 'help'
return '[?] '.fnamemodify(bufname, ':t')
endif
if bufname =~# '^__'
return bufname
endif
" '^\[ref-\w\+:.*\]$'
if bufname =~# '^\[.*\]$'
return bufname
endif
endif
" }}}
" {{{ fugitive
if bufname =~# '^fugitive:///'
let [gitdir, fug_path] = split(bufname, '//')[1:2]
" Caching based on bufname and timestamp of gitdir.
let git_ftime = getftime(gitdir)
if exists('g:_cache_shorten_filename_git[bufname]')
\ && g:_cache_shorten_filename_git[bufname][0] == git_ftime
let [commit_name, fug_type, fug_path]
\ = g:_cache_shorten_filename_git[bufname][1:-1]
else
let fug_buffer = fugitive#buffer(bufname)
let fug_type = fug_buffer.type()
" if fug_path =~# '^\x\{7,40\}\>'
let commit = matchstr(fug_path, '\v\w*')
if len(commit) > 1
let git_argv = ['git', '--git-dir='.gitdir]
let commit = systemlist(git_argv + ['rev-parse', '--short', commit])[0]
let commit_name = systemlist(git_argv + ['name-rev', '--name-only', commit])[0]
if commit_name !=# 'undefined'
" Remove current branch name (master~4 => ~4).
let HEAD = get(systemlist(git_argv + ['symbolic-ref', '--quiet', '--short', 'HEAD']), 0, '')
let len_HEAD = len(HEAD)
if len_HEAD > len(commit_name) && commit_name[0:len_HEAD-1] == HEAD
let commit_name = commit_name[len_HEAD:-1]
endif
" let commit .= '('.commit_name.')'
let commit_name .= '('.commit.')'
else
let commit_name = commit
endif
else
let commit_name = commit
endif
" endif
if fug_type !=# 'commit'
let fug_path = substitute(fug_path, '\v\w*/', '', '')
if len(fug_path)
let fug_path = ShortenFilename(fug_buffer.repo().tree(fug_path))
endif
else
let fug_path = 'NOT_USED'
endif
" Set cache.
let g:_cache_shorten_filename_git[bufname]
\ = [git_ftime, commit_name, fug_type, fug_path]
endif
if fug_type ==# 'blob'
return 'λ:' . commit_name . ':' . fug_path
elseif fug_type ==# 'file'
return 'λ:' . fug_path . '@' . commit_name
elseif fug_type ==# 'commit'
" elseif fug_path =~# '^\x\{7,40\}\>'
let work_tree = fugitive#buffer(bufname).repo().tree()
if cwd[0:len(work_tree)-1] == work_tree
let rel_work_tree = ''
else
let rel_work_tree = ShortenPath(fnamemodify(work_tree.'/', ':.'))
endif
return 'λ:' . rel_work_tree . '@' . commit_name
endif
throw "fug_type: ".fug_type." not handled: ".fug_path
endif " }}}
" Check for cache (avoiding fnamemodify): {{{
let cache_key = bufname.'::'.cwd.'::'.maxlen
if has_key(g:_cache_shorten_filename, cache_key)
return g:_cache_shorten_filename[cache_key]
endif
" Make path relative first, which might not work with the result from
" `shorten_path`.
let rel_path = fnamemodify(bufname, ":.")
let bufname = ShortenPath(rel_path, cwd, 1)
" }}}
" Loop over all segments/parts, to mark symlinks.
" XXX: symlinks get resolved currently anyway!?
" NOTE: consider using another method like http://stackoverflow.com/questions/13165941/how-to-truncate-long-file-path-in-vim-powerline-statusline
let maxlen_of_parts = 7 " including slash/dot
let maxlen_of_subparts = 1 " split at hypen/underscore; including split
let s:PS = exists('+shellslash') ? (&shellslash ? '/' : '\') : "/"
let parts = split(bufname, '\ze['.escape(s:PS, '\').']')
let i = 0
let n = len(parts)
let wholepath = '' " used for symlink check
while i < n
let wholepath .= parts[i]
|
blueyed/dotfiles | 230e24b8c0045564ae49ef6b077db2ff85ce5b81 | vim: statusline: partial update for Neomake integration | diff --git a/vim/plugin/statusline.vim b/vim/plugin/statusline.vim
index 6d6d742..0e58e38 100644
--- a/vim/plugin/statusline.vim
+++ b/vim/plugin/statusline.vim
@@ -1,832 +1,838 @@
" My custom statusline.
scriptencoding utf-8
if !has('statusline')
finish
endif
if &runtimepath =~# '\<airline\>'
finish
endif
if !exists('*ShortenFilename')
" when using a minimal vimrc etc.
finish
endif
set showtabline=2
" Helper functions {{{
function! FileSize()
let bytes = getfsize(expand('%:p'))
if bytes <= 0
return ''
endif
if bytes < 1024
return bytes
else
return (bytes / 1024) . 'K'
endif
endfunction
" Get property from highlighting group.
" Based on / copied from neomake#utils#GetHighlight
" (~/.dotfiles/vim/neobundles/neomake/autoload/neomake/utils.vim).
function! StatuslineGetHighlight(group, what) abort
let reverse = synIDattr(synIDtrans(hlID(a:group)), 'reverse')
let what = a:what
if reverse
let what = s:ReverseSynIDattr(what)
endif
if what[-1:] ==# '#'
let val = synIDattr(synIDtrans(hlID(a:group)), what, 'gui')
else
let val = synIDattr(synIDtrans(hlID(a:group)), what, 'cterm')
endif
if empty(val) || val == -1
let val = 'NONE'
endif
return val
endfunction
function! s:ReverseSynIDattr(attr) abort
if a:attr ==# 'fg'
return 'bg'
elseif a:attr ==# 'bg'
return 'fg'
elseif a:attr ==# 'fg#'
return 'bg#'
elseif a:attr ==# 'bg#'
return 'fg#'
endif
return a:attr
endfunction
function! StatuslineHighlights(...)
" NOTE: not much gui / termguicolors support!
" XXX: pretty much specific for solarized_base16.
" let event = a:0 ? a:1 : ''
" echom "Calling StatuslineHighlights" a:event
if &background ==# 'light'
hi StatColorHi1 ctermfg=21 ctermbg=7
hi StatColorHi1To2Normal ctermfg=7 ctermbg=8
hi link StatColorHi1To2 StatColorHi1To2Normal
exe 'hi StatColorHi1ToBg ctermfg=7 ctermbg='.StatuslineGetHighlight('StatusLine', 'bg')
hi StatColorHi2 ctermfg=21 ctermbg=8
exe 'hi StatColorHi2ToBg ctermfg=8 ctermbg='.StatuslineGetHighlight('StatusLine', 'bg')
exe 'hi StatColorNeomakeGood'
\ 'ctermfg=white'
\ 'ctermbg='.StatuslineGetHighlight('StatColorHi2', 'bg')
if get(g:, 'solarized_base16', 0)
hi VertSplit ctermbg=21 cterm=underline
endif
else " dark bg
" NOTE: using ctermfg=18 for bold support (for fg=0 color 8 is used for bold).
hi StatColorHi1 ctermfg=18 ctermbg=20
hi StatColorHi1To2Normal ctermfg=20 ctermbg=19
hi link StatColorHi1To2 StatColorHi1To2Normal
exe 'hi StatColorHi1ToBg ctermfg=7 ctermbg='.StatuslineGetHighlight('StatusLine', 'bg')
" NOTE: using ctermfg=18 for bold support (for fg=0 color 8 is used for bold).
hi StatColorHi2 ctermfg=18 ctermbg=19
exe 'hi StatColorHi2ToBg ctermfg=19 ctermbg='.StatuslineGetHighlight('StatusLine', 'bg')
exe 'hi StatColorNeomakeGood'
\ 'ctermfg=green'
\ 'ctermbg='.StatuslineGetHighlight('StatColorHi2', 'bg')
if get(g:, 'solarized_base16', 0)
hi VertSplit ctermbg=18
endif
endif
" exe 'hi StatColorCurHunk cterm=bold'
" \ ' ctermfg='.StatuslineGetHighlight('StatColorHi2', 'fg')
" \ ' ctermbg='.StatuslineGetHighlight('StatColorHi2', 'bg')
exe 'hi StatColorHi2Bold cterm=bold'
\ ' ctermfg='.StatuslineGetHighlight('StatColorHi2', 'fg')
\ ' ctermbg='.StatuslineGetHighlight('StatColorHi2', 'bg')
hi link StatColorMode StatColorHi1
" Force/set StatusLineNC based on VertSplit.
hi clear StatusLineNC
exe 'hi StatusLineNC'
\ . ' cterm=underline gui=underline'
\ . ' ctermfg=' . (&background ==# 'dark' ? 7 : 8)
\ . ' ctermbg=' . StatuslineGetHighlight('VertSplit', 'bg')
\ . ' guifg=' . StatuslineGetHighlight('CursorLine', 'bg#')
\ . ' guibg=' . StatuslineGetHighlight('VertSplit', 'bg#')
" exe 'hi StatusLineNC ctermfg=7 ctermbg=0 cterm=NONE'
" (&background ==# 'dark' ? 19 : 20)
" exe 'hi StatusLineQuickfixNC'
" \ . ' cterm=underline'
" \ . ' ctermfg=' . (&background ==# 'dark' ? 7 : 21)
" \ . ' ctermbg=' . (&background ==# 'dark' ? 7 : 7)
" hi link StatColorError Error
" exe 'hi StatColorErrorToBg'
" \ . ' ctermfg='.StatuslineGetHighlight('StatColorError', 'bg')
" \ . ' ctermbg='.StatuslineGetHighlight('StatusLine', 'bg')
" exe 'hi StatColorErrorToBgNC'
" \ . ' ctermfg='.StatuslineGetHighlight('StatColorError', 'bg')
" \ . ' ctermbg='.StatuslineGetHighlight('StatusLineNC', 'bg')
" exe 'hi StatColorHi1ToError'
" \ . ' ctermfg='.StatuslineGetHighlight('StatColorError', 'bg')
" \ . ' ctermbg='.StatuslineGetHighlight('StatColorHi1', 'bg')
" let error_color = StatuslineGetHighlight('Error', 'bg')
" if error_color == 'NONE'
" let error_color = StatuslineGetHighlight('Error', 'fg')
" endif
exe 'hi StatColorNeomakeError cterm=NONE'
\ 'ctermfg=white'
\ 'ctermbg=red'
exe 'hi StatColorNeomakeNonError cterm=NONE'
\ 'ctermfg=white'
\ 'ctermbg=yellow'
hi StatColorModified guibg=orange guifg=black ctermbg=yellow ctermfg=white
hi clear StatColorModifiedNC
exe 'hi StatColorModifiedNC'
\ . ' cterm=italic,underline'
\ . ' ctermfg=' . StatuslineGetHighlight('StatusLineNC', 'fg')
\ . ' ctermbg='.StatuslineGetHighlight('StatusLineNC', 'bg')
exe 'hi StatColorHi1To2Modified'
\ . ' ctermfg='.StatuslineGetHighlight('StatColorModified', 'bg')
\ . ' ctermbg='.StatuslineGetHighlight('StatColorHi2', 'bg')
exe 'hi StatColorHi1To2Insert'
\ . ' ctermfg=green'
\ . ' ctermbg='.StatuslineGetHighlight('StatColorHi2', 'bg')
" tabline
" exe 'hi TabLineSelSign cterm=underline'
" \ . ' ctermfg='.StatuslineGetHighlight('TabLineSel', 'bg')
" \ . ' ctermbg='.StatuslineGetHighlight('TabLine', 'bg')
exe 'hi TabLineCwd cterm=underline'
\ . ' ctermfg=green'
\ . ' ctermbg='.StatuslineGetHighlight('TabLine', 'bg')
exe 'hi TabLineNumber cterm=bold,underline'
\ . ' ctermfg='.StatuslineGetHighlight('TabLine', 'fg')
\ . ' ctermbg='.StatuslineGetHighlight('TabLine', 'bg')
hi! link TabLineSel StatColorHi1
exe 'hi TabLineNumberSel cterm=bold'
\ . ' ctermfg='.StatuslineGetHighlight('TabLineSel', 'fg')
\ . ' ctermbg='.StatuslineGetHighlight('TabLineSel', 'bg')
" hi! link TabLineNumberSel StatColorMode
endfunction
function! StatuslineModeColor(mode)
" echom "StatuslineModeColor" a:mode winnr()
if a:mode ==# 'i'
" hi StatColor guibg=orange guifg=black ctermbg=white ctermfg=black
" hi StatColor ctermbg=20 ctermfg=black
" hi StatColorMode cterm=reverse ctermfg=green
exe 'hi StatColorMode'
\ . ' ctermfg='.StatuslineGetHighlight('StatColorHi1', 'fg')
\ . ' ctermbg=green'
if &modified
hi link StatColorHi1To2 StatColorHi1To2Modified
else
hi link StatColorHi1To2 StatColorHi1To2Insert
endif
elseif a:mode ==# 'r' " via R
" hi StatColor guibg=#e454ba guifg=black ctermbg=magenta ctermfg=black
elseif a:mode ==# 'v'
" hi StatColor guibg=#e454ba guifg=black ctermbg=magenta ctermfg=black
else
" Reset
hi clear StatColorMode
if &modified
hi link StatColorMode StatColorModified
hi link StatColorHi1To2 StatColorHi1To2Modified
else
hi link StatColorMode StatColorHi1
" hi StatColorHi1To2 ctermfg=19 ctermbg=20
hi link StatColorHi1To2 StatColorHi1To2Normal
endif
endif
endfunction
let s:enabled = 1
function! s:RefreshStatus()
let winnr = winnr()
for nr in range(1, winnr('$'))
if s:enabled
let stl = getwinvar(nr, '&ft') ==# 'codi' ? '[codi]' : '%!MyStatusLine(' . nr . ', '.(winnr == nr).')'
else
let stl = ''
endif
call setwinvar(nr, '&statusline', stl)
endfor
endfunction
" Clear cache of corresponding real buffer when saving a fugitive buffer.
function! StatuslineClearCacheFugitive(bufname)
if !exists('*FugitiveReal')
return
endif
let bufnr = bufnr(FugitiveReal())
if bufnr != -1
call StatuslineClearCache(bufnr)
" Clear caches on / update alternative window(s).
" https://github.com/tomtom/quickfixsigns_vim/issues/67
let idx = 0
let prev_alt_winnr = winnr('#')
let prev_winnr = winnr()
for b in tabpagebuflist()
let idx += 1
if b == bufnr
exe 'noautocmd '.idx.'wincmd w'
QuickfixsignsSet
endif
endfor
if winnr() != prev_winnr || winnr('#') != prev_alt_winnr
exe 'noautocmd '.prev_alt_winnr.'wincmd w'
exe 'noautocmd '.prev_winnr.'wincmd w'
endif
endif
endfunction
function! StatuslineClearCache(...)
let bufnr = a:0 ? a:1 : bufnr('%')
if exists('*quickfixsigns#vcsdiff#ClearCache')
call quickfixsigns#vcsdiff#ClearCache(bufnr)
endif
call setbufvar(bufnr, 'stl_cache_hunks', 'UNSET')
call setbufvar(bufnr, 'stl_cache_fugitive', [0, ''])
endfun
-function! OnNeomakeCountsChanged()
- let [ll_counts, qf_counts] = GetNeomakeCounts(g:neomake_hook_context.bufnr, 0)
- let cmd = ''
- let file_mode = get(get(g:, 'neomake_hook_context', {}), 'file_mode')
- " let file_mode = get(get(g:, 'neomake_current_maker', {}), 'file_mode')
- if file_mode
- for [type, c] in items(ll_counts)
- if type ==# 'E'
- let cmd = 'lwindow'
- break
- endif
- endfor
- else
- for [type, c] in items(qf_counts)
- if type ==# 'E'
- let cmd = 'cwindow'
- break
- endif
- endfor
+
+" Close empty lists when Neomake finished (manually with neomake_open_list=0).
+function! OnNeomakeFinished(...)
+ if exists('g:neomake_test_messages')
+ return
endif
- if cmd !=# ''
- let aw = winnr('#')
- let pw = winnr()
- exec cmd
- if winnr() != pw
- " Go back, maintaining the '#' window.
- exec 'noautocmd ' . aw . 'wincmd w'
- exec 'noautocmd ' . pw . 'wincmd w'
- endif
- else
+ if get(g:, 'neomake_open_list', 0)
+ return
endif
-endfunction
-function! OnNeomakeFinished()
+ let context = a:0 ? a:1 : get(g:, 'neomake_hook_context', {})
+ let file_mode = context.options.file_mode
+
" Close empty lists.
- " echom 'statusline: OnNeomakeFinished'
- if g:neomake_hook_context.file_mode
+ if file_mode
if len(getloclist(0)) == 0
lwindow
endif
- else
- if len(getqflist()) == 0
- cwindow
+ elseif len(getqflist()) == 0
+ cwindow
+ endif
+endfunction
+
+function! s:list_has_errors(list)
+ for e in a:list
+ if get(e, 'type', 'E') ==? 'E'
+ return 1
endif
+ endfor
+ return 0
+endfunction
+
+function! OnNeomakeJobFinished(...) abort
+ let context = a:0 ? a:1 : get(g:, 'neomake_hook_context', {})
+
+ let jobinfo = context.jobinfo
+ call neomake#log#debug('OnNeomakeJobFinished (user statusline): job: '.jobinfo.id)
+ let file_mode = jobinfo.file_mode
+ let make_info = neomake#GetMakeOptions(jobinfo.make_id)
+ let entries_list = make_info.entries_list
+
+ if entries_list.need_init
+ " This job has added no entries - do not open the previous list.
+ return
endif
+
+ let list = file_mode ? getloclist(0) : getqflist()
+ if s:list_has_errors(list)
+ " call neomake#_handle_list_display(jobinfo, min([10, len(list)]))
+ call neomake#_handle_list_display(jobinfo, list)
+ endif
+ call neomake#log#debug('OnNeomakeJobFinished (user statusline): job: '.jobinfo.id.' finished.')
+
" XXX: brute-force
call s:RefreshStatus()
+ call neomake#log#debug('OnNeomakeJobFinished (user statusline): job: '.jobinfo.id.' end.')
endfunction
augroup stl_neomake
au!
- " autocmd User NeomakeMakerFinished unlet! b:stl_cache_neomake
- " autocmd User NeomakeListAdded unlet! b:stl_cache_neomake
- autocmd User NeomakeCountsChanged call OnNeomakeCountsChanged()
- autocmd User NeomakeFinished call OnNeomakeFinished()
- " autocmd User NeomakeMakerFinished call OnNeomakeMakerFinished()
+ autocmd User NeomakeFinished nested call OnNeomakeFinished()
+ autocmd User NeomakeJobFinished nested call OnNeomakeJobFinished()
augroup END
function! s:setup_autocmds()
augroup vimrc_statusline
au!
" au WinEnter * setlocal statusline=%!MyStatusLine('active')
" au WinLeave * setlocal statusline=%!MyStatusLine('inactive')
au InsertEnter * call StatuslineModeColor(v:insertmode)
" TODO: typically gets called for both InsertLeave and TextChanged?!
" BufWinEnter for when going to a tag etc to another buffer in the same win.
au InsertLeave,TextChanged,BufWritePost,ShellCmdPost,ShellFilterPost,BufWinEnter,WinEnter * call StatuslineModeColor('')
au TextChanged,BufWritePost,ShellCmdPost,ShellFilterPost,FocusGained * call StatuslineClearCache()
" Invalidate cache for corresponding buffer for a fugitive buffer.
au BufWritePost fugitive:///* call StatuslineClearCacheFugitive(expand('<amatch>'))
" au Syntax * call StatuslineHighlights()
au ColorScheme * call StatuslineHighlights('ColorScheme')
au VimEnter * call StatuslineHighlights('VimEnter')
autocmd VimEnter,WinEnter,BufWinEnter * call <SID>RefreshStatus()
augroup END
endfunction
call s:setup_autocmds()
call StatuslineHighlights() " Init, also for reloading vimrc.
function! StatuslineQfLocCount(winnr, ...)
let bufnr = a:0 ? a:1 : winbufnr(a:winnr)
let r = {}
let loclist = getloclist(a:winnr)
let loclist_for_buffer = copy(loclist)
if bufnr isnot# 0
call filter(loclist_for_buffer, 'v:val.bufnr == '.bufnr)
endif
" if len(loclist) && !len(loclist_for_buffer)
" echom "Ignoring loclist for different buffer (copied on split)" bufnr
" endif
for [type, list] in [['ll', loclist_for_buffer], ['qf', getqflist()]]
let list_len = len(list)
let valid_len = list_len ? len(filter(copy(list), 'v:val.valid == 1')) : 0
let r[type] = [list_len, valid_len]
endfor
return r
endfunction
function! s:has_localdir(winnr)
if exists('s:has_localdir_with_winnr')
let args = get(s:, 'has_localdir_with_winnr', 1) ? [a:winnr] : []
return call('haslocaldir', args)
endif
try
let r = haslocaldir(a:winnr)
let s:has_localdir_with_winnr = 1
return r
catch /^Vim\%((\a\+)\)\=:\(E15\|E118\)/
let s:has_localdir_with_winnr = 0
return haslocaldir()
endtry
endfunction
function! MyStatusLine(winnr, active)
if a:active && a:winnr != winnr()
" Handle :only for winnr() > 1: there is no (specific) autocommand, and
" none when window 1+2 are the same buffer.
call <SID>RefreshStatus()
return
endif
let mode = mode()
let winwidth = winwidth(0)
let bufnr = winbufnr(a:winnr)
let modified = getbufvar(bufnr, '&modified')
let ft = getbufvar(bufnr, '&ft')
let readonly_flag = getbufvar(bufnr, '&readonly') && ft !=# 'help' ? 'â¯â¼' : ''
" Neomake status.
if exists('*neomake#statusline#get')
let neomake_status_str = neomake#statusline#get(bufnr, {
\ 'format_running': '⦠({{running_job_names}})',
\ 'format_ok': (a:active ? '%#NeomakeStatusGood#' : '%*').'â',
\ 'format_quickfix_ok': '',
\ 'format_quickfix_issues': (a:active ? '%s' : ''),
\ 'format_status': '%%(%s'
\ .(a:active ? '%%#StatColorHi2#' : '%%*')
\ .'%%)',
\ })
else
let neomake_status_str = ''
if exists('*neomake#GetJobs')
if exists('*neomake#config#get_with_source')
" TODO: optimize! gets called often!
let [disabled, source] = neomake#config#get_with_source('disabled', -1, {'bufnr': bufnr})
if disabled != -1
if disabled
let neomake_status_str .= source[0].'-'
else
let neomake_status_str .= source[0].'+'
endif
endif
endif
let neomake_status_str .= '%('.StatuslineNeomakeStatus(bufnr, 'â¦', 'â')
\ . (a:active ? '%#StatColorHi2#' : '%*')
\ . '%)'
endif
endif
let bt = getbufvar(bufnr, '&buftype')
let show_file_info = a:active && bt ==# ''
" Current or next/prev conflict markers.
let conflict_status = ''
if show_file_info
if getbufvar(bufnr, 'stl_display_conflict', -1) == -1
call setbufvar(bufnr, 'stl_display_conflict', s:display_conflict_default())
endif
if getbufvar(bufnr, 'stl_display_conflict')
let info = StatuslineGetConflictInfo()
if len(info) && len(info.text)
let text = info.text
if info.current_conflict >= 0
let text .= ' (#'.(info.current_conflict+1).')'
endif
let conflict_count = (info.current_conflict >= 0
\ ? (info.current_conflict+1).'/' : '')
\ .len(info.conflicts)
if !len(info.conflicts)
let conflict_count .= '('.len(info.marks).')'
endif
let conflict_info = conflict_count.' '.text
let conflict_status = '[ä·
'.conflict_info.']'
" TODO: use function (from Neomake?!) to not cause hit-enter prompt.
" TODO: should not include hilight groups.
" redraw
" echo conflict_info
endif
endif
endif
let use_cache = (
\ ft !=# 'qf'
\ && (!getbufvar(bufnr, 'git_dir')
\ || (getbufvar(bufnr, 'stl_cache_hunks') !=# 'UNSET'
\ && getbufvar(bufnr, 'stl_cache_fugitive', [0, ''])[0]))
\ )
if show_file_info
let has_localdir = s:has_localdir(a:winnr)
endif
let cwd = getcwd()
if use_cache
let cache_key = [a:winnr, a:active, bufnr, modified, ft, readonly_flag, mode, winwidth, &paste, conflict_status, neomake_status_str, cwd]
if show_file_info
let cache_key += [has_localdir]
endif
let win_cache = getwinvar(a:winnr, 'stl_cache', {})
let cache = get(win_cache, mode, [])
if len(cache) && cache[0] == cache_key
return cache[1]
endif
endif
" let active = a:winnr == winnr()
if modified
if a:active
let r = '%#StatColorModified#'
else
let r = '%#StatColorModifiedNC#'
endif
elseif a:active
let r = '%#StatColorMode#'
" elseif ft ==# 'qf'
" let r = '%#StatusLineQuickfixNC#'
else
let r = '%#StatusLineNC#'
endif
let r .= 'Â ' " nbsp for underline style
let part1 = ''
let part2 = []
if bt !=# ''
if ft ==# 'qf'
" TODO: rely on b:isLoc directly?!
let isLoc = My_get_qfloclist_type(bufnr) ==# 'll'
let part1 .= isLoc ? '[ll]' : '[qf]'
" Get title, removing default names.
let qf_title = substitute(getwinvar(a:winnr, 'quickfix_title', ''), '\v:(setloclist|getqflist)\(\)|((cgetexpr|lgetexpr).*$)', '', '')
" trim
if len(qf_title)
if qf_title[0] ==# ':'
let qf_title = qf_title[1:-1]
endif
let qf_title = substitute(qf_title, '^\_s*\(.\{-}\)\_s*$', '\1', '')
if len(qf_title)
let max_len = float2nr(round(&columns/3))
if len(qf_title) > max_len
let part1 .= ' '.qf_title[0:max_len].'â¦'
else
let part1 .= ' '.qf_title
endif
let part1 .= ' '
endif
endif
let [list_len, valid_len] = StatuslineQfLocCount(a:winnr, 0)[isLoc ? 'll' : 'qf']
if valid_len != list_len
let part1 .= '('.valid_len.'['.list_len.'])'
else
let part1 .= '('.list_len.')'
endif
" if part2 == ' '
" let part2 .= bufname('#')
" endif
endif
elseif ft ==# 'startify'
let part1 = '[startify]'
endif
if part1 ==# ''
" Shorten filename while reserving 30 characters for the rest of the statusline.
" let fname = "%{ShortenFilename('%', winwidth-30)}"
let fname = ShortenFilename(bufname(bufnr), winwidth-30, cwd)
" let ext = fnamemodify(fname, ':e')
let part1 .= fname
endif
let r .= part1
if modified
let r .= '[+]'
endif
let r .= readonly_flag
if show_file_info
let git_dir = getbufvar(bufnr, 'git_dir', '')
if git_dir !=# ''
if exists('*quickfixsigns#vcsdiff#GetHunkSummary')
let stl_cache_hunks = getbufvar(bufnr, 'stl_cache_hunks', 'UNSET')
if stl_cache_hunks ==# 'UNSET'
let hunks = quickfixsigns#vcsdiff#GetHunkSummary()
if len(hunks)
let stl_cache_hunks = join(filter(map(['+', '~', '-'], 'hunks[v:key] > 0 ? v:val.hunks[v:key] : 0'), 'v:val isnot 0'))
call setbufvar(bufnr, 'stl_cache_hunks', stl_cache_hunks)
endif
endif
if len(stl_cache_hunks)
let part2 += [stl_cache_hunks]
endif
endif
if exists('*fugitive#head')
let git_ftime = getftime(git_dir)
let stl_cache_fugitive = getbufvar(bufnr, 'stl_cache_fugitive', [0, ''])
if stl_cache_fugitive[0] != git_ftime
let stl_cache_fugitive = [git_ftime, '']
" NOTE: the commit itself is in the "filename" already.
let fug_head = fugitive#head(40)
if fug_head =~# '^\x\{40\}$'
let output = systemlist('git --git-dir='.shellescape(git_dir).' name-rev --name-only '.shellescape(fug_head))
if len(output)
let stl_cache_fugitive[1] = output[0]
if stl_cache_fugitive[1] ==# 'undefined'
let stl_cache_fugitive[1] = fug_head[0:6]
endif
else
let stl_cache_fugitive[1] = ''
endif
else
let stl_cache_fugitive[1] = fug_head
endif
" let fug_commit = fugitive#buffer().commit()
" if fug_commit != ''
" let named = systemlist(['git', 'name-rev', '--name-only', fug_commit])
" let stl_cache_fugitive = fug_commit[0:7] . '('.fugitive#head(7).')'
" else
" let stl_cache_fugitive = fugitive#head(7)
" endif
call setbufvar(bufnr, 'stl_cache_fugitive', stl_cache_fugitive)
endif
let part2 += ['î '.stl_cache_fugitive[1]]
endif
endif
if has_localdir
let part2 += ['[lcd]']
endif
endif
if modified && !a:active
let r .= ' %#StatusLineNC#'
endif
" if len(part2)
if a:active
" Add space for copy'n'paste of filename.
let r .= ' %#StatColorHi1To2#'
let r .= 'î°'
let r .= '%#StatColorHi2#'
else
let r .= ' '
endif
" elseif a:active
" " let r .= '%#StatColorHi1ToBg#'
" let r .= '%#StatColorHi2#'
" endif
let r .= '%<' " Cut off here, if necessary.
if len(part2)
let r .= ' '.join(part2).' '
" if a:active
" let r .= '%#StatColorHi2ToBg#'
" endif
endif
" if a:active
" let r .= "î°"
" let r .= '%#StatusLine#'
" let r .= '%*'
" else
" let r .= ' '
" endif
let r .= '%( ['
" let r .= '%Y' "filetype
let r .= '%H' "help file flag
let r .= '%W' "preview window flag
let r .= '%{&ff=="unix"?"":",".&ff}' "file format (if !=unix)
let r .= '%{strlen(&fenc) && &fenc!="utf-8"?",".&fenc:""}' "file encoding (if !=utf-8)
let r .= '] %)'
" Right part.
let r .= '%='
" if a:active
" let r .= '%#StatColorHi2ToBg#'
" let r .= 'î²'
" let r .= '%#StatColorHi2#'
" endif
" let r .= '%b,0x%-8B ' " Current character in decimal and hex representation
" let r .= ' %{FileSize()} ' " size of file (human readable)
let r .= conflict_status
let r .= neomake_status_str
" General qf/loclist counts.
" TODO: only if not managed by Neomake?!
" TODO: detect/handle grepper usage?!
" TODO: display qf info in tabline?!
if a:active && ft !=# 'qf'
for [list_type, counts] in items(StatuslineQfLocCount(a:winnr, bufnr))
let [list_len, valid_len] = counts
if list_len
" let r .= ' ' . (list_type == 'll' ? 'Lâ° ' : 'Qâ° ') . valid_len
" let r .= ' ' . (list_type == 'll' ? 'Lâ®' : 'Qâ®') . valid_len
let r .= ' ' . (list_type ==# 'll' ? 'Lâ¡' : 'Qâ¡') . valid_len
" let r .= ' '.qfloc_type.':'.valid_len
if valid_len != list_len
let r .= '['.list_len.']'
endif
" let r .= ']'
endif
endfor
endif
" XXX: always on 2nd level on the right side.
" if a:active
" let r .= '%#StatColorHi1To2Normal#'
" let r .= 'î²'
" let r .= '%#StatColorHi1#'
" else
" let r .= '%*'
" endif
if bufname(bufnr) ==# ''
if ft !=# ''
if index(['qf', 'startify'], ft) == -1
" let r .= '['.(isLoc ? 'll' : 'qf').']'
" else
let r .= '['.ft.']'
endif
endif
elseif ft ==# ''
let r .= '[no ft]'
endif
if a:active && &paste
let r .= ' %#StatColorHi2Bold#[P]%#StatColorHi2#'
endif
" " let r .= ' %-12(L%l/%L:C%c%V%) ' " Current line and column
" if !&number && !&relativenumber
let r .= ' î¡%l:%2v' " Current line and (virtual) column, %c is bytes.
" endif
" " let r .= '%l/%L' "cursor line/total lines
" " let r .= ' %P' "percent through file
" let r .= ' %2p%%' "percent through file
" let r .= ' [%n@%{winnr()}]' " buffer and windows nr
let r .= ' [%n.'.a:winnr " buffer and windows nr
if tabpagenr('$') > 1
let r .= '.'.tabpagenr()
endif
let r .= ']'
" let errors = ''
" if exists('*neomake#statusline#LoclistStatus')
" let errors = neomake#statusline#LoclistStatus()
" if errors == ''
" let errors = neomake#statusline#QflistStatus()
" endif
" if errors != ''
" " let r .= '%('
" let r .= '%#StatColorHi1ToError#î²'
" let r .= '%#StatColorError#'
" let r .= ' '.errors.' '
" endif
" endif
if use_cache
let win_cache[mode] = [cache_key, r]
call setwinvar(a:winnr, 'stl_cache', win_cache)
endif
return r
endfunction
unlockvar s:empty_conflict_cache
let s:empty_conflict_cache = {
\ 'conflicts': [],
\ 'marks': [],
\ 'part_begin_marks': [],
\ 'end_marks': [],
\ 'current_conflict': -1,
\ }
lockvar s:empty_conflict_cache
function! s:display_conflict_default(...)
" _MY_HAS_GIT_CONFLICTS gets set in the shell theme (+vi-git-unmerged).
return expand($_MY_HAS_GIT_CONFLICTS) || getwinvar(a:0 ? a:1 : winnr(), '&diff')
endfunction
function! StatuslineToggleConflictInfo()
let b:stl_display_conflict = !get(b:, 'stl_display_conflict', s:display_conflict_default())
if &verbose
echom b:stl_display_conflict ? 'Enabled.' : 'Disabled.'
endif
unlet! b:stl_cache_conflict
endfunction
command! StatuslineToggleConflictInfo call StatuslineToggleConflictInfo()
function! s:get_marker_desc(line)
let line = a:line[8:-1]
if !len(line)
return a:line[0:2]
endif
if line =~# '^\x\{40\}$'
let line = line[0:7]
endif
return a:line[0].' '.line
endfunction
function! StatuslineGetConflictInfo()
let prev_cursor = getcurpos()
lockvar prev_cursor
try
let mark_all = '\m^\(@@ .* @@\|[<=>|]\{7}[<=>|]\@!\)'
let mark_start = '\m^<\{7}<\@!'
let mark_part_begin = '\m^\(@@ .* @@\|[<=|]\{7}[<=|]\@!\)'
let mark_end = '\m>\{7}>\@!'
if !exists('b:stl_cache_conflict')
let b:stl_cache_conflict = [0, deepcopy(s:empty_conflict_cache)]
endif
if b:stl_cache_conflict[0] == b:changedtick
let r = b:stl_cache_conflict[1]
else
let r = deepcopy(s:empty_conflict_cache)
" Count conflicts and marks.
" TODO: use this data (more) instead of searching again below.
call cursor(1, 1)
while search(mark_all, 'cW')
let linenr = line('.')
let line = getline('.')
let type = line[0]
if type ==# '>'
" let r.end_marks += [linenr]
call insert(r.end_marks, linenr, 0)
else
" index(["<", "|", "="], v:val[1]) != -1')
call insert(r.part_begin_marks, linenr, 0)
if type ==# '<'
let r.conflicts += [linenr]
endif
endif
let r.marks += [[linenr, type]]
if linenr == line('$')
break
endif
call cursor(linenr + 1, 1)
endwhile
let b:stl_cache_conflict = [b:changedtick, r]
endif
if !len(r.marks)
return {}
endif
|
blueyed/dotfiles | d3b80a986ec83ba430d9b8c381829e7a8071d764 | usr/bin/with-indent.py: prepend class | diff --git a/usr/bin/with-indent.py b/usr/bin/with-indent.py
index 252bfc3..7ec79f1 100755
--- a/usr/bin/with-indent.py
+++ b/usr/bin/with-indent.py
@@ -1,96 +1,142 @@
#!/usr/bin/env python
"""Wrapper around commands that dedents/reindent partial code via textwrap.
Useful for ``black`` from an editor on selected code blocks.
Tests via ``pytest â¦/with-indent.py`` (the reason for the .py extension).
Ref: https://github.com/ambv/black/issues/796
"""
-
import textwrap
import sys
import subprocess
+def len_firstline(s):
+ return len(s.split("\n", 1)[0])
+
+
def dedent(stdin):
if not stdin:
return 0, stdin
dedented = textwrap.dedent(stdin)
- indent = stdin.index("\n") - dedented.index("\n")
- return indent, dedented
+ removed_indent = len_firstline(stdin) - len_firstline(dedented)
+ return removed_indent, dedented
+
+
+def prepare(stdin):
+ if stdin and stdin.startswith(" "):
+ removed_indent, dedented = dedent(stdin)
+ add_prefixes = max(1, removed_indent // 4)
+ prefix = ""
+ indent = " " * 4
+ for i in range(0, add_prefixes):
+ prefix += (indent * i) + "class wrappedforindent:\n"
+ stdin = prefix + stdin
+ return add_prefixes, stdin
+ return 0, stdin
def main(argv):
if "-" not in argv:
sys.stderr.write("should be used with stdin, i.e. -\n")
sys.exit(64)
- stdin = sys.stdin.read()
- indent, dedented = dedent(stdin)
+ orig_stdin = sys.stdin.read()
+ wrapped, dedented = prepare(orig_stdin)
proc = subprocess.Popen(
- argv,
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
+ argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
- stdin = dedented.encode()
- stdout, stderr = proc.communicate(stdin)
+ proc_stdin = dedented.encode()
+ stdout, stderr = proc.communicate(proc_stdin)
stdout = stdout.decode("utf8")
if proc.returncode == 0:
- if indent:
- prefix = " " * indent
- stdout = "".join(prefix + line for line in stdout.splitlines(True))
- sys.stdout.write(stdout)
+ while wrapped:
+ stdout = stdout[(stdout.index("\n") + 1) :]
+ wrapped -= 1
+ sys.stdout.write(stdout)
+ else:
+ # Output original input in case of error (similar to black does it, but
+ # we have changed it).
+ sys.stdout.write(orig_stdin)
+ sys.stdout.flush()
sys.stderr.write(stderr.decode("utf8"))
return proc.returncode
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
class Test:
def test_dedent(self):
assert dedent("") == (0, "")
assert dedent(" if True:\n pass\n") == (2, "if True:\n pass\n")
assert dedent(" if True:\npass\n") == (0, " if True:\npass\n")
+ def test_prepare(self):
+ assert prepare("") == (0, "")
+
+ wrap_prefix = "class wrappedforindent:\n"
+
+ in_ = " if True:\n pass\n"
+ assert prepare(in_) == (1, wrap_prefix + in_)
+
+ in_ = " if True:\npass\n"
+ assert prepare(in_) == (1, wrap_prefix + in_)
+
+ in_ = " pass\n"
+ assert prepare(in_) == (2, "{0} {0} pass\n".format(wrap_prefix))
+
def test_main_with_black(self, monkeypatch, capsys):
stdin = []
def read():
nonlocal stdin
return "\n".join(stdin)
monkeypatch.setattr(sys.stdin, "read", read)
def run_black():
return main(["black", "-q", "-"])
assert run_black() == 0
out, err = capsys.readouterr()
assert out == ""
assert err == ""
# No changes, but still indented.
stdin = [" if foo:", " pass"]
assert run_black() == 0
out, err = capsys.readouterr()
assert out.splitlines() == stdin
assert err == ""
# No changes, no indent.
stdin = ["def foo():", " pass"]
assert run_black() == 0
out, err = capsys.readouterr()
assert out.splitlines() == stdin
assert err == ""
+ # Fixed def.
+ stdin = [" def foo():", " pass"]
+ assert run_black() == 0
+ out, err = capsys.readouterr()
+ assert out.splitlines() == [" def foo():", " pass"]
+ assert err == ""
+
+ # Multiple indents.
+ stdin = [" pass"]
+ assert run_black() == 0
+ out, err = capsys.readouterr()
+ assert out.splitlines() == stdin
+ assert err == ""
+
# Invalid.
stdin = [" if foo:", "pass"]
assert run_black() == 123
out, err = capsys.readouterr()
assert out.splitlines() == stdin
- assert err == "error: cannot format -: Cannot parse: 2:0: pass\n"
+ assert err == "error: cannot format -: Cannot parse: 3:0: pass\n"
|
blueyed/dotfiles | 2aa68751fe827253ee7ae291ca87dc2b89bce32a | Add usr/bin/with-indent.py | diff --git a/usr/bin/with-indent.py b/usr/bin/with-indent.py
new file mode 100755
index 0000000..252bfc3
--- /dev/null
+++ b/usr/bin/with-indent.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env python
+"""Wrapper around commands that dedents/reindent partial code via textwrap.
+
+Useful for ``black`` from an editor on selected code blocks.
+
+Tests via ``pytest â¦/with-indent.py`` (the reason for the .py extension).
+
+Ref: https://github.com/ambv/black/issues/796
+"""
+
+import textwrap
+import sys
+import subprocess
+
+
+def dedent(stdin):
+ if not stdin:
+ return 0, stdin
+ dedented = textwrap.dedent(stdin)
+ indent = stdin.index("\n") - dedented.index("\n")
+ return indent, dedented
+
+
+def main(argv):
+ if "-" not in argv:
+ sys.stderr.write("should be used with stdin, i.e. -\n")
+ sys.exit(64)
+
+ stdin = sys.stdin.read()
+ indent, dedented = dedent(stdin)
+
+ proc = subprocess.Popen(
+ argv,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+ stdin = dedented.encode()
+ stdout, stderr = proc.communicate(stdin)
+ stdout = stdout.decode("utf8")
+ if proc.returncode == 0:
+ if indent:
+ prefix = " " * indent
+ stdout = "".join(prefix + line for line in stdout.splitlines(True))
+ sys.stdout.write(stdout)
+ sys.stderr.write(stderr.decode("utf8"))
+ return proc.returncode
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
+
+
+class Test:
+ def test_dedent(self):
+ assert dedent("") == (0, "")
+ assert dedent(" if True:\n pass\n") == (2, "if True:\n pass\n")
+ assert dedent(" if True:\npass\n") == (0, " if True:\npass\n")
+
+ def test_main_with_black(self, monkeypatch, capsys):
+ stdin = []
+
+ def read():
+ nonlocal stdin
+ return "\n".join(stdin)
+
+ monkeypatch.setattr(sys.stdin, "read", read)
+
+ def run_black():
+ return main(["black", "-q", "-"])
+
+ assert run_black() == 0
+ out, err = capsys.readouterr()
+ assert out == ""
+ assert err == ""
+
+ # No changes, but still indented.
+ stdin = [" if foo:", " pass"]
+ assert run_black() == 0
+ out, err = capsys.readouterr()
+ assert out.splitlines() == stdin
+ assert err == ""
+
+ # No changes, no indent.
+ stdin = ["def foo():", " pass"]
+ assert run_black() == 0
+ out, err = capsys.readouterr()
+ assert out.splitlines() == stdin
+ assert err == ""
+
+ # Invalid.
+ stdin = [" if foo:", "pass"]
+ assert run_black() == 123
+ out, err = capsys.readouterr()
+ assert out.splitlines() == stdin
+ assert err == "error: cannot format -: Cannot parse: 2:0: pass\n"
|
blueyed/dotfiles | d2deb349d4d748332ed99cafe6fbcbba515228a1 | vim: move isort command to after/ftplugin/python.vim | diff --git a/vim/after/ftplugin/python.vim b/vim/after/ftplugin/python.vim
new file mode 100644
index 0000000..976d717
--- /dev/null
+++ b/vim/after/ftplugin/python.vim
@@ -0,0 +1,3 @@
+" Sort Python imports.
+command! -range=% -nargs=* Isort :<line1>,<line2>! cd %:h 2>/dev/null >&2; isort --lines 79 <args> -
+command! -range=% -nargs=* Isortdiff :<line1>,<line2>w !cd %:h 2>/dev/null >&2; isort --lines 79 --diff <args> -
diff --git a/vimrc b/vimrc
index a2bd66e..65a4d90 100644
--- a/vimrc
+++ b/vimrc
@@ -2173,1026 +2173,1024 @@ if !exists('g:mrutab')
let g:mrutab = 1
endif
if tabpagenr('$') == 1
echomsg "There is only one tab!"
return
endif
if g:mrutab > tabpagenr('$') || g:mrutab == tabpagenr()
let g:mrutab = tabpagenr() > 1 ? tabpagenr()-1 : tabpagenr('$')
endif
exe "tabn ".g:mrutab
endfun
" Overrides Vim's gh command (start select-mode, but I don't use that).
" It can be simulated using v<C-g> also.
nnoremap <silent> gh :call MyGotoMRUTab()<CR>
" nnoremap ° :call MyGotoMRUTab()<CR>
" nnoremap <C-^> :call MyGotoMRUTab()<CR>
augroup MyTL
au!
au TabLeave * let g:mrutab = tabpagenr()
augroup END
" Map <A-1> .. <A-9> to goto tab or buffer.
for i in range(9)
exec 'nmap <M-' .(i+1).'> :call MyGotoNextTabOrBuffer('.(i+1).')<cr>'
endfor
fun! MyGetNonDefaultServername()
" Not for gvim in general (uses v:servername by default), and the global
" server ("G").
let sname = v:servername
if len(sname)
if has('nvim')
if sname !~# '^/tmp/nvim'
let sname = substitute(fnamemodify(v:servername, ':t:r'), '^nvim-', '', '')
return sname
endif
elseif sname !~# '\v^GVIM.*' " && sname =~# '\v^G\d*$'
return sname
endif
endif
return ''
endfun
fun! MyGetSessionName()
" Use / auto-set g:MySessionName
if !len(get(g:, "MySessionName", ""))
if len(v:this_session)
let g:MySessionName = fnamemodify(v:this_session, ':t:r')
elseif len($TERM_INSTANCE_NAME)
let g:MySessionName = substitute($TERM_INSTANCE_NAME, '^vim-', '', '')
else
return ''
end
endif
return g:MySessionName
endfun
" titlestring handling, with tmux support {{{
" Set titlestring, used to set terminal title (pane title in tmux).
set title
" Setup titlestring on BufEnter, when v:servername is available.
fun! MySetupTitleString()
let title = 'â '
let session_name = MyGetSessionName()
if len(session_name)
let title .= '['.session_name.'] '
else
" Add non-default servername to titlestring.
let sname = MyGetNonDefaultServername()
if len(sname)
let title .= '['.sname.'] '
endif
endif
" Call the function and use its result, rather than including it.
" (for performance reasons).
let title .= substitute(
\ ShortenFilenameWithSuffix('%', 15).' ('.ShortenPath(getcwd()).')',
\ '%', '%%', 'g')
if len(s:my_context)
let title .= ' {'.s:my_context.'}'
endif
" Easier to type/find than the unicode symbol prefix.
let title .= ' - vim'
" Append $_TERM_TITLE_SUFFIX (e.g. user@host) to title (set via zsh, used
" with SSH).
if len($_TERM_TITLE_SUFFIX)
let title .= $_TERM_TITLE_SUFFIX
endif
" Setup tmux window name, see ~/.dotfiles/oh-my-zsh/lib/termsupport.zsh.
if len($TMUX)
\ && (!len($_tmux_name_reset) || $_tmux_name_reset != $TMUX . '_' . $TMUX_PANE)
let tmux_auto_rename=systemlist('tmux show-window-options -t '.$TMUX_PANE.' -v automatic-rename 2>/dev/null')
" || $(tmux show-window-options -t $TMUX_PANE | grep '^automatic-rename' | cut -f2 -d\ )
" echom string(tmux_auto_rename)
if !len(tmux_auto_rename) || tmux_auto_rename[0] != "off"
" echom "Resetting tmux name to 0."
call system('tmux set-window-option -t '.$TMUX_PANE.' -q automatic-rename off')
call system('tmux rename-window -t '.$TMUX_PANE.' 0')
endif
endif
let &titlestring = title
" Set icon text according to &titlestring (used for minimized windows).
let &iconstring = '(v) '.&titlestring
endfun
augroup vimrc_title
au!
" XXX: might not get called with fugitive buffers (title is the (closed) fugitive buffer).
autocmd BufEnter,BufWritePost * call MySetupTitleString()
if exists('##TextChanged')
autocmd TextChanged * call MySetupTitleString()
endif
augroup END
" Make Vim set the window title according to &titlestring.
if !has('gui_running') && empty(&t_ts)
if len($TMUX)
let &t_ts = "\e]2;"
let &t_fs = "\007"
elseif &term =~ "^screen.*"
let &t_ts="\ek"
let &t_fs="\e\\"
endif
endif
fun! MySetSessionName(name)
let g:MySessionName = a:name
call MySetupTitleString()
endfun
"}}}
" Inserts the path of the currently edited file into a command
" Command mode: Ctrl+P
" cmap <C-P> <C-R>=expand("%:p:h") . "/" <CR>
" Change to current file's dir
nnoremap <Leader>cd :lcd <C-R>=expand('%:p:h')<CR><CR>
" yankstack, see also unite's history/yank {{{1
if &rtp =~ '\<yankstack\>'
" Do not map s/S (used by vim-sneak).
" let g:yankstack_yank_keys = ['c', 'C', 'd', 'D', 's', 'S', 'x', 'X', 'y', 'Y']
let g:yankstack_yank_keys = ['c', 'C', 'd', 'D', 'x', 'X', 'y', 'Y']
" Setup yankstack now to make yank/paste related mappings work.
call yankstack#setup()
endif
" Command-line maps to act on the current search (with incsearch). {{{
" E.g. '?foo$m' will move the matched line to where search started.
" Source: http://www.reddit.com/r/vim/comments/1yfzg2/does_anyone_actually_use_easymotion/cfkaxw5
" NOTE: with vim-oblique, '?' and '/' are mapped, and not in getcmdtype().
fun! MyCmdMapNotForColon(from, to, ...)
let init = a:0 ? 0 : 1
if init
exec printf('cnoremap <expr> %s MyCmdMapNotForColon("%s", "%s", 1)',
\ a:from, a:from, a:to)
return
endif
if index([':', '>', '@', '-', '='], getcmdtype()) == 0
return a:from
endif
return a:to
endfun
call MyCmdMapNotForColon('$d', "<CR>:delete<CR>``")
call MyCmdMapNotForColon('$m', "<CR>:move''<CR>")
call MyCmdMapNotForColon('$c', "<CR>:copy''<CR>")
call MyCmdMapNotForColon('$t', "<CR>:t''<CR>") " synonym for :copy
" Allow to quickly enter a single $.
cnoremap $$ $
" }}}
" sneak {{{1
" Overwrite yankstack with sneak maps.
" Ref: https://github.com/maxbrunsfeld/vim-yankstack/issues/39
nmap s <Plug>Sneak_s
nmap S <Plug>Sneak_S
xmap s <Plug>Sneak_s
xmap S <Plug>Sneak_S
omap s <Plug>Sneak_s
omap S <Plug>Sneak_S
" Use streak mode, also for Sneak_f/Sneak_t.
let g:sneak#streak=2
let g:sneak#s_next = 1 " clever-s
let g:sneak#target_labels = "sfjktunbqz/SFKGHLTUNBRMQZ?"
" Replace 'f' with inclusive 1-char Sneak.
nmap f <Plug>Sneak_f
nmap F <Plug>Sneak_F
xmap f <Plug>Sneak_f
xmap F <Plug>Sneak_F
omap f <Plug>Sneak_f
omap F <Plug>Sneak_F
" Replace 't' with exclusive 1-char Sneak.
nmap t <Plug>Sneak_t
nmap T <Plug>Sneak_T
xmap t <Plug>Sneak_t
xmap T <Plug>Sneak_T
omap t <Plug>Sneak_t
omap T <Plug>Sneak_T
" IDEA: just use 'f' for sneak, leaving 's' at its default.
" nmap f <Plug>Sneak_s
" nmap F <Plug>Sneak_S
" xmap f <Plug>Sneak_s
" xmap F <Plug>Sneak_S
" omap f <Plug>Sneak_s
" omap F <Plug>Sneak_S
" }}}1
" GoldenView {{{1
let g:goldenview__enable_default_mapping = 0
let g:goldenview__enable_at_startup = 0
" 1. split to tiled windows
nmap <silent> g<C-L> <Plug>GoldenViewSplit
" " 2. quickly switch current window with the main pane
" " and toggle back
nmap <silent> <F9> <Plug>GoldenViewSwitchMain
nmap <silent> <S-F9> <Plug>GoldenViewSwitchToggle
" " 3. jump to next and previous window
nmap <silent> <C-N> <Plug>GoldenViewNext
nmap <silent> <C-P> <Plug>GoldenViewPrevious
" }}}
" Duplicate a selection in visual mode
vmap D y'>p
" Press Shift+P while in visual mode to replace the selection without
" overwriting the default register
vmap P p :call setreg('"', getreg('0')) <CR>
" This is an alternative that also works in block mode, but the deleted
" text is lost and it only works for putting the current register.
"vnoremap p "_dp
" imap <C-L> <Space>=><Space>
" Toggle settings (see also vim-unimpaired).
" No pastetoggle: use `yo`/`yO` from unimpaired. Triggers also Neovim issue #6716.
" set pastetoggle=<leader>sp
nnoremap <leader>sc :ColorToggle<cr>
nnoremap <leader>sq :QuickfixsignsToggle<cr>
nnoremap <leader>si :IndentGuidesToggle<cr>
" Toggle mouse.
nnoremap <leader>sm :exec 'set mouse='.(&mouse == 'a' ? '' : 'a')<cr>:set mouse?<cr>
" OLD: Ack/Ag setup, handled via ag plugin {{{
" Use Ack instead of Grep when available
" if executable("ack")
" set grepprg=ack\ -H\ --nogroup\ --nocolor\ --ignore-dir=tmp\ --ignore-dir=coverage
" elseif executable("ack-grep")
" set grepprg=ack-grep\ -H\ --nogroup\ --nocolor\ --ignore-dir=tmp\ --ignore-dir=coverage
" else
" this is for Windows/cygwin and to add -H
" '$*' is not passed to the shell, but used by Vim
set grepprg=grep\ -nH\ $*\ /dev/null
" endif
if executable("ag")
let g:ackprg = 'ag --nogroup --nocolor --column'
" command alias, http://stackoverflow.com/a/3879737/15690
" if re-used, use a function
" cnoreabbrev <expr> Ag ((getcmdtype() is# ':' && getcmdline() is# 'Ag')?('Ack'):('Ag'))
endif
" 1}}}
" Automatic line numbers {{{
" NOTE: relativenumber might slow Vim down: https://code.google.com/p/vim/issues/detail?id=311
set norelativenumber
fun! MyAutoSetNumberSettings(...)
if get(w:, 'my_default_number_manually_set')
return
endif
let s:my_auto_number_ignore_OptionSet = 1
if a:0
exec 'setl' a:1
elseif &ft =~# 'qf\|cram\|vader'
setl number
elseif index(['nofile', 'terminal'], &buftype) != -1
\ || index(['help', 'fugitiveblame', 'fzf'], &ft) != -1
\ || bufname("%") =~ '^__'
setl nonumber
elseif winwidth(".") > 90
setl number
else
setl nonumber
endif
unlet s:my_auto_number_ignore_OptionSet
endfun
fun! MySetDefaultNumberSettingsSet()
if !exists('s:my_auto_number_ignore_OptionSet')
" echom "Manually set:" expand("<amatch>").":" v:option_old "=>" v:option_new
let w:my_auto_number_manually_set = 1
endif
endfun
augroup vimrc_number_setup
au!
au VimResized,FileType,BufWinEnter * call MyAutoSetNumberSettings()
if exists('##OptionSet')
au OptionSet number,relativenumber call MySetDefaultNumberSettingsSet()
endif
au CmdwinEnter * call MyAutoSetNumberSettings('number norelativenumber')
augroup END
fun! MyOnVimResized()
noautocmd WindoNodelay call MyAutoSetNumberSettings()
QfResizeWindows
endfun
nnoremap <silent> <c-w>= :wincmd =<cr>:call MyOnVimResized()<cr>
fun! MyWindoNoDelay(range, command)
" 100ms by default!
let s = g:ArgsAndMore_AfterCommand
let g:ArgsAndMore_AfterCommand = ''
call ArgsAndMore#Windo('', a:command)
let g:ArgsAndMore_AfterCommand = s
endfun
command! -nargs=1 -complete=command WindoNodelay call MyWindoNoDelay('', <q-args>)
augroup vimrc_on_resize
au!
au VimResized * WindoNodelay call MyOnVimResized()
augroup END
let &showbreak = '⪠'
set cpoptions+=n " Use line column for wrapped text / &showbreak.
function! CycleLineNr()
" states: [start] => norelative/number => relative/number (=> relative/nonumber) => nonumber/norelative
if exists('+relativenumber')
if &relativenumber
" if &number
" set relativenumber nonumber
" else
set norelativenumber nonumber
" endif
else
if &number
set number relativenumber
if !&number " Older Vim.
set relativenumber
endif
else
" init:
set norelativenumber number
endif
endif
" if &number | set relativenumber | elseif &relativenumber | set norelativenumber | else | set number | endif
else
set number!
endif
call SetNumberWidth()
endfunction
function! SetNumberWidth()
" NOTE: 'numberwidth' will get expanded by Vim automatically to fit the last line
if &number
if has('float')
let &l:numberwidth = float2nr(ceil(log10(line('$'))))
endif
elseif exists('+relativenumber') && &relativenumber
set numberwidth=2
endif
endfun
nnoremap <leader>sa :call CycleLineNr()<CR>
" Toggle numbers, but with relativenumber turned on
fun! ToggleLineNr()
if &number
if exists('+relativenumber')
set norelativenumber
endif
set nonumber
else
if exists('+relativenumber')
set relativenumber
endif
set number
endif
endfun
" map according to unimpaired, mnemonic "a on the left, like numbers".
nnoremap coa :call ToggleLineNr()<cr>
" Allow cursor to move anywhere in all modes.
nnoremap cov :set <C-R>=empty(&virtualedit) ? 'virtualedit=all' : 'virtualedit='<CR><CR>
"}}}
" Completion options.
" Do not use longest, but make Ctrl-P work directly.
set completeopt=menuone
" set completeopt+=preview " experimental
set wildmode=list:longest,list:full
" set complete+=kspell " complete from spell checking
" set dictionary+=spell " very useful (via C-X C-K), but requires ':set spell' once
" NOTE: gets handled dynamically via cursorcross plugin.
" set cursorline
" highlight CursorLine guibg=lightblue ctermbg=lightgray
" via http://www.reddit.com/r/programming/comments/7yk4i/vim_settings_per_directory/c07rk9d
" :au! BufRead,BufNewFile *path/to/project/*.* setlocal noet
" Maps for jk and kj to act as Esc (idempotent in normal mode).
" NOTE: jk moves to the right after Esc, leaving the cursor at the current position.
fun! MyRightWithoutError()
if col(".") < len(getline("."))
normal! l
endif
endfun
inoremap <silent> jk <esc>:call MyRightWithoutError()<cr>
" cno jk <c-c>
ino kj <esc>
" cno kj <c-c>
ino jh <esc>
" Improve the Esc key: good for `i`, does not work for `a`.
" Source: http://vim.wikia.com/wiki/Avoid_the_escape_key#Improving_the_Esc_key
" inoremap <Esc> <Esc>`^
" close tags (useful for html)
" NOTE: not required/used; avoid imap for leader.
" imap <Leader>/ </<C-X><C-O>
nnoremap <Leader>a :Ag<space>
nnoremap <Leader>A :Ag!<space>
" Make those behave like ci' , ci"
nnoremap ci( f(ci(
nnoremap ci{ f{ci{
nnoremap ci[ f[ci[
" NOTE: occupies `c`.
" vnoremap ci( f(ci(
" vnoremap ci{ f{ci{
" vnoremap ci[ f[ci[
" 'goto buffer'; NOTE: overwritten with Unite currently.
nnoremap gb :ls<CR>:b
function! MyIfToVarDump()
normal yyP
s/\mif\>/var_dump/
s/\m\s*\(&&\|||\)\s*/, /ge
s/\m{\s*$/; die();/
endfunction
" Toggle fold under cursor. {{{
fun! MyToggleFold()
if !&foldenable
echom "Folds are not enabled."
endif
let level = foldlevel('.')
echom "Current foldlevel:" level
if level == 0
return
endif
if foldclosed('.') > 0
" Open recursively
norm! zA
else
" Close only one level.
norm! za
endif
endfun
nnoremap <Leader><space> :call MyToggleFold()<cr>
vnoremap <Leader><space> zf
" }}}
" Easily switch between different fold methods {{{
" Source: https://github.com/pydave/daveconfig/blob/master/multi/vim/.vim/bundle/foldtoggle/plugin/foldtoggle.vim
nnoremap <Leader>sf :call ToggleFold()<CR>
function! ToggleFold()
if !exists("b:fold_toggle_options")
" By default, use the main three. I rarely use custom expressions or
" manual and diff is just for diffing.
let b:fold_toggle_options = ["syntax", "indent", "marker"]
if len(&foldexpr)
let b:fold_toggle_options += ["expr"]
endif
endif
" Find the current setting in the list
let i = match(b:fold_toggle_options, &foldmethod)
" Advance to the next setting
let i = (i + 1) % len(b:fold_toggle_options)
let old_method = &l:foldmethod
let &l:foldmethod = b:fold_toggle_options[i]
echom 'foldmethod: ' . old_method . " => " . &l:foldmethod
endfunction
function! FoldParagraphs()
setlocal foldmethod=expr
setlocal fde=getline(v:lnum)=~'^\\s*$'&&getline(v:lnum+1)=~'\\S'?'<1':1
endfunction
command! FoldParagraphs call FoldParagraphs()
" }}}
-" Sort Python imports.
-command! -range=% -nargs=* Isort :<line1>,<line2>! isort --lines 79 <args> -
" Map S-Insert to insert the "*" register literally.
if has('gui')
" nmap <S-Insert> <C-R><C-o>*
" map! <S-Insert> <C-R><C-o>*
nmap <S-Insert> <MiddleMouse>
map! <S-Insert> <MiddleMouse>
endif
" swap previously selected text with currently selected one (via http://vim.wikia.com/wiki/Swapping_characters,_words_and_lines#Visual-mode_swapping)
vnoremap <C-X> <Esc>`.``gvP``P
" Easy indentation in visual mode
" This keeps the visual selection active after indenting.
" Usually the visual selection is lost after you indent it.
"vmap > >gv
"vmap < <gv
" Make `<leader>gp` select the last pasted text
" (http://vim.wikia.com/wiki/Selecting_your_pasted_text).
nnoremap <expr> <leader>gp '`[' . strpart(getregtype(), 0, 1) . '`]'
" select last inserted text
" nnoremap gV `[v`]
nmap gV <leader>gp
if 1 " has('eval') {{{1
" Strip trailing whitespace {{{2
function! StripWhitespace(line1, line2, ...)
let s_report = &report
let &report=0
let pattern = a:0 ? a:1 : '[\\]\@<!\s\+$'
if exists('*winsaveview')
let oldview = winsaveview()
else
let save_cursor = getpos(".")
endif
exe 'keepjumps keeppatterns '.a:line1.','.a:line2.'substitute/'.pattern.'//e'
if exists('oldview')
if oldview != winsaveview()
redraw
echohl WarningMsg | echomsg 'Trimmed whitespace.' | echohl None
endif
call winrestview(oldview)
else
call setpos('.', save_cursor)
endif
let &report = s_report
endfunction
command! -range=% -nargs=0 -bar Untrail keepjumps call StripWhitespace(<line1>,<line2>)
" Untrail, for pastes from tmux (containing border).
command! -range=% -nargs=0 -bar UntrailSpecial keepjumps call StripWhitespace(<line1>,<line2>,'[\\]\@<!\s\+â\?$')
nnoremap <leader>st :Untrail<CR>
" Source/execute current line/selection/operator-pending. {{{
" This uses a temporary file instead of "exec", which does not handle
" statements after "endfunction".
fun! SourceViaFile() range
let tmpfile = tempname()
call writefile(getbufline(bufnr('%'), a:firstline, a:lastline), tmpfile)
exe "source" tmpfile
if &verbose
echom "Sourced ".(a:lastline - a:firstline + 1)." lines."
endif
endfun
command! -range SourceThis <line1>,<line2>call SourceViaFile()
map <Leader>< <Plug>(operator-source)
nnoremap <Leader><< :call SourceViaFile()<cr>
if &rtp =~ '\<operator-user\>'
call operator#user#define('source', 'Op_source_via_file')
" call operator#user#define_ex_command('source', 'SourceThis')
function! Op_source_via_file(motion_wiseness)
" execute (line("']") - line("'[") + 1) 'wincmd' '_'
'[,']call SourceViaFile()
endfunction
endif
" }}}
" Shortcut for <C-r>= in cmdline.
fun! RR(...)
return call(ProjectRootGuess, a:000)
endfun
command! RR ProjectRootLCD
command! RRR ProjectRootCD
" Follow symlink and lcd to root.
fun! MyLCDToProjectRoot()
let oldcwd = getcwd()
FollowSymlink
ProjectRootLCD
if oldcwd != getcwd()
echom "lcd:" oldcwd "=>" getcwd()
endif
endfun
nnoremap <silent> <Leader>fr :call MyLCDToProjectRoot()<cr>
" Toggle pattern (typically a char) at the end of line(s). {{{2
function! MyToggleLastChar(pat)
let view = winsaveview()
try
keepjumps keeppatterns exe 's/\([^'.escape(a:pat,'/').']\)$\|^$/\1'.escape(a:pat,'/').'/'
catch /^Vim\%((\a\+)\)\=:E486: Pattern not found/
keepjumps keeppatterns exe 's/'.escape(a:pat, '/').'$//'
finally
call winrestview(view)
endtry
endfunction
if has('vim_starting')
noremap <unique> <Leader>,; :call MyToggleLastChar(';')<cr>
noremap <unique> <Leader>,: :call MyToggleLastChar(':')<cr>
noremap <unique> <Leader>,, :call MyToggleLastChar(',')<cr>
noremap <unique> <Leader>,. :call MyToggleLastChar('.')<cr>
noremap <unique> <Leader>,qa :call MyToggleLastChar(' # noqa')<cr>
endif
" use 'en_us' also to work around matchit considering 'en' as 'endif'
set spl=de,en_us
" Toggle spellang: de => en => de,en
fun! MyToggleSpellLang()
if &spl == 'de,en'
set spl=en
elseif &spl == 'en'
set spl=de
else
set spl=de,en
endif
echo "Set spl to ".&spl
endfun
nnoremap <Leader>ss :call MyToggleSpellLang()<cr>
" Grep in the current (potential unsaved) buffer {{{2
" NOTE: obsolete with Unite.
command! -nargs=1 GrepCurrentBuffer call GrepCurrentBuffer('<args>')
fun! GrepCurrentBuffer(q)
let save_cursor = getpos(".")
let save_errorformat = &errorformat
try
set errorformat=%f:%l:%m
cexpr []
exe 'g/'.escape(a:q, '/').'/caddexpr expand("%") . ":" . line(".") . ":" . getline(".")'
cw
finally
call setpos('.', save_cursor)
let &errorformat = save_errorformat
endtry
endfunction
" nnoremap <leader><space> :GrepCurrentBuffer <C-r><C-w><cr>
" Commands to disable (and re-enable) all other tests in the current file. {{{2
command! DisableOtherTests call DisableOtherTests()
fun! DisableOtherTests()
let save_cursor = getpos(".")
try
%s/function test_/function ttest_/
call setpos('.', save_cursor)
call search('function ttest_', 'b')
normal wx
finally
call setpos('.', save_cursor)
endtry
endfun
command! EnableAllTests call EnableAllTests()
fun! EnableAllTests()
let save_cursor = getpos(".")
try
%s/function ttest_/function test_/
finally
call setpos('.', save_cursor)
endtry
endfun
" Twiddle case of chars / visual selection. {{{2
" source http://vim.wikia.com/wiki/Switching_case_of_characters
function! TwiddleCase(str)
if a:str ==# toupper(a:str)
let result = tolower(a:str)
elseif a:str ==# tolower(a:str)
let result = substitute(a:str,'\(\<\w\+\>\)', '\u\1', 'g')
else
let result = toupper(a:str)
endif
return result
endfunction
vnoremap ~ ygv"=TwiddleCase(@")<CR>Pgv
" }}}2
" Exit if the last window is a controlling one (NERDTree, qf). {{{2
" Note: vim-qf has something similar (but simpler).
function! s:QuitIfOnlyControlWinLeft()
if winnr("$") != 1
return
endif
" Alt Source: https://github.com/scrooloose/nerdtree/issues/21#issuecomment-3348390
" autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif
if (exists("t:NERDTreeBufName") && bufwinnr(t:NERDTreeBufName) != -1)
\ || &buftype == 'quickfix'
" NOTE: problematic with Unite's directory, when opening a file:
" :Unite from startify, then quitting Unite quits Vim; also with TMRU from
" startify.
" \ || &ft == 'startify'
q
endif
endfunction
augroup my_QuitIfOnlyControlWinLeft
au!
au BufEnter * nested call s:QuitIfOnlyControlWinLeft()
augroup END
" }}}2
" Check for file modifications automatically
" (current buffer only)
" Use :NoAutoChecktime to disable it (uses b:autochecktime)
fun! MyAutoCheckTime()
" only check timestamp for normal files
if &buftype != '' | return | endif
if ! exists('b:autochecktime') || b:autochecktime
checktime %
let b:autochecktime = 1
endif
endfun
augroup MyAutoChecktime
au!
" NOTE: nested is required for Neovim to trigger FileChangedShellPost
" autocommand with :checktime.
au FocusGained,BufEnter,CursorHold,InsertEnter * nested call MyAutoCheckTime()
augroup END
command! NoAutoChecktime let b:autochecktime=0
command! ToggleAutoChecktime let b:autochecktime=!get(b:, 'autochecktime', 0) | echom "b:autochecktime:" b:autochecktime
" vcscommand: only used as lib for detection (e.g. with airline). {{{1
" Setup b:VCSCommandVCSType.
function! SetupVCSType()
try
call VCSCommandGetVCSType(bufnr('%'))
catch /No suitable plugin/
endtry
endfunction
" do not call it automatically for now: vcscommands behaves weird (changing
" dirs), and slows simple scrolling (?) down (that might be quickfixsigns
" though)
if exists("*VCSCommandVCSType")
"au BufRead * call SetupVCSType()
endif
let g:VCSCommandDisableMappings = 1
" }}}1
" Open Windows explorer and select current file
if executable('explorer.exe')
command! Winexplorer :!start explorer.exe /e,/select,"%:p:gs?/?\\?"
endif
" do not pick last item automatically (non-global: g:tmru_world.tlib_pick_last_item)
let g:tlib_pick_last_item = 1
let g:tlib_inputlist_match = 'cnf'
let g:tmruSize = 2000
let g:tmru_resolve_method = '' " empty: ask, 'read' or 'write'.
let g:tlib#cache#purge_days = 365
let g:tmru_world = {}
let g:tmru_world.cache_var = 'g:tmru_cache'
let g:tmru#drop = 0 " do not `:drop` to files in existing windows. XXX: should use/follow &switchbuf maybe?! XXX: not documented
" Easytags
let g:easytags_on_cursorhold = 0 " disturbing, at least on work machine
let g:easytags_cmd = 'ctags'
let g:easytags_suppress_ctags_warning = 1
" let g:easytags_dynamic_files = 1
let g:easytags_resolve_links = 1
let g:easytags_async = 1
let g:detectindent_preferred_indent = 2 " used for sw and ts if only tabs
let g:detectindent_preferred_expandtab = 1
let g:detectindent_min_indent = 2
let g:detectindent_max_indent = 4
let g:detectindent_max_lines_to_analyse = 100
" command-t plugin {{{
let g:CommandTMaxFiles=50000
let g:CommandTMaxHeight=20
" NOTE: find finder does not skip g:CommandTWildIgnore for scanning!
" let g:CommandTFileScanner='find'
if has("autocmd") && exists(":CommandTFlush") && has("ruby")
" this is required for Command-T to pickup the setting(s)
au VimEnter * CommandTFlush
endif
if (has("gui_running"))
" use Alt-T in GUI mode
map <A-t> :CommandT<CR>
endif
map <leader>tt :CommandT<CR>
map <leader>t. :execute "CommandT ".expand("%:p:h")<cr>
map <leader>t :CommandT<space>
map <leader>tb :CommandTBuffer<CR>
" }}}
" Setup completefunc / base completion. {{{
" (used as fallback (manual)).
" au FileType python set completefunc=eclim#python#complete#CodeComplete
if !s:use_ycm && has("autocmd") && exists("+omnifunc")
augroup vimrc_base_omnifunc
au!
if &rtp =~ '\<eclim\>'
au FileType * if index(
\ ["php", "javascript", "css", "python", "xml", "java", "html"], &ft) != -1 |
\ let cf="eclim#".&ft."#complete#CodeComplete" |
\ exec 'setlocal omnifunc='.cf |
\ endif
" function! eclim#php#complete#CodeComplete(findstart, base)
" function! eclim#javascript#complete#CodeComplete(findstart, base)
" function! eclim#css#complete#CodeComplete(findstart, base)
" function! eclim#python#complete#CodeComplete(findstart, base) " {{{
" function! eclim#xml#complete#CodeComplete(findstart, base)
" function! eclim#java#complete#CodeComplete(findstart, base) " {{{
" function! eclim#java#ant#complete#CodeComplete(findstart, base)
" function! eclim#html#complete#CodeComplete(findstart, base)
else
au FileType css setlocal omnifunc=csscomplete#CompleteCSS
au FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags
au FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS
au FileType python setlocal omnifunc=pythoncomplete#Complete
au FileType xml setlocal omnifunc=xmlcomplete#CompleteTags
"au FileType ruby setlocal omnifunc=rubycomplete#Complete
endif
au FileType htmldjango set omnifunc=htmldjangocomplete#CompleteDjango
" Use syntaxcomplete, if there is no better omnifunc.
autocmd Filetype *
\ if &omnifunc == "" |
\ setlocal omnifunc=syntaxcomplete#Complete |
\ endif
augroup END
endif
" }}}
" supertab.vim {{{
if &rtp =~ '\<supertab\>'
" "context" appears to trigger path/file lookup?!
" let g:SuperTabDefaultCompletionType = 'context'
" let g:SuperTabContextDefaultCompletionType = "<c-p>"
" let g:SuperTabContextTextFileTypeExclusions =
" \ ['htmldjango', 'htmljinja', 'javascript', 'sql']
" auto select the first result when using 'longest'
"let g:SuperTabLongestHighlight = 1 " triggers bug with single match (https://github.com/ervandew/supertab/commit/e026bebf1b7113319fc7831bc72d0fb6e49bd087#commitcomment-297471)
" let g:SuperTabLongestEnhanced = 1 " involves mappings; requires
" completeopt =~ longest
let g:SuperTabClosePreviewOnPopupClose = 1
let g:SuperTabNoCompleteAfter = ['^', '\s']
" map <c-space> to <c-p> completion (useful when supertab 'context'
" defaults to something else).
" imap <nul> <c-r>=SuperTabAlternateCompletion("\<lt>c-p>")<cr>
" Setup completion with SuperTab: default to omnifunc (YouCompleteMe),
" then completefunc.
if s:use_ycm
" Call YouCompleteMe always (semantic).
" Let &completefunc untouched (eclim).
" Use autocommand to override any other automatic setting from filetypes.
" Use SuperTab chaining to fallback to "<C-p>".
" autocmd FileType *
" \ let g:ycm_set_omnifunc = 0 |
" \ set omnifunc=youcompleteme#OmniComplete
" let g:SuperTabDefaultCompletionType = "<c-x><c-o>"
fun! CompleteViaSuperTab(findstart, base)
let old = g:ycm_min_num_of_chars_for_completion
" 0 would trigger/force semantic completion (results in everything after
" a dot also).
let g:ycm_min_num_of_chars_for_completion = 1
let r = youcompleteme#Complete(a:findstart, a:base)
let g:ycm_min_num_of_chars_for_completion = old
return r
endfun
" completefunc is used by SuperTab's chaining.
" let ycm_set_completefunc = 0
autocmd FileType *
\ call SuperTabChain("CompleteViaSuperTab", "<c-p>") |
\ call SuperTabSetDefaultCompletionType("<c-x><c-u>") |
" Let SuperTab trigger YCM always.
" call SuperTabChain('youcompleteme#OmniComplete', "<c-p>") |
" let g:SuperTabChain = ['youcompleteme#Complete', "<c-p>"]
" set completefunc=SuperTabCodeComplete
" let g:SuperTabDefaultCompletionType = "<c-x><c-u>"
" autocmd FileType *
" \ call SuperTabChain('youcompleteme#Complete', "<c-p>") |
" \ call SuperTabSetDefaultCompletionType("<c-x><c-u>") |
else
let g:SuperTabDefaultCompletionType = "<c-p>"
autocmd FileType *
\ if &omnifunc != '' |
\ call SuperTabChain(&omnifunc, "<c-p>") |
\ call SuperTabSetDefaultCompletionType("<c-x><c-u>") |
\ elseif &completefunc != '' |
\ call SuperTabChain(&completefunc, "<c-p>") |
\ call SuperTabSetDefaultCompletionType("<c-x><c-u>") |
\ endif
endif
endif
" }}}
let g:LustyExplorerSuppressRubyWarning = 1 " suppress warning when vim-ruby is not installed
let g:EclimLargeFileEnabled = 0
let g:EclimCompletionMethod = 'completefunc' " Default, picked up via SuperTab.
" let g:EclimLogLevel = 6
" if exists(":EclimEnable")
" au VimEnter * EclimEnable
" endif
let g:EclimShowCurrentError = 0 " can be really slow, when used with PHP omnicompletion. I am using Syntastic anyway.
let g:EclimSignLevel = 0
let g:EclimLocateFileNonProjectScope = 'ag'
" Disable eclim's validation, prefer Syntastic.
" NOTE: patch pending to do so automatically (in eclim).
" does not work as expected, ref: https://github.com/ervandew/eclim/issues/199
let g:EclimFileTypeValidate = 0
" Disable HTML indenting via eclim, ref: https://github.com/ervandew/eclim/issues/332.
let g:EclimHtmlIndentDisabled = 1
let g:EclimHtmldjangoIndentDisabled = 1
" lua {{{
let g:lua_check_syntax = 0 " done via syntastic
let g:lua_define_omnifunc = 0 " must be enabled also (g:lua_complete_omni=1, but crashes Vim!)
let g:lua_complete_keywords = 0 " interferes with YouCompleteMe
let g:lua_complete_globals = 0 " interferes with YouCompleteMe?
let g:lua_complete_library = 0 " interferes with YouCompleteMe
let g:lua_complete_dynamic = 0 " interferes with YouCompleteMe
let g:lua_complete_omni = 0 " Disabled by default. Likely to crash Vim!
let g:lua_define_completion_mappings = 0
" }}}
" Prepend <leader> to visualctrlg mappings.
let g:visualctrg_no_default_keymappings = 1
silent! vmap <unique> <Leader><C-g> <Plug>(visualctrlg-briefly)
silent! vmap <unique> <Leader>g<C-g> <Plug>(visualctrlg-verbosely)
" Toggle quickfix window, using <Leader>qq. {{{2
" Based on: http://vim.wikia.com/wiki/Toggle_to_open_or_close_the_quickfix_window
nnoremap <Leader>qq :QFix<CR>
nnoremap <Leader>cc :QFix<CR>
command! -bang -nargs=? QFix call QFixToggle(<bang>0)
function! QFixToggle(forced)
if exists("t:qfix_buf") && bufwinnr(t:qfix_buf) != -1 && a:forced == 0
cclose
else
copen
let t:qfix_buf = bufnr("%")
endif
endfunction
" Used to track manual opening of the quickfix, e.g. via `:copen`.
augroup QFixToggle
au!
au BufWinEnter quickfix let g:qfix_buf = bufnr("%")
augroup END
" 2}}}
fun! MyHandleWinClose(event)
if get(t:, '_win_count', 0) > winnr('$')
" NOTE: '<nomodeline>' prevents the modelines to get applied, even if
" there are no autocommands being executed!
" That would cause folds to collaps after closing another window and
" coming back to e.g. this vimrc.
doautocmd <nomodeline> User MyAfterWinClose
endif
let t:_win_count = winnr('$')
endfun
augroup vimrc_user
au!
for e in ['BufWinEnter', 'WinEnter', 'BufDelete', 'BufWinLeave']
exec 'au' e '* call MyHandleWinClose("'.e.'")'
endfor
augroup END
endif " 1}}} eval guard
" Mappings {{{1
" Save.
nnoremap <silent> <C-s> :up<CR>:if &diff \| diffupdate \| endif<cr>
imap <C-s> <Esc><C-s>
" Swap n_CTRL-Z and n_CTRL-Y (qwertz layout; CTRL-Z should be next to CTRL-U).
nnoremap <C-z> <C-y>
nnoremap <C-y> <C-z>
" map! <C-Z> <C-O>:stop<C-M>
" zi: insert one char
" map zi i$<ESC>r
" defined in php-doc.vim
" nnoremap <Leader>d :call PhpDocSingle()<CR>
nnoremap <Leader>n :NERDTree<space>
nnoremap <Leader>n. :execute "NERDTree ".expand("%:p:h")<cr>
nnoremap <Leader>nb :NERDTreeFromBookmark<space>
nnoremap <Leader>nn :NERDTreeToggle<cr>
nnoremap <Leader>no :NERDTreeToggle<space>
nnoremap <Leader>nf :NERDTreeFind<cr>
nnoremap <Leader>nc :NERDTreeClose<cr>
nnoremap <S-F1> :tab<Space>:help<Space>
" ':tag {ident}' - difficult on german keyboard layout and not working in gvim/win32
nnoremap <F2> g<C-]>
" expand abbr (insert mode and command line)
noremap! <F2> <C-]>
|
blueyed/dotfiles | 8e15edfaae48abbdbafd21b79eaf983f03a0faee | timeit-shell: verbose, handle missing cmd | diff --git a/usr/bin/timeit-shell b/usr/bin/timeit-shell
index 4b55ab8..30690fe 100755
--- a/usr/bin/timeit-shell
+++ b/usr/bin/timeit-shell
@@ -1,15 +1,20 @@
#!/usr/bin/python
"""
Wrapper around Python's timeit to time a shell command.
"""
import sys
import timeit
+cmd = sys.argv[1:]
+if not cmd:
+ sys.stderr.write('%s: missing command\n' % sys.argv[0])
+ sys.exit(64)
+
timeit.main([
+ '--verbose',
'--setup', 'import subprocess',
'--',
- 'subprocess.Popen(%r, stdout=subprocess.PIPE).communicate()' % (
- sys.argv[1:],
- )])
+ 'subprocess.Popen(%r, stdout=subprocess.PIPE).communicate()' % cmd,
+])
|
blueyed/dotfiles | 9216ebe312b308bab16ddd420fc3a00c0db9d6e1 | firefox/thunderbird: send SIGCONT | diff --git a/usr/bin/firefox b/usr/bin/firefox
index 7871cec..e1ebee9 100755
--- a/usr/bin/firefox
+++ b/usr/bin/firefox
@@ -1,57 +1,74 @@
#!/bin/sh
# Automatically use a firefox/thunderbird profile based on $MY_X_SESSION_NAME.
# See also ./thunderbird.
-# XXX: get $program bin from after removing ourself from PATH.
program="$(basename "$0")"
+# XXX: get $program bin from after removing ourself from PATH.
+target_program="/usr/bin/$program"
if [ "$program" = thunderbird ]; then
profile_root=~/.$program/
# Start thunderbird with German date format.
# 'en_DK' would allow for ISO 8601 format.
# See: http://kb.mozillazine.org/Date_display_format#Configuring_the_date.2Ftime_system_settings_on_your_computer
export LC_TIME=de_DE.UTF-8
[ "$LC_ALL" != "$LC_TIME" ] && unset LC_ALL
elif [ "$program" = firefox ]; then
profile_root=~/.mozilla/$program/
# Indicate to awesome that the client window should get raised and jumped to.
echo "Firefox $(date +%s)" > /tmp/.awesome-raise-next-client
-
- # # Continue any stopped processed (via sigstop-if-not-focused).
- # pkill -CONT firefox
else
echo "$0: unexpected program basename: $program" >&2
fi
auto_use_profile=1
for i; do
case $i in
-P|--profile|--ProfileManager)
auto_use_profile=0
break ;;
esac
done
+# Send SIGCONT to main PID(s) of program.
+# This is necessary for it to receive the open-url request etc.
+# Once it gets focused also its childs will be continued.
+continue_program() {
+ this_tty=$(get-tty)
+ for pid in $(pgrep "$program"); do
+ pid_tty=$(get-tty "$pid")
+ if [ "$pid_tty" = "$this_tty" ]; then
+ if [ "$(ps -o state= "$pid")" = T ]; then
+ echo "$0: continuing $pid" >&2
+ kill -CONT "$pid"
+ fi
+ fi
+ done
+}
+
start_profile() {
profile_dir="$(find "$profile_root" -name "*.$1")"
shift
if [ -z "$profile_dir" ]; then
- echo "Could not find profile dir for $session_name." >&2
+ echo "$0: could not find profile dir for $session_name." >&2
return 1
else
- exec "/usr/bin/$program" --profile "$profile_dir" "$@"
+ continue_program
+ exec "$target_program" --profile "$profile_dir" "$@"
fi
}
if [ "$auto_use_profile" = 1 ]; then
session_name=$MY_X_SESSION_NAME
if [ -n "$session_name" ]; then
start_profile "$session_name" "$@"
if [ "$session_name" = personal ]; then
start_profile private "$@"
fi
fi
fi
-exec "/usr/bin/$program" "$@"
+
+continue_program
+exec "$target_program" "$@"
|
blueyed/dotfiles | c961796a5ed30f354c97f77ff60b6f3a4031777d | vim: statusline: use FugitiveReal | diff --git a/vim/plugin/statusline.vim b/vim/plugin/statusline.vim
index 63fe82f..6d6d742 100644
--- a/vim/plugin/statusline.vim
+++ b/vim/plugin/statusline.vim
@@ -1,749 +1,745 @@
" My custom statusline.
scriptencoding utf-8
if !has('statusline')
finish
endif
if &runtimepath =~# '\<airline\>'
finish
endif
if !exists('*ShortenFilename')
" when using a minimal vimrc etc.
finish
endif
set showtabline=2
" Helper functions {{{
function! FileSize()
let bytes = getfsize(expand('%:p'))
if bytes <= 0
return ''
endif
if bytes < 1024
return bytes
else
return (bytes / 1024) . 'K'
endif
endfunction
" Get property from highlighting group.
" Based on / copied from neomake#utils#GetHighlight
" (~/.dotfiles/vim/neobundles/neomake/autoload/neomake/utils.vim).
function! StatuslineGetHighlight(group, what) abort
let reverse = synIDattr(synIDtrans(hlID(a:group)), 'reverse')
let what = a:what
if reverse
let what = s:ReverseSynIDattr(what)
endif
if what[-1:] ==# '#'
let val = synIDattr(synIDtrans(hlID(a:group)), what, 'gui')
else
let val = synIDattr(synIDtrans(hlID(a:group)), what, 'cterm')
endif
if empty(val) || val == -1
let val = 'NONE'
endif
return val
endfunction
function! s:ReverseSynIDattr(attr) abort
if a:attr ==# 'fg'
return 'bg'
elseif a:attr ==# 'bg'
return 'fg'
elseif a:attr ==# 'fg#'
return 'bg#'
elseif a:attr ==# 'bg#'
return 'fg#'
endif
return a:attr
endfunction
function! StatuslineHighlights(...)
" NOTE: not much gui / termguicolors support!
" XXX: pretty much specific for solarized_base16.
" let event = a:0 ? a:1 : ''
" echom "Calling StatuslineHighlights" a:event
if &background ==# 'light'
hi StatColorHi1 ctermfg=21 ctermbg=7
hi StatColorHi1To2Normal ctermfg=7 ctermbg=8
hi link StatColorHi1To2 StatColorHi1To2Normal
exe 'hi StatColorHi1ToBg ctermfg=7 ctermbg='.StatuslineGetHighlight('StatusLine', 'bg')
hi StatColorHi2 ctermfg=21 ctermbg=8
exe 'hi StatColorHi2ToBg ctermfg=8 ctermbg='.StatuslineGetHighlight('StatusLine', 'bg')
exe 'hi StatColorNeomakeGood'
\ 'ctermfg=white'
\ 'ctermbg='.StatuslineGetHighlight('StatColorHi2', 'bg')
if get(g:, 'solarized_base16', 0)
hi VertSplit ctermbg=21 cterm=underline
endif
else " dark bg
" NOTE: using ctermfg=18 for bold support (for fg=0 color 8 is used for bold).
hi StatColorHi1 ctermfg=18 ctermbg=20
hi StatColorHi1To2Normal ctermfg=20 ctermbg=19
hi link StatColorHi1To2 StatColorHi1To2Normal
exe 'hi StatColorHi1ToBg ctermfg=7 ctermbg='.StatuslineGetHighlight('StatusLine', 'bg')
" NOTE: using ctermfg=18 for bold support (for fg=0 color 8 is used for bold).
hi StatColorHi2 ctermfg=18 ctermbg=19
exe 'hi StatColorHi2ToBg ctermfg=19 ctermbg='.StatuslineGetHighlight('StatusLine', 'bg')
exe 'hi StatColorNeomakeGood'
\ 'ctermfg=green'
\ 'ctermbg='.StatuslineGetHighlight('StatColorHi2', 'bg')
if get(g:, 'solarized_base16', 0)
hi VertSplit ctermbg=18
endif
endif
" exe 'hi StatColorCurHunk cterm=bold'
" \ ' ctermfg='.StatuslineGetHighlight('StatColorHi2', 'fg')
" \ ' ctermbg='.StatuslineGetHighlight('StatColorHi2', 'bg')
exe 'hi StatColorHi2Bold cterm=bold'
\ ' ctermfg='.StatuslineGetHighlight('StatColorHi2', 'fg')
\ ' ctermbg='.StatuslineGetHighlight('StatColorHi2', 'bg')
hi link StatColorMode StatColorHi1
" Force/set StatusLineNC based on VertSplit.
hi clear StatusLineNC
exe 'hi StatusLineNC'
\ . ' cterm=underline gui=underline'
\ . ' ctermfg=' . (&background ==# 'dark' ? 7 : 8)
\ . ' ctermbg=' . StatuslineGetHighlight('VertSplit', 'bg')
\ . ' guifg=' . StatuslineGetHighlight('CursorLine', 'bg#')
\ . ' guibg=' . StatuslineGetHighlight('VertSplit', 'bg#')
" exe 'hi StatusLineNC ctermfg=7 ctermbg=0 cterm=NONE'
" (&background ==# 'dark' ? 19 : 20)
" exe 'hi StatusLineQuickfixNC'
" \ . ' cterm=underline'
" \ . ' ctermfg=' . (&background ==# 'dark' ? 7 : 21)
" \ . ' ctermbg=' . (&background ==# 'dark' ? 7 : 7)
" hi link StatColorError Error
" exe 'hi StatColorErrorToBg'
" \ . ' ctermfg='.StatuslineGetHighlight('StatColorError', 'bg')
" \ . ' ctermbg='.StatuslineGetHighlight('StatusLine', 'bg')
" exe 'hi StatColorErrorToBgNC'
" \ . ' ctermfg='.StatuslineGetHighlight('StatColorError', 'bg')
" \ . ' ctermbg='.StatuslineGetHighlight('StatusLineNC', 'bg')
" exe 'hi StatColorHi1ToError'
" \ . ' ctermfg='.StatuslineGetHighlight('StatColorError', 'bg')
" \ . ' ctermbg='.StatuslineGetHighlight('StatColorHi1', 'bg')
" let error_color = StatuslineGetHighlight('Error', 'bg')
" if error_color == 'NONE'
" let error_color = StatuslineGetHighlight('Error', 'fg')
" endif
exe 'hi StatColorNeomakeError cterm=NONE'
\ 'ctermfg=white'
\ 'ctermbg=red'
exe 'hi StatColorNeomakeNonError cterm=NONE'
\ 'ctermfg=white'
\ 'ctermbg=yellow'
hi StatColorModified guibg=orange guifg=black ctermbg=yellow ctermfg=white
hi clear StatColorModifiedNC
exe 'hi StatColorModifiedNC'
\ . ' cterm=italic,underline'
\ . ' ctermfg=' . StatuslineGetHighlight('StatusLineNC', 'fg')
\ . ' ctermbg='.StatuslineGetHighlight('StatusLineNC', 'bg')
exe 'hi StatColorHi1To2Modified'
\ . ' ctermfg='.StatuslineGetHighlight('StatColorModified', 'bg')
\ . ' ctermbg='.StatuslineGetHighlight('StatColorHi2', 'bg')
exe 'hi StatColorHi1To2Insert'
\ . ' ctermfg=green'
\ . ' ctermbg='.StatuslineGetHighlight('StatColorHi2', 'bg')
" tabline
" exe 'hi TabLineSelSign cterm=underline'
" \ . ' ctermfg='.StatuslineGetHighlight('TabLineSel', 'bg')
" \ . ' ctermbg='.StatuslineGetHighlight('TabLine', 'bg')
exe 'hi TabLineCwd cterm=underline'
\ . ' ctermfg=green'
\ . ' ctermbg='.StatuslineGetHighlight('TabLine', 'bg')
exe 'hi TabLineNumber cterm=bold,underline'
\ . ' ctermfg='.StatuslineGetHighlight('TabLine', 'fg')
\ . ' ctermbg='.StatuslineGetHighlight('TabLine', 'bg')
hi! link TabLineSel StatColorHi1
exe 'hi TabLineNumberSel cterm=bold'
\ . ' ctermfg='.StatuslineGetHighlight('TabLineSel', 'fg')
\ . ' ctermbg='.StatuslineGetHighlight('TabLineSel', 'bg')
" hi! link TabLineNumberSel StatColorMode
endfunction
function! StatuslineModeColor(mode)
" echom "StatuslineModeColor" a:mode winnr()
if a:mode ==# 'i'
" hi StatColor guibg=orange guifg=black ctermbg=white ctermfg=black
" hi StatColor ctermbg=20 ctermfg=black
" hi StatColorMode cterm=reverse ctermfg=green
exe 'hi StatColorMode'
\ . ' ctermfg='.StatuslineGetHighlight('StatColorHi1', 'fg')
\ . ' ctermbg=green'
if &modified
hi link StatColorHi1To2 StatColorHi1To2Modified
else
hi link StatColorHi1To2 StatColorHi1To2Insert
endif
elseif a:mode ==# 'r' " via R
" hi StatColor guibg=#e454ba guifg=black ctermbg=magenta ctermfg=black
elseif a:mode ==# 'v'
" hi StatColor guibg=#e454ba guifg=black ctermbg=magenta ctermfg=black
else
" Reset
hi clear StatColorMode
if &modified
hi link StatColorMode StatColorModified
hi link StatColorHi1To2 StatColorHi1To2Modified
else
hi link StatColorMode StatColorHi1
" hi StatColorHi1To2 ctermfg=19 ctermbg=20
hi link StatColorHi1To2 StatColorHi1To2Normal
endif
endif
endfunction
let s:enabled = 1
function! s:RefreshStatus()
let winnr = winnr()
for nr in range(1, winnr('$'))
if s:enabled
let stl = getwinvar(nr, '&ft') ==# 'codi' ? '[codi]' : '%!MyStatusLine(' . nr . ', '.(winnr == nr).')'
else
let stl = ''
endif
call setwinvar(nr, '&statusline', stl)
endfor
endfunction
+" Clear cache of corresponding real buffer when saving a fugitive buffer.
function! StatuslineClearCacheFugitive(bufname)
- " Clear cache of corresponding real buffer when saving a fugitive buffer.
- if !exists('*fugitive#buffer')
+ if !exists('*FugitiveReal')
return
endif
- let fug_buffer = fugitive#buffer()
- let [gitdir, fug_path] = split(a:bufname, '//')[1:2]
- let fug_path = substitute(fug_path, '\v\w*/', '', '')
- let fug_path = fug_buffer.repo().tree(fug_path)
- let bufnr = bufnr(fug_path)
+ let bufnr = bufnr(FugitiveReal())
if bufnr != -1
call StatuslineClearCache(bufnr)
" Clear caches on / update alternative window(s).
" https://github.com/tomtom/quickfixsigns_vim/issues/67
let idx = 0
let prev_alt_winnr = winnr('#')
let prev_winnr = winnr()
for b in tabpagebuflist()
let idx += 1
if b == bufnr
exe 'noautocmd '.idx.'wincmd w'
QuickfixsignsSet
endif
endfor
if winnr() != prev_winnr || winnr('#') != prev_alt_winnr
exe 'noautocmd '.prev_alt_winnr.'wincmd w'
exe 'noautocmd '.prev_winnr.'wincmd w'
endif
endif
endfunction
function! StatuslineClearCache(...)
let bufnr = a:0 ? a:1 : bufnr('%')
if exists('*quickfixsigns#vcsdiff#ClearCache')
call quickfixsigns#vcsdiff#ClearCache(bufnr)
endif
call setbufvar(bufnr, 'stl_cache_hunks', 'UNSET')
call setbufvar(bufnr, 'stl_cache_fugitive', [0, ''])
endfun
function! OnNeomakeCountsChanged()
let [ll_counts, qf_counts] = GetNeomakeCounts(g:neomake_hook_context.bufnr, 0)
let cmd = ''
let file_mode = get(get(g:, 'neomake_hook_context', {}), 'file_mode')
" let file_mode = get(get(g:, 'neomake_current_maker', {}), 'file_mode')
if file_mode
for [type, c] in items(ll_counts)
if type ==# 'E'
let cmd = 'lwindow'
break
endif
endfor
else
for [type, c] in items(qf_counts)
if type ==# 'E'
let cmd = 'cwindow'
break
endif
endfor
endif
if cmd !=# ''
let aw = winnr('#')
let pw = winnr()
exec cmd
if winnr() != pw
" Go back, maintaining the '#' window.
exec 'noautocmd ' . aw . 'wincmd w'
exec 'noautocmd ' . pw . 'wincmd w'
endif
else
endif
endfunction
function! OnNeomakeFinished()
" Close empty lists.
" echom 'statusline: OnNeomakeFinished'
if g:neomake_hook_context.file_mode
if len(getloclist(0)) == 0
lwindow
endif
else
if len(getqflist()) == 0
cwindow
endif
endif
" XXX: brute-force
call s:RefreshStatus()
endfunction
augroup stl_neomake
au!
" autocmd User NeomakeMakerFinished unlet! b:stl_cache_neomake
" autocmd User NeomakeListAdded unlet! b:stl_cache_neomake
autocmd User NeomakeCountsChanged call OnNeomakeCountsChanged()
autocmd User NeomakeFinished call OnNeomakeFinished()
" autocmd User NeomakeMakerFinished call OnNeomakeMakerFinished()
augroup END
function! s:setup_autocmds()
augroup vimrc_statusline
au!
" au WinEnter * setlocal statusline=%!MyStatusLine('active')
" au WinLeave * setlocal statusline=%!MyStatusLine('inactive')
au InsertEnter * call StatuslineModeColor(v:insertmode)
" TODO: typically gets called for both InsertLeave and TextChanged?!
" BufWinEnter for when going to a tag etc to another buffer in the same win.
au InsertLeave,TextChanged,BufWritePost,ShellCmdPost,ShellFilterPost,BufWinEnter,WinEnter * call StatuslineModeColor('')
au TextChanged,BufWritePost,ShellCmdPost,ShellFilterPost,FocusGained * call StatuslineClearCache()
" Invalidate cache for corresponding buffer for a fugitive buffer.
au BufWritePost fugitive:///* call StatuslineClearCacheFugitive(expand('<amatch>'))
" au Syntax * call StatuslineHighlights()
au ColorScheme * call StatuslineHighlights('ColorScheme')
au VimEnter * call StatuslineHighlights('VimEnter')
autocmd VimEnter,WinEnter,BufWinEnter * call <SID>RefreshStatus()
augroup END
endfunction
call s:setup_autocmds()
call StatuslineHighlights() " Init, also for reloading vimrc.
function! StatuslineQfLocCount(winnr, ...)
let bufnr = a:0 ? a:1 : winbufnr(a:winnr)
let r = {}
let loclist = getloclist(a:winnr)
let loclist_for_buffer = copy(loclist)
if bufnr isnot# 0
call filter(loclist_for_buffer, 'v:val.bufnr == '.bufnr)
endif
" if len(loclist) && !len(loclist_for_buffer)
" echom "Ignoring loclist for different buffer (copied on split)" bufnr
" endif
for [type, list] in [['ll', loclist_for_buffer], ['qf', getqflist()]]
let list_len = len(list)
let valid_len = list_len ? len(filter(copy(list), 'v:val.valid == 1')) : 0
let r[type] = [list_len, valid_len]
endfor
return r
endfunction
function! s:has_localdir(winnr)
if exists('s:has_localdir_with_winnr')
let args = get(s:, 'has_localdir_with_winnr', 1) ? [a:winnr] : []
return call('haslocaldir', args)
endif
try
let r = haslocaldir(a:winnr)
let s:has_localdir_with_winnr = 1
return r
catch /^Vim\%((\a\+)\)\=:\(E15\|E118\)/
let s:has_localdir_with_winnr = 0
return haslocaldir()
endtry
endfunction
function! MyStatusLine(winnr, active)
if a:active && a:winnr != winnr()
" Handle :only for winnr() > 1: there is no (specific) autocommand, and
" none when window 1+2 are the same buffer.
call <SID>RefreshStatus()
return
endif
let mode = mode()
let winwidth = winwidth(0)
let bufnr = winbufnr(a:winnr)
let modified = getbufvar(bufnr, '&modified')
let ft = getbufvar(bufnr, '&ft')
let readonly_flag = getbufvar(bufnr, '&readonly') && ft !=# 'help' ? 'â¯â¼' : ''
" Neomake status.
if exists('*neomake#statusline#get')
let neomake_status_str = neomake#statusline#get(bufnr, {
\ 'format_running': '⦠({{running_job_names}})',
\ 'format_ok': (a:active ? '%#NeomakeStatusGood#' : '%*').'â',
\ 'format_quickfix_ok': '',
\ 'format_quickfix_issues': (a:active ? '%s' : ''),
\ 'format_status': '%%(%s'
\ .(a:active ? '%%#StatColorHi2#' : '%%*')
\ .'%%)',
\ })
else
let neomake_status_str = ''
if exists('*neomake#GetJobs')
if exists('*neomake#config#get_with_source')
" TODO: optimize! gets called often!
let [disabled, source] = neomake#config#get_with_source('disabled', -1, {'bufnr': bufnr})
if disabled != -1
if disabled
let neomake_status_str .= source[0].'-'
else
let neomake_status_str .= source[0].'+'
endif
endif
endif
let neomake_status_str .= '%('.StatuslineNeomakeStatus(bufnr, 'â¦', 'â')
\ . (a:active ? '%#StatColorHi2#' : '%*')
\ . '%)'
endif
endif
let bt = getbufvar(bufnr, '&buftype')
let show_file_info = a:active && bt ==# ''
" Current or next/prev conflict markers.
let conflict_status = ''
if show_file_info
if getbufvar(bufnr, 'stl_display_conflict', -1) == -1
call setbufvar(bufnr, 'stl_display_conflict', s:display_conflict_default())
endif
if getbufvar(bufnr, 'stl_display_conflict')
let info = StatuslineGetConflictInfo()
if len(info) && len(info.text)
let text = info.text
if info.current_conflict >= 0
let text .= ' (#'.(info.current_conflict+1).')'
endif
let conflict_count = (info.current_conflict >= 0
\ ? (info.current_conflict+1).'/' : '')
\ .len(info.conflicts)
if !len(info.conflicts)
let conflict_count .= '('.len(info.marks).')'
endif
let conflict_info = conflict_count.' '.text
let conflict_status = '[ä·
'.conflict_info.']'
" TODO: use function (from Neomake?!) to not cause hit-enter prompt.
" TODO: should not include hilight groups.
" redraw
" echo conflict_info
endif
endif
endif
let use_cache = (
\ ft !=# 'qf'
\ && (!getbufvar(bufnr, 'git_dir')
\ || (getbufvar(bufnr, 'stl_cache_hunks') !=# 'UNSET'
\ && getbufvar(bufnr, 'stl_cache_fugitive', [0, ''])[0]))
\ )
if show_file_info
let has_localdir = s:has_localdir(a:winnr)
endif
let cwd = getcwd()
if use_cache
let cache_key = [a:winnr, a:active, bufnr, modified, ft, readonly_flag, mode, winwidth, &paste, conflict_status, neomake_status_str, cwd]
if show_file_info
let cache_key += [has_localdir]
endif
let win_cache = getwinvar(a:winnr, 'stl_cache', {})
let cache = get(win_cache, mode, [])
if len(cache) && cache[0] == cache_key
return cache[1]
endif
endif
" let active = a:winnr == winnr()
if modified
if a:active
let r = '%#StatColorModified#'
else
let r = '%#StatColorModifiedNC#'
endif
elseif a:active
let r = '%#StatColorMode#'
" elseif ft ==# 'qf'
" let r = '%#StatusLineQuickfixNC#'
else
let r = '%#StatusLineNC#'
endif
let r .= 'Â ' " nbsp for underline style
let part1 = ''
let part2 = []
if bt !=# ''
if ft ==# 'qf'
" TODO: rely on b:isLoc directly?!
let isLoc = My_get_qfloclist_type(bufnr) ==# 'll'
let part1 .= isLoc ? '[ll]' : '[qf]'
" Get title, removing default names.
let qf_title = substitute(getwinvar(a:winnr, 'quickfix_title', ''), '\v:(setloclist|getqflist)\(\)|((cgetexpr|lgetexpr).*$)', '', '')
" trim
if len(qf_title)
if qf_title[0] ==# ':'
let qf_title = qf_title[1:-1]
endif
let qf_title = substitute(qf_title, '^\_s*\(.\{-}\)\_s*$', '\1', '')
if len(qf_title)
let max_len = float2nr(round(&columns/3))
if len(qf_title) > max_len
let part1 .= ' '.qf_title[0:max_len].'â¦'
else
let part1 .= ' '.qf_title
endif
let part1 .= ' '
endif
endif
let [list_len, valid_len] = StatuslineQfLocCount(a:winnr, 0)[isLoc ? 'll' : 'qf']
if valid_len != list_len
let part1 .= '('.valid_len.'['.list_len.'])'
else
let part1 .= '('.list_len.')'
endif
" if part2 == ' '
" let part2 .= bufname('#')
" endif
endif
elseif ft ==# 'startify'
let part1 = '[startify]'
endif
if part1 ==# ''
" Shorten filename while reserving 30 characters for the rest of the statusline.
" let fname = "%{ShortenFilename('%', winwidth-30)}"
let fname = ShortenFilename(bufname(bufnr), winwidth-30, cwd)
" let ext = fnamemodify(fname, ':e')
let part1 .= fname
endif
let r .= part1
if modified
let r .= '[+]'
endif
let r .= readonly_flag
if show_file_info
let git_dir = getbufvar(bufnr, 'git_dir', '')
if git_dir !=# ''
if exists('*quickfixsigns#vcsdiff#GetHunkSummary')
let stl_cache_hunks = getbufvar(bufnr, 'stl_cache_hunks', 'UNSET')
if stl_cache_hunks ==# 'UNSET'
let hunks = quickfixsigns#vcsdiff#GetHunkSummary()
if len(hunks)
let stl_cache_hunks = join(filter(map(['+', '~', '-'], 'hunks[v:key] > 0 ? v:val.hunks[v:key] : 0'), 'v:val isnot 0'))
call setbufvar(bufnr, 'stl_cache_hunks', stl_cache_hunks)
endif
endif
if len(stl_cache_hunks)
let part2 += [stl_cache_hunks]
endif
endif
if exists('*fugitive#head')
let git_ftime = getftime(git_dir)
let stl_cache_fugitive = getbufvar(bufnr, 'stl_cache_fugitive', [0, ''])
if stl_cache_fugitive[0] != git_ftime
let stl_cache_fugitive = [git_ftime, '']
" NOTE: the commit itself is in the "filename" already.
let fug_head = fugitive#head(40)
if fug_head =~# '^\x\{40\}$'
let output = systemlist('git --git-dir='.shellescape(git_dir).' name-rev --name-only '.shellescape(fug_head))
if len(output)
let stl_cache_fugitive[1] = output[0]
if stl_cache_fugitive[1] ==# 'undefined'
let stl_cache_fugitive[1] = fug_head[0:6]
endif
else
let stl_cache_fugitive[1] = ''
endif
else
let stl_cache_fugitive[1] = fug_head
endif
" let fug_commit = fugitive#buffer().commit()
" if fug_commit != ''
" let named = systemlist(['git', 'name-rev', '--name-only', fug_commit])
" let stl_cache_fugitive = fug_commit[0:7] . '('.fugitive#head(7).')'
" else
" let stl_cache_fugitive = fugitive#head(7)
" endif
call setbufvar(bufnr, 'stl_cache_fugitive', stl_cache_fugitive)
endif
let part2 += ['î '.stl_cache_fugitive[1]]
endif
endif
if has_localdir
let part2 += ['[lcd]']
endif
endif
if modified && !a:active
let r .= ' %#StatusLineNC#'
endif
" if len(part2)
if a:active
" Add space for copy'n'paste of filename.
let r .= ' %#StatColorHi1To2#'
let r .= 'î°'
let r .= '%#StatColorHi2#'
else
let r .= ' '
endif
" elseif a:active
" " let r .= '%#StatColorHi1ToBg#'
" let r .= '%#StatColorHi2#'
" endif
let r .= '%<' " Cut off here, if necessary.
if len(part2)
let r .= ' '.join(part2).' '
" if a:active
" let r .= '%#StatColorHi2ToBg#'
" endif
endif
" if a:active
" let r .= "î°"
" let r .= '%#StatusLine#'
" let r .= '%*'
" else
" let r .= ' '
" endif
let r .= '%( ['
" let r .= '%Y' "filetype
let r .= '%H' "help file flag
let r .= '%W' "preview window flag
let r .= '%{&ff=="unix"?"":",".&ff}' "file format (if !=unix)
let r .= '%{strlen(&fenc) && &fenc!="utf-8"?",".&fenc:""}' "file encoding (if !=utf-8)
let r .= '] %)'
" Right part.
let r .= '%='
" if a:active
" let r .= '%#StatColorHi2ToBg#'
" let r .= 'î²'
" let r .= '%#StatColorHi2#'
" endif
" let r .= '%b,0x%-8B ' " Current character in decimal and hex representation
" let r .= ' %{FileSize()} ' " size of file (human readable)
let r .= conflict_status
let r .= neomake_status_str
" General qf/loclist counts.
" TODO: only if not managed by Neomake?!
" TODO: detect/handle grepper usage?!
" TODO: display qf info in tabline?!
if a:active && ft !=# 'qf'
for [list_type, counts] in items(StatuslineQfLocCount(a:winnr, bufnr))
let [list_len, valid_len] = counts
if list_len
" let r .= ' ' . (list_type == 'll' ? 'Lâ° ' : 'Qâ° ') . valid_len
" let r .= ' ' . (list_type == 'll' ? 'Lâ®' : 'Qâ®') . valid_len
let r .= ' ' . (list_type ==# 'll' ? 'Lâ¡' : 'Qâ¡') . valid_len
" let r .= ' '.qfloc_type.':'.valid_len
if valid_len != list_len
let r .= '['.list_len.']'
endif
" let r .= ']'
endif
endfor
endif
" XXX: always on 2nd level on the right side.
" if a:active
" let r .= '%#StatColorHi1To2Normal#'
" let r .= 'î²'
" let r .= '%#StatColorHi1#'
" else
" let r .= '%*'
" endif
if bufname(bufnr) ==# ''
if ft !=# ''
if index(['qf', 'startify'], ft) == -1
" let r .= '['.(isLoc ? 'll' : 'qf').']'
" else
let r .= '['.ft.']'
endif
endif
elseif ft ==# ''
let r .= '[no ft]'
endif
if a:active && &paste
let r .= ' %#StatColorHi2Bold#[P]%#StatColorHi2#'
endif
" " let r .= ' %-12(L%l/%L:C%c%V%) ' " Current line and column
" if !&number && !&relativenumber
let r .= ' î¡%l:%2v' " Current line and (virtual) column, %c is bytes.
" endif
" " let r .= '%l/%L' "cursor line/total lines
" " let r .= ' %P' "percent through file
" let r .= ' %2p%%' "percent through file
" let r .= ' [%n@%{winnr()}]' " buffer and windows nr
let r .= ' [%n.'.a:winnr " buffer and windows nr
if tabpagenr('$') > 1
let r .= '.'.tabpagenr()
endif
let r .= ']'
" let errors = ''
" if exists('*neomake#statusline#LoclistStatus')
" let errors = neomake#statusline#LoclistStatus()
" if errors == ''
" let errors = neomake#statusline#QflistStatus()
" endif
" if errors != ''
" " let r .= '%('
" let r .= '%#StatColorHi1ToError#î²'
" let r .= '%#StatColorError#'
" let r .= ' '.errors.' '
" endif
" endif
if use_cache
|
blueyed/dotfiles | bb676fad98eaf2be4c6596c997fd35a5bbd66957 | tmux.weechat.conf: source global conf | diff --git a/tmux.weechat.conf b/tmux.weechat.conf
index fdda409..b15d797 100644
--- a/tmux.weechat.conf
+++ b/tmux.weechat.conf
@@ -1,13 +1,15 @@
+source ~/.tmux.conf
+
bind R source-file ~/.dotfiles/tmux.weechat.conf \; display "Reloaded (weechat)!"
# used in weechat
unbind -n M-1
unbind -n M-2
unbind -n M-3
unbind -n M-4
unbind -n M-5
unbind -n M-6
unbind -n M-7
unbind -n M-8
unbind -n M-9
unbind -n M-0
|
blueyed/dotfiles | 09ed1adb6d17124842b32ad5159e76107ec326b0 | tmux.weechat.conf: tmux.common.conf was removed/merged | diff --git a/Makefile b/Makefile
index cd48b8c..95a84fa 100644
--- a/Makefile
+++ b/Makefile
@@ -1,220 +1,220 @@
# Settings for debugging.
DRYRUN?=
DRYRUN_COND:=$(if $(DRYRUN),echo DRY: ,)
DEBUG=
VERBOSE=1
INSTALL_FILES := ackrc agignore aptitude/config ctags \
$(wildcard fonts/*) gemrc \
hgrc irbrc ignore oh-my-zsh pdbrc pentadactyl \
pentadactylrc profile railsrc \
screenrc screenrc.common subversion/servers \
terminfo tigrc tmux.conf vim vimrc Xresources \
xprofile \
config/mc/ini \
config/gnome-session/sessions \
$(filter-out config/mc config/gnome-session, $(wildcard config/*)) \
$(wildcard local/share/applications/*) \
$(patsubst %/,%,$(sort $(dir $(wildcard urxvt/ext/*/))))
-REMOVED_FILES:=pastebinit.xml config/lilyterm/default.conf vimpagerrc
+REMOVED_FILES:=pastebinit.xml config/lilyterm/default.conf vimpagerrc tmux.common.conf
# zshrc needs to get installed after submodules have been initialized
INSTALL_FILES_AFTER_SM := zshenv zshrc
# first install/update, and than migrate (might update submodules to be removed)
default: install migrate
install_files: install_files_before_sm install_files_after_sm
install: install_files_before_sm init_submodules install_files_after_sm
# Migrate existing dotfiles setup
migrate: .stamps .stamps/migrate_byobu.2 .stamps/dangling.2 .stamps/submodules_rm.25
migrate: .stamps/neobundle.1
migrate: .stamps/remove-byobu
migrate: .stamps/remove-autojump
migrate: .stamps/rename-xsessionrc-xprofile
migrate: check_removed_files
check_removed_files:
@for i in $(REMOVED_FILES); do \
target=~/.$$i; \
if [ -L $$target ] && ! [ -f $$target ]; then \
echo "NOTE: found obsolete/removed file (dangling symlink): $$target"; \
fi \
done
.stamps:
mkdir -p .stamps
.stamps/migrate_byobu.2:
@# .local/share/byobu is handled independently (preferred), only use ~/.byobu
$(RM) -r ~/.local/share/byobu
$(RM) ~/.byobu/keybindings ~/.byobu/profile ~/.byobu/profile.tmux ~/.byobu/status ~/.byobu/statusrc
$(RM) .stamps/migrate_byobu.*
touch $@
.stamps/dangling.2:
@echo "== Checking dangling/moved symlinks =="; \
for f in ~/.byobu ~/.byoburc ~/.sh ~/.bin ~/.gitignore \
~/.gitattributes.global ~/.gitconfig ~/.gitignore.global; do \
if [ -h "$$f" ]; then \
if [ -e "$$f" ]; then \
echo "Expected $$f to be a dangling symlink now. Skipping."; \
else \
echo "Removing old symlink: $$f"; \
$(RM) "$$f"; \
fi \
elif [ -f "$$f" ]; then \
echo "Found old $$f, but it is not a symlink. Please handle it manually."; \
fi \
done
touch $@
.stamps/submodules_rm.25:
rm_bundles="vim/bundle/DBGp-Remote-Debugger-Interface vim/bundle/dbext vim/bundle/xdebug vim/bundle/taglist vim/bundle/autocomplpop vim/bundle/tplugin vim/bundle/powerline vim/bundle/snipmate-snippets vim/bundle/autoclose vim/bundle/zoomwin vim/bundle/snippets vim/bundle/outlook lib/git-meld vim/bundle/powerline-vim vim/bundle/occur vim/vendor/UltiSnips vim/bundle/colorscheme-gruvbox config/awesome/awpomodoro vim/bundle/isort vim/bundle/targets lib/legit lib/base16/base16-gnome-terminal lib/vimpager lib/powerline lib/sack lib/docker-zsh-completion"; \
for i in $$rm_bundles; do \
[ ! -d "$$i" ] || [ ! -e "$$i/.git" ] && continue ; \
( cd $$i && gst=$$(git status --short --untracked-files=normal 2>&1) && [ "$$gst" = "" ] || { echo "Repo not clean ($$i): $$gst" ; false ; } ; ) \
&& $(RM) -r $$i \
|| { echo "Skipping removal of submodule $$i" ; } ; \
done
touch $@
.stamps/neobundle.1:
@echo '== Migrating to neobundles =='
@echo Use the following to inspect any changes to vim/pathogen submodules:
@echo 'cd vim/bundle; for i in $$(git ls-files -o); do echo $$i; ( test -f $$i && (git diff --exit-code;) || ( cd $$i && git diff --exit-code; ) ) || break; done'
@echo To delete all untracked bundles:
@echo 'rm $$(git ls-files -o vim/bundle) -r'
touch $@
.stamps/remove-byobu:
@echo "== byobu has been removed =="
@echo "You should 'rm ~/.byobu -rf' manually."
touch $@
.stamps/remove-autojump:
@echo "== autojump has been removed =="
@echo "You should 'rm ~/.autojump ~/.local/share/autojump -rf' manually."
touch $@
.stamps/rename-xsessionrc-xprofile:
@echo "== .xsessionrc has been moved to .xprofile =="
@echo "You should 'rm -i ~/.xsessionrc manually."
touch $@
# Target to install a copy of .dotfiles, where Git is not available
# (e.g. distributed with rsync)
install_checkout: install_files install_files_after_sm
# Handle Git submodules
init_submodules: update_submodules
update_submodules: sync_submodules
@# Requires e.g. git 1.7.5.4
git submodule update --init --quiet
@# Simulate `--recursive`, but not for vim/bundle/command-t:
@# (https://github.com/wincent/Command-T/pull/23)
# cd vim/bundle/operator-replace && git submodule update --init --quiet
# cd vim/bundle/operator-user && git submodule update --init --quiet
# cd vim/bundle/YouCompleteMe && git submodule update --init --quiet
sync_submodules:
git submodule sync --quiet
ALL_FILES := $(INSTALL_FILES) $(INSTALL_FILES_AFTER_SM)
# Add dirs additionally with trailing slash removed.
ALL_FILES := $(sort $(ALL_FILES) $(patsubst %/,%,$(ALL_FILES)))
.PHONY: $(ALL_FILES)
install_files_before_sm: $(addprefix ~/.,$(INSTALL_FILES))
install_files_after_sm: $(addprefix ~/.,$(INSTALL_FILES_AFTER_SM))
define func-install
$(if $(DEBUG),,@){ test -h $(1) && test -e $(1) && $(if $(VERBOSE),echo "Already installed: $(1)",); } \
|| { test -f $(1) && echo "Skipping existing target (file): $(1)"; } \
|| { test -d $(1) && echo "Skipping existing target (dir): $(1)"; } \
|| { test ! -e "$(2)" && echo "Target does not exist: $(2)" ; } \
|| { $(DRYRUN_COND) mkdir -p $(shell dirname $(1)) \
&& $(DRYRUN_COND) ln -sfn --relative $(2) $(1) \
&& echo "Installed symlink: $(1)" ; }
endef
# install_files handler: test for (existing) symlinks, skipping existing files/dirs.
~/.%: % ;
$(ALL_FILES):
$(call func-install,~/.$@,$@)
diff_files: $(ALL_FILES)
@for i in $^ ; do \
test -h "$$HOME/.$$i" && continue; \
echo ===== $$HOME/.$$i $(CURDIR)/$$i ================ ; \
ls -lh "$$HOME/.$$i" "$(CURDIR)/$$i" ; \
if cmp "$$HOME/.$$i" "$(CURDIR)/$$i" ; then \
echo "Same contents." ; \
else \
diff -u "$$HOME/.$$i" "$(CURDIR)/$$i" ; \
fi ; \
printf "Replace regular file/dir ($$HOME/.$$i) with symlink? (y/n) " ; \
read yn ; \
if [ "x$$yn" = xy ]; then \
command rm -rf "$$HOME/.$$i" ; \
ln -sfn "$(CURDIR)/$$i" "$$HOME/.$$i" ; \
fi \
done
setup_full: setup_ppa install_programs install_zsh setup_zsh
setup_ppa:
# TODO: make it work with missing apt-add-repository (Debian Squeeze)
sudo apt-add-repository ppa:git-core/ppa
install_programs:
sudo apt-get update
sudo apt-get install aptitude
sudo aptitude install console-terminus git rake vim-gnome xfonts-terminus xfonts-terminus-oblique exuberant-ctags
# extra
sudo aptitude install ttf-mscorefonts-installer
install_zsh:
sudo aptitude install zsh
install_commandt_module:
cd ~/.dotfiles/vim/bundle/command-t && \
rake make
install_programs_rpm: install_zsh_rpm
sudo yum install git rubygem-rake ctags
install_zsh_rpm:
sudo yum install zsh
ZSH_PATH := /bin/zsh
ifneq ($(wildcard /usr/bin/zsh),)
ZSH_PATH := /usr/bin/zsh
endif
ifneq ($(wildcard /usr/local/bin/zsh),)
ZSH_PATH := /usr/local/bin/zsh
endif
setup_sudo:
@user_file=/etc/sudoers.d/$$USER ; \
if [ -e $$user_file ] ; then \
echo "$$user_file exists already." ; exit 1 ; \
fi ; \
printf '# sudo config for %s\nDefaults:%s !tty_tickets,timestamp_timeout=60\n' $$USER $$USER | sudo tee $$user_file.tmp > /dev/null \
&& sudo chmod 440 $$user_file.tmp \
&& sudo visudo -c -f $$user_file.tmp \
&& sudo mv $$user_file.tmp $$user_file
setup_zsh:
@# Check that ZSH_PATH is listed in /etc/shells
@grep -qF "${ZSH_PATH}" /etc/shells || { \
echo "Adding ${ZSH_PATH} to /etc/shells" ; \
echo "${ZSH_PATH}" | sudo tee -a /etc/shells > /dev/null ; \
}
@if [ "$(shell getent passwd $$USER | cut -f7 -d:)" != "${ZSH_PATH}" ]; then \
chsh -s ${ZSH_PATH} ; \
fi
@# obsolete/buggy?!: -o "$(shell zsh -i -c env|grep '^ZSH=')" != "" ]
# Upgrade all submodules
upgrade:
rake upgrade
tags:
# ctags -R --exclude=YouCompleteMe .
# ag --ignore YouCompleteMe -g . | ctags --links=no -L-
ag -g . | ctags --links=no -L-
.PHONY: tags
diff --git a/tmux.weechat.conf b/tmux.weechat.conf
index f0579a5..fdda409 100644
--- a/tmux.weechat.conf
+++ b/tmux.weechat.conf
@@ -1,16 +1,13 @@
-# Source common config between byobu and tmux
-source ~/.tmux.common.conf
-
bind R source-file ~/.dotfiles/tmux.weechat.conf \; display "Reloaded (weechat)!"
# used in weechat
unbind -n M-1
unbind -n M-2
unbind -n M-3
unbind -n M-4
unbind -n M-5
unbind -n M-6
unbind -n M-7
unbind -n M-8
unbind -n M-9
unbind -n M-0
|
blueyed/dotfiles | 4c39b6ccdd43d118a92413cd419ea32a05e61e1e | vimrc: fix neomake setup without bat info and/or timers | diff --git a/vimrc b/vimrc
index 16ce4b1..a2bd66e 100644
--- a/vimrc
+++ b/vimrc
@@ -643,1034 +643,1038 @@ set selection=inclusive
" set clipboard=unnamed
" Do not mess with X selection by default (only in modeless mode).
if !has('nvim')
set clipboard-=autoselect
set clipboard+=autoselectml
endif
if has('mouse')
set mouse=nvi " Enable mouse (not for command line mode)
if !has('nvim')
" Make mouse work with Vim in tmux
try
set ttymouse=sgr
catch
set ttymouse=xterm2
endtry
endif
endif
set showmatch " show matching pairs
set matchtime=3
" Jump to matching bracket when typing the closing one.
" Deactivated, causes keys to be ignored when typed too fast (?).
"inoremap } }<Left><c-o>%<c-o>:sleep 500m<CR><c-o>%<c-o>a
"inoremap ] ]<Left><c-o>%<c-o>:sleep 500m<CR><c-o>%<c-o>a
"inoremap ) )<Left><c-o>%<c-o>:sleep 500m<CR><c-o>%<c-o>a
set sessionoptions+=unix,slash " for unix/windows compatibility
set nostartofline " do not go to start of line automatically when moving
" Use both , and Space as leader.
if 1 " has('eval')
let mapleader = ","
endif
" But not for imap!
nmap <space> <Leader>
vmap <space> <Leader>
" scrolloff: number of lines visible above/below the cursor.
" Special handling for &bt!="" and &diff.
set scrolloff=3
if has('autocmd')
fun! MyAutoScrollOff() " {{{
if exists('b:no_auto_scrolloff')
return
endif
if &ft == 'help'
let scrolloff = 999
elseif &buftype != ""
" Especially with quickfix (mouse jumping, more narrow).
let scrolloff = 0
elseif &diff
let scrolloff = 10
else
let scrolloff = 3
endif
if &scrolloff != scrolloff
let &scrolloff = scrolloff
endif
endfun
augroup set_scrolloff
au!
au BufEnter,WinEnter * call MyAutoScrollOff()
if exists('##TermOpen') " neovim
au TermOpen * set sidescrolloff=0 scrolloff=0
endif
augroup END
" Toggle auto-scrolloff handling.
fun! MyAutoScrollOffToggle()
if exists('b:no_auto_scrolloff')
unlet b:no_auto_scrolloff
call MyAutoScrollOff()
echom "auto-scrolloff: enabled"
else
let b:no_auto_scrolloff=1
let &scrolloff=3
echom "auto-scrolloff: disabled"
endif
endfun
nnoremap <leader>so :call MyAutoScrollOffToggle()<cr>
endif " }}}
set sidescroll=1
set sidescrolloff=10
set commentstring=#\ %s
" 'suffixes' get ignored by tmru
set suffixes+=.tmp
set suffixes+=.pyc
" set suffixes+=.sw?
" case only matters with mixed case expressions
set ignorecase smartcase
set smarttab
" NOTE: ignorecase also affects ":tj"/":tselect"!
" https://github.com/vim/vim/issues/712
if exists('+tagcase')
set tagcase=match
endif
set lazyredraw " No redraws in macros.
set wildmenu
" move cursor instead of selecting entries (wildmenu)
cnoremap <Left> <Space><BS><Left>
cnoremap <Right> <Space><BS><Right>
" consider existing windows (but not tabs) when opening files, e.g. from quickfix
" set switchbuf=useopen
" set switchbuf=split
" Display extra whitespace
" set list listchars=tab:»·,trail:·,eol:¬,nbsp:_,extends:â¯,precedes:â®
" set fillchars=stl:^,stlnc:-,vert:\|,fold:-,diff:-
" set fillchars=vert:\|,fold:·,stl:\ ,stlnc:â,diff:⣿
set fillchars=vert:\ ,fold:\ ,stl:\ ,stlnc:\ ,diff:⣿
" Do not display "Pattern not found" messages during YouCompleteMe completion.
" Patch: https://groups.google.com/forum/#!topic/vim_dev/WeBBjkXE8H8
if 1 && exists(':try')
try
set shortmess+=c
" Catch "Illegal character" (and its translations).
catch /E539: /
endtry
endif
set nolist
set listchars=tab:»·,trail:·,eol:¬,nbsp:_,extends:»,precedes:«
" Experimental: setup listchars diffenrently for insert mode {{{
" fun! MySetupList(mode)
" if a:mode == 'i'
" let b:has_list=&list
" if ! &list
" " set listchars-=eol:¬
" endif
" set list
" else
" if !(exists('b:has_list') && b:has_list)
" set nolist
" endif
" " set listchars+=eol:¬
" endif
" endfun
" augroup trailing
" au!
" au InsertEnter * call MySetupList('i')
" au InsertLeave * call MySetupList('n')
" augroup END
" }}}
" Generic GUI options. {{{2
if has('gui_running')
set guioptions-=T " hide toolbar
if has('vim_starting')
" TODO: dependent on monitor size.
set lines=50 columns=90
endif
set guifont=Ubuntu\ Mono\ For\ Powerline\ 12,DejaVu\ Sans\ Mono\ 10
endif
" }}}1
" Generic mappings. {{{
" Repeat last f/t in opposite direction.
if &rtp =~ '\<sneak\>'
nmap <Leader>; <Plug>SneakPrevious
else
nnoremap <Leader>; ,
endif
nnoremap <Leader><c-l> :redraw!<cr>
" Optimize mappings on German keyboard layout. {{{
" Maps initially inspired by the intl US keyboard layout.
" Not using langmap, because of bugs / issues, e.g.:
" - used with input for LustyBufferGrep
" Not using a function to have this in minimal Vims, too.
" `sunmap` is used to use the key as-is in select mode.
map ö :
sunmap ö
map - /
sunmap -
map _ ?
sunmap _
map ü [
sunmap ü
map + ]
sunmap +
" TODO: ä
" Swap ' and ` keys (` is more useful, but requires shift on a German keyboard) {{{
noremap ' `
sunmap '
noremap ` '
sunmap `
noremap g' g`
sunmap g'
noremap g` g'
sunmap g`
" }}}
" Align/tabularize text.
vmap <Enter> <Plug>(EasyAlign)
if 1 " has('eval') / `let` may not be available.
" Maps to unimpaired mappings by context: diff, loclist or qflist.
" Falls back to "a" for args.
fun! MySetupUnimpairedShortcut()
if &diff
let m = 'c'
" diff-obtain and goto next.
nmap dn do+c
elseif len(getqflist())
let m = 'q'
elseif len(getloclist(0))
let m = 'l'
else
let m = 'n'
endif
if get(b:, '_mysetupunimpairedmaps', '') == m
return
endif
let b:_mysetupunimpairedmaps = m
" Backward.
exec 'nmap <buffer> üü ['.m
exec 'nmap <buffer> +ü ['.m
exec 'nmap <buffer> <Leader>ü ['.m
exec 'nmap <buffer> <A-ü> ['.m
" Forward.
exec 'nmap <buffer> ++ ]'.m
exec 'nmap <buffer> ü+ ]'.m
exec 'nmap <buffer> <Leader>+ ]'.m
exec 'nmap <buffer> <A-+> ]'.m
" AltGr-o and AltGr-p
exec 'nmap <buffer> ø ['.m
exec 'nmap <buffer> þ ]'.m
endfun
augroup vimrc_setupunimpaired
au!
au BufEnter,VimEnter * call MySetupUnimpairedShortcut()
augroup END
" Quit with Q, exit with C-q.
" (go to tab on the left).
fun! MyQuitWindow()
let t = tabpagenr()
let nb_tabs = tabpagenr('$')
let was_last_tab = t == nb_tabs
if &ft != 'qf' && getcmdwintype() == ''
lclose
endif
" Turn off diff mode for all other windows.
if &diff && !exists('w:fugitive_diff_restore')
WindoNodelay diffoff
endif
if &bt == 'terminal'
" 'confirm' does not work: https://github.com/neovim/neovim/issues/4651
q
else
confirm q
endif
if ! was_last_tab && nb_tabs != tabpagenr('$') && tabpagenr() > 1
tabprevious
endif
endfun
nnoremap <silent> Q :call MyQuitWindow()<cr>
nnoremap <silent> <C-Q> :confirm qall<cr>
" Use just "q" in special buffers.
if has('autocmd')
augroup vimrc_special_q
au!
autocmd FileType help,startify nnoremap <buffer> q :confirm q<cr>
augroup END
endif
" }}}
" Close preview and quickfix windows.
nnoremap <silent> <C-W>z :wincmd z<Bar>cclose<Bar>lclose<CR>
" fzf.vim {{{
" Insert mode completion
imap <Leader><c-x><c-k> <plug>(fzf-complete-word)
imap <Leader><c-x><c-f> <plug>(fzf-complete-path)
imap <c-x><c-j> <plug>(fzf-complete-file-ag)
imap <Leader><c-x><c-l> <plug>(fzf-complete-line)
let g:fzf_command_prefix = 'FZF'
let g:fzf_layout = { 'window': 'execute (tabpagenr()-1)."tabnew"' }
" TODO: see /home/daniel/.dotfiles/vim/neobundles/fzf/plugin/fzf.vim
" let g:fzf_nvim_statusline = 0
function! s:fzf_statusline()
let bg_dim = &bg == 'dark' ? 18 : 21
exec 'highlight fzf1 ctermfg=1 ctermbg='.bg_dim
exec 'highlight fzf2 ctermfg=2 ctermbg='.bg_dim
exec 'highlight fzf3 ctermfg=7 ctermbg='.bg_dim
setlocal statusline=%#fzf1#\ >\ %#fzf2#fz%#fzf3#f
endfunction
augroup vimrc_quickfixsigns
au!
autocmd FileType help,fzf,ref-* let b:noquickfixsigns = 1
if exists('##TermOpen')
autocmd TermOpen * let b:noquickfixsigns = 1
endif
augroup END
augroup vimrc_fzf
au!
autocmd User FzfStatusLine call <SID>fzf_statusline()
augroup END
" }}}
let tmux_navigator_no_mappings = 1
if has('vim_starting')
if &rtp =~ '\<tmux-navigator\>'
nnoremap <silent> <c-h> :TmuxNavigateLeft<cr>
nnoremap <silent> <c-j> :TmuxNavigateDown<cr>
nnoremap <silent> <c-k> :TmuxNavigateUp<cr>
nnoremap <silent> <c-l> :TmuxNavigateRight<cr>
" nnoremap <silent> <c-\> :TmuxNavigatePrevious<cr>
else
nnoremap <C-h> <c-w>h
nnoremap <C-j> <c-w>j
nnoremap <C-k> <c-w>k
nnoremap <C-l> <c-w>l
" nnoremap <C-\> <c-w>j
endif
endif
if exists(':tnoremap') && has('vim_starting') " Neovim
" Exit.
tnoremap <Esc> <C-\><C-n>
" <c-space> does not work (https://github.com/neovim/neovim/issues/3101).
tnoremap <C-@> <C-\><C-n>:tab sp<cr>:startinsert<cr>
let g:terminal_scrollback_buffer_size = 100000 " current max
nnoremap <Leader>cx :sp \| :term p --testmon<cr>
nnoremap <Leader>cX :sp \| :term p -k
" Add :Term equivalent to :term, but with ":new" instead of ":enew".
fun! <SID>SplitTerm(...) abort
let cmd = ['zsh', '-i']
if a:0
let cmd += ['-c', join(a:000)]
endif
new
call termopen(cmd)
startinsert
endfun
com! -nargs=* -complete=shellcmd Term call <SID>SplitTerm(<f-args>)
" Open term in current file's dir.
nnoremap <Leader>gt :sp \| exe 'lcd' expand('%:p:h') \| :term<cr>
endif
let g:my_full_name = "Daniel Hahler"
let g:snips_author = g:my_full_name
" TAB is used for general completion.
let g:UltiSnipsExpandTrigger="<c-j>"
let g:UltiSnipsJumpForwardTrigger="<c-j>"
let g:UltiSnipsJumpBackwardTrigger="<c-k>"
let g:UltiSnipsListSnippets = "<c-b>"
let g:UltiSnipsEditSplit='context'
" let g:UltiSnips.always_use_first_snippet = 1
augroup UltiSnipsConfig
au!
au FileType smarty UltiSnipsAddFiletypes smarty.html.javascript.php
au FileType html UltiSnipsAddFiletypes html.javascript.php
augroup END
if !exists('g:UltiSnips') | let g:UltiSnips = {} | endif
let g:UltiSnips.load_early = 1
let g:UltiSnips.UltiSnips_ft_filter = {
\ 'default' : {'filetypes': ["FILETYPE", "all"] },
\ 'html' : {'filetypes': ["html", "javascript", "all"] },
\ 'python' : {'filetypes': ["python", "django", "all"] },
\ 'htmldjango' : {'filetypes': ["python", "django", "html", "all"] },
\ }
let g:UltiSnips.snipmate_ft_filter = {
\ 'default' : {'filetypes': ["FILETYPE", "_"] },
\ 'html' : {'filetypes': ["html", "javascript", "_"] },
\ 'python' : {'filetypes': ["python", "django", "_"] },
\ 'htmldjango' : {'filetypes': ["python", "django", "html", "_"] },
\ }
"\ 'html' : {'filetypes': ["html", "javascript"], 'dir-regex': '[._]vim$' },
if has('win32') || has('win64')
" replace ~/vimfiles with ~/.vim in runtimepath
" let &runtimepath = join( map( split(&rtp, ','), 'substitute(v:val, escape(expand("~/vimfiles"), "\\"), escape(expand("~/.vim"), "\\"), "g")' ), "," )
let &runtimepath = substitute(&runtimepath, '\('.escape($HOME, '\').'\)vimfiles\>', '\1.vim', 'g')
endif
" Sparkup (insert mode) maps. Default: <c-e>/<c-n>, both used by Vim.
let g:sparkupExecuteMapping = '<Leader><c-e>'
" '<c-n>' by default!
let g:sparkupNextMapping = '<Leader><c-n>'
" Syntastic {{{2
let g:syntastic_enable_signs=1
let g:syntastic_check_on_wq=1 " Only for active filetypes.
let g:syntastic_auto_loc_list=1
let g:syntastic_always_populate_loc_list=1
" let g:syntastic_echo_current_error=0 " TEST: faster?!
let g:syntastic_mode_map = {
\ 'mode': 'passive',
\ 'active_filetypes': ['ruby', 'php', 'lua', 'python', 'sh', 'zsh'],
\ 'passive_filetypes': [] }
let g:syntastic_error_symbol='â'
let g:syntastic_warning_symbol='â '
let g:syntastic_aggregate_errors = 0
let g:syntastic_python_checkers = ['python', 'frosted', 'flake8', 'pep8']
" let g:syntastic_php_checkers = ['php']
let g:syntastic_loc_list_height = 1 " handled via qf-resize autocommand
" See 'syntastic_quiet_messages' and 'syntastic_<filetype>_<checker>_quiet_messages'
" let g:syntastic_quiet_messages = {
" \ "level": "warnings",
" \ "type": "style",
" \ "regex": '\m\[C03\d\d\]',
" \ "file": ['\m^/usr/include/', '\m\c\.h$'] }
let g:syntastic_quiet_messages = { "level": [], "type": ["style"] }
fun! SyntasticToggleQuiet(k, v, scope)
let varname = a:scope."syntastic_quiet_messages"
if !exists(varname) | exec 'let '.varname.' = { "level": [], "type": ["style"] }' | endif
exec 'let idx = index('.varname.'[a:k], a:v)'
if idx == -1
exec 'call add('.varname.'[a:k], a:v)'
echom 'Syntastic: '.a:k.':'.a:v.' disabled (filtered).'
else
exec 'call remove('.varname.'[a:k], idx)'
echom 'Syntastic: '.a:k.':'.a:v.' enabled (not filtered).'
endif
endfun
command! SyntasticToggleWarnings call SyntasticToggleQuiet('level', 'warnings', "g:")
command! SyntasticToggleStyle call SyntasticToggleQuiet('type', 'style', "g:")
command! SyntasticToggleWarningsBuffer call SyntasticToggleQuiet('level', 'warnings', "b:")
command! SyntasticToggleStyleBuffer call SyntasticToggleQuiet('type', 'style', "b:")
fun! MySyntasticCheckAll()
let save = g:syntastic_quiet_messages
let g:syntastic_quiet_messages = { "level": [], 'type': [] }
SyntasticCheck
let g:syntastic_quiet_messages = save
endfun
command! MySyntasticCheckAll call MySyntasticCheckAll()
" Source: https://github.com/scrooloose/syntastic/issues/1361#issuecomment-82312541
function! SyntasticDisableToggle()
if !exists('s:syntastic_disabled')
let s:syntastic_disabled = 0
endif
if !s:syntastic_disabled
let s:modemap_save = deepcopy(g:syntastic_mode_map)
let g:syntastic_mode_map['active_filetypes'] = []
let g:syntastic_mode_map['mode'] = 'passive'
let s:syntastic_disabled = 1
SyntasticReset
echom "Syntastic disabled."
else
let g:syntastic_mode_map = deepcopy(s:modemap_save)
let s:syntastic_disabled = 0
echom "Syntastic enabled."
endif
endfunction
command! SyntasticDisableToggle call SyntasticDisableToggle()
" Neomake {{{
let g:neomake_open_list = 2
let g:neomake_list_height = 1 " handled via qf-resize autocommand
" let g:neomake_verbose = 3
" let g:neomake_logfile = '/tmp/neomake.log'
let g:neomake_tempfile_enabled = 1
let g:neomake_vim_enabled_makers = ['vint'] " vimlint is slow and too picky(?).
let g:neomake_python_enabled_makers = ['python', 'flake8']
let g:neomake_c_enabled_makers = []
augroup vimrc_neomake
au!
au BufReadPost ~/.dotfiles/vimrc let b:neomake_disabled = 1
au BufReadPost ~/.dotfiles/vimrc let b:neomake = extend(get(b:, 'neomake', {}), {'disabled': 1})
augroup END
" shellcheck: ignore "Can't follow non-constant source."
let $SHELLCHECK_OPTS='-e SC1090'
nnoremap <Leader>cc :Neomake<CR>
" Setup automake (https://github.com/neomake/neomake/pull/1167).
function! MyOnBattery()
- return readfile('/sys/class/power_supply/AC/online') == ['0']
+ try
+ return readfile('/sys/class/power_supply/AC/online') == ['0']
+ catch
+ return 1
+ endtry
endfunction
try
let g:neomake = {
\ 'automake': {
\ 'ignore_filetypes': ['startify'],
\ }}
- if MyOnBattery()
- call neomake#configure#automake('w', 500)
+ if !has('timers') || MyOnBattery()
+ call neomake#configure#automake('w')
else
call neomake#configure#automake('nrw', 500)
endif
catch
echom 'Neomake: failed to setup automake: '.v:exception
function! NeomakeCheck(fname) abort
if !get(g:, 'neomake_check_on_wq', 0) && get(w:, 'neomake_quitting_win', 0)
return
endif
if bufnr(a:fname) != bufnr('%')
" Not invoked for the current buffer. This happens for ':w /tmp/foo'.
return
endif
if get(b:, 'neomake_disabled', get(t:, 'neomake_disabled', get(g:, 'neomake_disabled', 0)))
return
endif
let s:windows_before = [tabpagenr(), winnr('$')]
if get(b:, '_my_neomake_checked_tick') == b:changedtick
return
endif
call neomake#Make(1, [])
let b:_my_neomake_checked_tick = b:changedtick
endfun
augroup neomake_check
au!
autocmd BufWritePost * call NeomakeCheck(expand('<afile>'))
if exists('##QuitPre')
autocmd QuitPre * if winnr('$') == 1 | let w:neomake_quitting_win = 1 | endif
endif
augroup END
endtry
" }}}
" gist-vim {{{2
let g:gist_detect_filetype = 1
" }}}
" tinykeymap: used to move between signs from quickfixsigns and useful by itself. {{{2
let g:tinykeymap#mapleader = '<Leader>k'
let g:tinykeymap#timeout = 0 " default: 5000s (ms)
let g:tinykeymap#conflict = 1
" Exit also with 'q'.
let g:tinykeymap#break_key = 113
" Default "*"; exluded "para_move" from tlib.
" List: :echo globpath(&rtp, 'autoload/tinykeymap/map/*.vim')
let g:tinykeymaps_default = [
\ 'buffers', 'diff', 'filter', 'lines', 'loc', 'qfl', 'tabs', 'undo',
\ 'windows', 'quickfixsigns',
\ ]
" \ 'para_move',
" }}}
" fontzoom {{{
let g:fontzoom_no_default_key_mappings = 1
nmap <A-+> <Plug>(fontzoom-larger)
nmap <A--> <Plug>(fontzoom-smaller)
" }}}
" Call bcompare with current and alternate file.
command! BC call system('bcompare '.shellescape(expand('%')).' '.shellescape(expand('#')).'&')
" YouCompleteMe {{{
" This needs to be the Python that YCM was built against. (set in ~/.zshrc.local).
if filereadable($PYTHON_YCM)
let g:ycm_path_to_python_interpreter = $PYTHON_YCM
" let g:ycm_path_to_python_interpreter = 'python-in-terminal'
endif
let g:ycm_filetype_blacklist = {
\ 'python' : 1,
\ 'ycmblacklisted': 1
\}
let g:ycm_complete_in_comments = 1
let g:ycm_complete_in_strings = 1
let g:ycm_collect_identifiers_from_comments_and_strings = 1
let g:ycm_extra_conf_globlist = ['~/src/awesome/.ycm_extra_conf.py']
" Jump mappings, overridden in Python mode with jedi-vim.
nnoremap <leader>j :YcmCompleter GoToDefinition<CR>
nnoremap <leader>gj :YcmCompleter GoToDeclaration<CR>
fun! MySetupPythonMappings()
nnoremap <buffer> <leader>j :call jedi#goto_definitions()<CR>
nnoremap <buffer> <leader>gj :call jedi#goto_assignments()<CR>
endfun
augroup vimrc_jump_maps
au!
au FileType python call MySetupPythonMappings()
augroup END
" Deactivated: causes huge RAM usage (YCM issue 595)
" let g:ycm_collect_identifiers_from_tags_files = 1
" EXPERIMENTAL: auto-popups and experimenting with SuperTab
" NOTE: this skips the following map setup (also for C-n):
" ' pumvisible() ? "\<C-p>" : "\' . key .'"'
let g:ycm_key_list_select_completion = []
let g:ycm_key_list_previous_completion = []
let g:ycm_semantic_triggers = {
\ 'c' : ['->', '.'],
\ 'objc' : ['->', '.'],
\ 'ocaml' : ['.', '#'],
\ 'cpp,objcpp' : ['->', '.', '::'],
\ 'perl' : ['->'],
\ 'php' : ['->', '::'],
\ 'cs,java,javascript,d,vim,python,perl6,scala,vb,elixir,go' : ['.'],
\ 'ruby' : ['.', '::'],
\ 'lua' : ['.', ':'],
\ 'erlang' : [':'],
\ }
" Tags (configure this before easytags, except when using easytags_dynamic_files)
" Look for tags file in parent directories, upto "/"
set tags=./tags;/
" CR and BS mapping: call various plugins manually. {{{
let g:endwise_no_mappings = 1 " NOTE: must be unset instead of 0
let g:cursorcross_no_map_CR = 1
let g:cursorcross_no_map_BS = 1
let g:delimitMate_expand_cr = 0
let g:SuperTabCrMapping = 0 " Skip SuperTab CR map setup (skipped anyway for expr mapping)
let g:cursorcross_mappings = 0 " No generic mappings for cursorcross.
" Force delimitMate mapping (gets skipped if mapped already).
fun! My_CR_map()
" "<CR>" via delimitMateCR
if len(maparg('<Plug>delimitMateCR', 'i'))
let r = "\<Plug>delimitMateCR"
else
let r = "\<CR>"
endif
if len(maparg('<Plug>CursorCrossCR', 'i'))
" requires vim 704
let r .= "\<Plug>CursorCrossCR"
endif
if len(maparg('<Plug>DiscretionaryEnd', 'i'))
let r .= "\<Plug>DiscretionaryEnd"
endif
return r
endfun
imap <expr> <CR> My_CR_map()
fun! My_BS_map()
" "<BS>" via delimitMateBS
if len(maparg('<Plug>delimitMateBS', 'i'))
let r = "\<Plug>delimitMateBS"
else
let r = "\<BS>"
endif
if len(maparg('<Plug>CursorCrossBS', 'i'))
" requires vim 704
let r .= "\<Plug>CursorCrossBS"
endif
return r
endfun
imap <expr> <BS> My_BS_map()
" For endwise.
imap <C-X><CR> <CR><Plug>AlwaysEnd
" }}}
" github-issues
" Trigger API request(s) only when completion is used/invoked.
let g:gissues_lazy_load = 1
" Add tags from $VIRTUAL_ENV
if $VIRTUAL_ENV != ""
let &tags = $VIRTUAL_ENV.'/tags,' . &tags
endif
" syntax mode setup
let php_sql_query = 1
let php_htmlInStrings = 1
" let php_special_functions = 0
" let php_alt_comparisons = 0
" let php_alt_assignByReference = 0
" let PHP_outdentphpescape = 1
let g:PHP_autoformatcomment = 0 " do not set formatoptions/comments automatically (php-indent bundle / vim runtime)
let g:php_noShortTags = 1
" always use Smarty comments in smarty files
" NOTE: for {php} it's useful
let g:tcommentGuessFileType_smarty = 0
endif
if &t_Co == 8
" Allow color schemes to do bright colors without forcing bold. (vim-sensible)
if $TERM !~# '^linux'
set t_Co=16
endif
" Fix t_Co: hack to enable 256 colors with e.g. "screen-bce" on CentOS 5.4;
" COLORTERM=lilyterm used for LilyTerm (set TERM=xterm).
" Do not match "screen" in Linux VT
" if (&term[0:6] == "screen-" || len($COLORTERM))
" set t_Co=256
" endif
endif
" Local dirs"{{{1
set backupdir=~/.local/share/vim/backups
if ! isdirectory(expand(&backupdir))
call mkdir( &backupdir, 'p', 0700 )
endif
if 1
let s:xdg_cache_home = $XDG_CACHE_HOME
if !len(s:xdg_cache_home)
let s:xdg_cache_home = expand('~/.cache')
endif
let s:vimcachedir = s:xdg_cache_home . '/vim'
let g:tlib_cache = s:vimcachedir . '/tlib'
let s:xdg_config_home = $XDG_CONFIG_HOME
if !len(s:xdg_config_home)
let s:xdg_config_home = expand('~/.config')
endif
let s:vimconfigdir = s:xdg_config_home . '/vim'
let g:session_directory = s:vimconfigdir . '/sessions'
let g:startify_session_dir = g:session_directory
let g:startify_change_to_dir = 0
let s:xdg_data_home = $XDG_DATA_HOME
if !len(s:xdg_data_home)
let s:xdg_data_home = expand('~/.local/share')
endif
let s:vimsharedir = s:xdg_data_home . '/vim'
let &viewdir = s:vimsharedir . '/views'
let g:yankring_history_dir = s:vimsharedir
let g:yankring_max_history = 500
" let g:yankring_min_element_length = 2 " more that 1 breaks e.g. `xp`
" Move yankring history from old location, if any..
let s:old_yankring = expand('~/yankring_history_v2.txt')
if filereadable(s:old_yankring)
execute '!mv -i '.s:old_yankring.' '.s:vimsharedir
endif
" Transfer any old (default) tmru files db to new (default) location.
let g:tlib_persistent = s:vimsharedir
let s:old_tmru_file = expand('~/.cache/vim/tlib/tmru/files')
let s:global_tmru_file = s:vimsharedir.'/tmru/files'
let s:new_tmru_file_dir = fnamemodify(s:global_tmru_file, ':h')
if ! isdirectory(s:new_tmru_file_dir)
call mkdir(s:new_tmru_file_dir, 'p', 0700)
endif
if filereadable(s:old_tmru_file)
execute '!mv -i '.shellescape(s:old_tmru_file).' '.shellescape(s:global_tmru_file)
" execute '!rm -r '.shellescape(g:tlib_cache)
endif
end
let s:check_create_dirs = [s:vimcachedir, g:tlib_cache, s:vimconfigdir, g:session_directory, s:vimsharedir, &directory]
if has('persistent_undo')
let &undodir = s:vimsharedir . '/undo'
set undofile
call add(s:check_create_dirs, &undodir)
endif
for s:create_dir in s:check_create_dirs
" Remove trailing slashes, especially for &directory.
let s:create_dir = substitute(s:create_dir, '/\+$', '', '')
if ! isdirectory(s:create_dir)
if match(s:create_dir, ',') != -1
echohl WarningMsg | echom "WARN: not creating dir: ".s:create_dir | echohl None
continue
endif
echom "Creating dir: ".s:create_dir
call mkdir(s:create_dir, 'p', 0700 )
endif
endfor
" }}}
if has("user_commands")
" Themes
" Airline:
let g:airline#extensions#disable_rtp_load = 1
let g:airline_extensions_add = ['neomake']
let g:airline_powerline_fonts = 1
" to test
let g:airline#extensions#branch#use_vcscommand = 1
let g:airline#extensions#branch#displayed_head_limit = 7
let g:airline#extensions#hunks#non_zero_only = 1
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#show_buffers = 0
let g:airline#extensions#tabline#tab_nr_type = '[__tabnr__.%{len(tabpagebuflist(__tabnr__))}]'
let g:airline#extensions#tmuxline#enabled = 1
let g:airline#extensions#whitespace#enabled = 0
let g:airline#extensions#tagbar#enabled = 0
let g:airline#extensions#tagbar#flags = 'f' " full hierarchy of tag (with scope), see tagbar-statusline
" see airline-predefined-parts
" let r += ['%{ShortenFilename(fnamemodify(bufname("%"), ":~:."), winwidth(0)-50)}']
" function! AirlineInit()
" " let g:airline_section_a = airline#section#create(['mode', ' ', 'foo'])
" " let g:airline_section_b = airline#section#create_left(['ffenc','file'])
" " let g:airline_section_c = airline#section#create(['%{getcwd()}'])
" endfunction
" au VimEnter * call AirlineInit()
" jedi-vim (besides YCM with jedi library) {{{1
" let g:jedi#force_py_version = 3
let g:jedi#auto_vim_configuration = 0
let g:jedi#goto_assignments_command = '' " dynamically done for ft=python.
let g:jedi#goto_definitions_command = '' " dynamically done for ft=python.
let g:jedi#rename_command = 'cR'
let g:jedi#usages_command = 'gr'
let g:jedi#completions_enabled = 1
" Unite/ref and pydoc are more useful.
let g:jedi#documentation_command = '<Leader>_K'
" Manually setup jedi's call signatures.
let g:jedi#show_call_signatures = 1
if &rtp =~ '\<jedi\>'
augroup JediSetup
au!
au FileType python call jedi#configure_call_signatures()
augroup END
endif
let g:jedi#auto_close_doc = 1
" if g:jedi#auto_close_doc
" " close preview if its still open after insert
" autocmd InsertLeave <buffer> if pumvisible() == 0|pclose|endif
" end
" }}}1
endif
" Enable syntax {{{1
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
" if (&t_Co > 2 || has("gui_running")) && !exists("syntax_on")
if (&t_Co > 2 || has("gui_running"))
if !exists("syntax_on")
syntax on " after 'filetype plugin indent on' (?!), but not on reload.
endif
set nohlsearch
" Improved syntax handling of TODO etc.
au Syntax * syn match MyTodo /\v<(FIXME|NOTE|TODO|OPTIMIZE|XXX):/
\ containedin=.*Comment,vimCommentTitle
hi def link MyTodo Todo
endif
if 1 " has('eval')
" Color scheme (after 'syntax on') {{{1
" Use light/dark background based on day/night period (according to
" get-daytime-period (uses redshift))
fun! SetBgAccordingToShell(...)
let variant = a:0 ? a:1 : ""
if len(variant) && variant != "auto"
let bg = variant
elseif len($TMUX)
let bg = system('tmux show-env MY_X_THEME_VARIANT') == "MY_X_THEME_VARIANT=light\n" ? 'light' : 'dark'
elseif len($MY_X_THEME_VARIANT)
let bg = $MY_X_THEME_VARIANT
else
" let daytime = system('get-daytime-period')
let daytime_file = expand('/tmp/redshift-period')
if filereadable(daytime_file)
let daytime = readfile(daytime_file)[0]
if daytime == 'Daytime'
let bg = "light"
else
let bg = "dark"
endif
else
let bg = "dark"
endif
endif
if bg != &bg
let &bg = bg
let $FZF_DEFAULT_OPTS = '--color 16,bg+:' . (bg == 'dark' ? '18' : '21')
doautocmd <nomodeline> ColorScheme
endif
endfun
command! -nargs=? Autobg call SetBgAccordingToShell(<q-args>)
fun! ToggleBg()
let &bg = &bg == 'dark' ? 'light' : 'dark'
endfun
nnoremap <Leader>sb :call ToggleBg()<cr>
" Colorscheme: prefer solarized with 16 colors (special palette).
let g:solarized_hitrail=0 " using MyWhitespaceSetup instead.
let g:solarized_menu=0
" Use corresponding theme from $BASE16_THEME, if set up in the shell.
" BASE16_THEME should be in sudoer's env_keep for "sudo vi".
if len($BASE16_THEME)
let base16colorspace=&t_Co
if $BASE16_THEME =~ '^solarized'
let s:use_colorscheme = 'solarized'
let g:solarized_base16=1
let g:airline_theme = 'solarized'
else
let s:use_colorscheme = 'base16-'.substitute($BASE16_THEME, '\.\(dark\|light\)$', '', '')
endif
let g:solarized_termtrans=1
elseif has('gui_running')
let s:use_colorscheme = "solarized"
let g:solarized_termcolors=256
else
" Check for dumb terminal.
if ($TERM !~ '256color' )
let s:use_colorscheme = "default"
else
let s:use_colorscheme = "solarized"
let g:solarized_termcolors=256
endif
endif
" Airline: do not use powerline symbols with linux/screen terminal.
" NOTE: xterm-256color gets setup for tmux/screen with $DISPLAY.
if (index(["linux", "screen"], $TERM) != -1)
let g:airline_powerline_fonts = 0
endif
fun! s:MySetColorscheme()
" Set s:use_colorscheme, called through GUIEnter for gvim.
try
exec 'NeoBundleSource colorscheme-'.s:use_colorscheme
exec 'colorscheme' s:use_colorscheme
catch
echom "Failed to load colorscheme: " v:exception
endtry
endfun
if has('vim_starting')
call SetBgAccordingToShell($MY_X_THEME_VARIANT)
endif
if has('gui_running')
au GUIEnter * nested call s:MySetColorscheme()
else
call s:MySetColorscheme()
endif
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd") " Autocommands {{{1
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcEx
au!
" Handle large files, based on LargeFile plugin.
let g:LargeFile = 5 " 5mb
autocmd BufWinEnter * if get(b:, 'LargeFile_mode') || line2byte(line("$") + 1) > 1000000
\ | echom "vimrc: handling large file."
\ | set syntax=off
\ | let &ft = &ft.".ycmblacklisted"
\ | endif
" Enable soft-wrapping for text files
au FileType text,markdown,html,xhtml,eruby,vim setlocal wrap linebreak nolist
au FileType mail,markdown,gitcommit setlocal spell
au FileType json setlocal equalprg=json_pp
" XXX: only works for whole files
" au FileType css setlocal equalprg=csstidy\ -\ --silent=true\ --template=default
" For all text files set 'textwidth' to 78 characters.
" au FileType text setlocal textwidth=78
" Follow symlinks when opening a file {{{
" NOTE: this happens with directory symlinks anyway (due to Vim's chdir/getcwd
" magic when getting filenames).
" Sources:
" - https://github.com/tpope/vim-fugitive/issues/147#issuecomment-7572351
" - http://www.reddit.com/r/vim/comments/yhsn6/is_it_possible_to_work_around_the_symlink_bug/c5w91qw
function! MyFollowSymlink(...)
if exists('w:no_resolve_symlink') && w:no_resolve_symlink
return
endif
if &ft == 'help'
return
endif
let fname = a:0 ? a:1 : expand('%')
if fname =~ '^\w\+:/'
" Do not mess with 'fugitive://' etc.
return
endif
let fname = simplify(fname)
let resolvedfile = resolve(fname)
if resolvedfile == fname
return
endif
let resolvedfile = fnameescape(resolvedfile)
let sshm = &shm
set shortmess+=A " silence ATTENTION message about swap file (would get displayed twice)
redraw " Redraw now, to avoid hit-enter prompt.
exec 'file ' . resolvedfile
let &shm=sshm
unlet! b:git_dir
call fugitive#detect(resolvedfile)
if &modifiable
" Only display a note when editing a file, especially not for `:help`.
redraw " Redraw now, to avoid hit-enter prompt.
|
blueyed/dotfiles | 5ca3a844c520d6d352a5b32857a74e3192f22f74 | vimrc: fix s:systemlist for vim73 | diff --git a/vimrc b/vimrc
index cd52ad1..16ce4b1 100644
--- a/vimrc
+++ b/vimrc
@@ -1366,1027 +1366,1028 @@ endif
" Local dirs"{{{1
set backupdir=~/.local/share/vim/backups
if ! isdirectory(expand(&backupdir))
call mkdir( &backupdir, 'p', 0700 )
endif
if 1
let s:xdg_cache_home = $XDG_CACHE_HOME
if !len(s:xdg_cache_home)
let s:xdg_cache_home = expand('~/.cache')
endif
let s:vimcachedir = s:xdg_cache_home . '/vim'
let g:tlib_cache = s:vimcachedir . '/tlib'
let s:xdg_config_home = $XDG_CONFIG_HOME
if !len(s:xdg_config_home)
let s:xdg_config_home = expand('~/.config')
endif
let s:vimconfigdir = s:xdg_config_home . '/vim'
let g:session_directory = s:vimconfigdir . '/sessions'
let g:startify_session_dir = g:session_directory
let g:startify_change_to_dir = 0
let s:xdg_data_home = $XDG_DATA_HOME
if !len(s:xdg_data_home)
let s:xdg_data_home = expand('~/.local/share')
endif
let s:vimsharedir = s:xdg_data_home . '/vim'
let &viewdir = s:vimsharedir . '/views'
let g:yankring_history_dir = s:vimsharedir
let g:yankring_max_history = 500
" let g:yankring_min_element_length = 2 " more that 1 breaks e.g. `xp`
" Move yankring history from old location, if any..
let s:old_yankring = expand('~/yankring_history_v2.txt')
if filereadable(s:old_yankring)
execute '!mv -i '.s:old_yankring.' '.s:vimsharedir
endif
" Transfer any old (default) tmru files db to new (default) location.
let g:tlib_persistent = s:vimsharedir
let s:old_tmru_file = expand('~/.cache/vim/tlib/tmru/files')
let s:global_tmru_file = s:vimsharedir.'/tmru/files'
let s:new_tmru_file_dir = fnamemodify(s:global_tmru_file, ':h')
if ! isdirectory(s:new_tmru_file_dir)
call mkdir(s:new_tmru_file_dir, 'p', 0700)
endif
if filereadable(s:old_tmru_file)
execute '!mv -i '.shellescape(s:old_tmru_file).' '.shellescape(s:global_tmru_file)
" execute '!rm -r '.shellescape(g:tlib_cache)
endif
end
let s:check_create_dirs = [s:vimcachedir, g:tlib_cache, s:vimconfigdir, g:session_directory, s:vimsharedir, &directory]
if has('persistent_undo')
let &undodir = s:vimsharedir . '/undo'
set undofile
call add(s:check_create_dirs, &undodir)
endif
for s:create_dir in s:check_create_dirs
" Remove trailing slashes, especially for &directory.
let s:create_dir = substitute(s:create_dir, '/\+$', '', '')
if ! isdirectory(s:create_dir)
if match(s:create_dir, ',') != -1
echohl WarningMsg | echom "WARN: not creating dir: ".s:create_dir | echohl None
continue
endif
echom "Creating dir: ".s:create_dir
call mkdir(s:create_dir, 'p', 0700 )
endif
endfor
" }}}
if has("user_commands")
" Themes
" Airline:
let g:airline#extensions#disable_rtp_load = 1
let g:airline_extensions_add = ['neomake']
let g:airline_powerline_fonts = 1
" to test
let g:airline#extensions#branch#use_vcscommand = 1
let g:airline#extensions#branch#displayed_head_limit = 7
let g:airline#extensions#hunks#non_zero_only = 1
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#show_buffers = 0
let g:airline#extensions#tabline#tab_nr_type = '[__tabnr__.%{len(tabpagebuflist(__tabnr__))}]'
let g:airline#extensions#tmuxline#enabled = 1
let g:airline#extensions#whitespace#enabled = 0
let g:airline#extensions#tagbar#enabled = 0
let g:airline#extensions#tagbar#flags = 'f' " full hierarchy of tag (with scope), see tagbar-statusline
" see airline-predefined-parts
" let r += ['%{ShortenFilename(fnamemodify(bufname("%"), ":~:."), winwidth(0)-50)}']
" function! AirlineInit()
" " let g:airline_section_a = airline#section#create(['mode', ' ', 'foo'])
" " let g:airline_section_b = airline#section#create_left(['ffenc','file'])
" " let g:airline_section_c = airline#section#create(['%{getcwd()}'])
" endfunction
" au VimEnter * call AirlineInit()
" jedi-vim (besides YCM with jedi library) {{{1
" let g:jedi#force_py_version = 3
let g:jedi#auto_vim_configuration = 0
let g:jedi#goto_assignments_command = '' " dynamically done for ft=python.
let g:jedi#goto_definitions_command = '' " dynamically done for ft=python.
let g:jedi#rename_command = 'cR'
let g:jedi#usages_command = 'gr'
let g:jedi#completions_enabled = 1
" Unite/ref and pydoc are more useful.
let g:jedi#documentation_command = '<Leader>_K'
" Manually setup jedi's call signatures.
let g:jedi#show_call_signatures = 1
if &rtp =~ '\<jedi\>'
augroup JediSetup
au!
au FileType python call jedi#configure_call_signatures()
augroup END
endif
let g:jedi#auto_close_doc = 1
" if g:jedi#auto_close_doc
" " close preview if its still open after insert
" autocmd InsertLeave <buffer> if pumvisible() == 0|pclose|endif
" end
" }}}1
endif
" Enable syntax {{{1
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
" if (&t_Co > 2 || has("gui_running")) && !exists("syntax_on")
if (&t_Co > 2 || has("gui_running"))
if !exists("syntax_on")
syntax on " after 'filetype plugin indent on' (?!), but not on reload.
endif
set nohlsearch
" Improved syntax handling of TODO etc.
au Syntax * syn match MyTodo /\v<(FIXME|NOTE|TODO|OPTIMIZE|XXX):/
\ containedin=.*Comment,vimCommentTitle
hi def link MyTodo Todo
endif
if 1 " has('eval')
" Color scheme (after 'syntax on') {{{1
" Use light/dark background based on day/night period (according to
" get-daytime-period (uses redshift))
fun! SetBgAccordingToShell(...)
let variant = a:0 ? a:1 : ""
if len(variant) && variant != "auto"
let bg = variant
elseif len($TMUX)
let bg = system('tmux show-env MY_X_THEME_VARIANT') == "MY_X_THEME_VARIANT=light\n" ? 'light' : 'dark'
elseif len($MY_X_THEME_VARIANT)
let bg = $MY_X_THEME_VARIANT
else
" let daytime = system('get-daytime-period')
let daytime_file = expand('/tmp/redshift-period')
if filereadable(daytime_file)
let daytime = readfile(daytime_file)[0]
if daytime == 'Daytime'
let bg = "light"
else
let bg = "dark"
endif
else
let bg = "dark"
endif
endif
if bg != &bg
let &bg = bg
let $FZF_DEFAULT_OPTS = '--color 16,bg+:' . (bg == 'dark' ? '18' : '21')
doautocmd <nomodeline> ColorScheme
endif
endfun
command! -nargs=? Autobg call SetBgAccordingToShell(<q-args>)
fun! ToggleBg()
let &bg = &bg == 'dark' ? 'light' : 'dark'
endfun
nnoremap <Leader>sb :call ToggleBg()<cr>
" Colorscheme: prefer solarized with 16 colors (special palette).
let g:solarized_hitrail=0 " using MyWhitespaceSetup instead.
let g:solarized_menu=0
" Use corresponding theme from $BASE16_THEME, if set up in the shell.
" BASE16_THEME should be in sudoer's env_keep for "sudo vi".
if len($BASE16_THEME)
let base16colorspace=&t_Co
if $BASE16_THEME =~ '^solarized'
let s:use_colorscheme = 'solarized'
let g:solarized_base16=1
let g:airline_theme = 'solarized'
else
let s:use_colorscheme = 'base16-'.substitute($BASE16_THEME, '\.\(dark\|light\)$', '', '')
endif
let g:solarized_termtrans=1
elseif has('gui_running')
let s:use_colorscheme = "solarized"
let g:solarized_termcolors=256
else
" Check for dumb terminal.
if ($TERM !~ '256color' )
let s:use_colorscheme = "default"
else
let s:use_colorscheme = "solarized"
let g:solarized_termcolors=256
endif
endif
" Airline: do not use powerline symbols with linux/screen terminal.
" NOTE: xterm-256color gets setup for tmux/screen with $DISPLAY.
if (index(["linux", "screen"], $TERM) != -1)
let g:airline_powerline_fonts = 0
endif
fun! s:MySetColorscheme()
" Set s:use_colorscheme, called through GUIEnter for gvim.
try
exec 'NeoBundleSource colorscheme-'.s:use_colorscheme
exec 'colorscheme' s:use_colorscheme
catch
echom "Failed to load colorscheme: " v:exception
endtry
endfun
if has('vim_starting')
call SetBgAccordingToShell($MY_X_THEME_VARIANT)
endif
if has('gui_running')
au GUIEnter * nested call s:MySetColorscheme()
else
call s:MySetColorscheme()
endif
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd") " Autocommands {{{1
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcEx
au!
" Handle large files, based on LargeFile plugin.
let g:LargeFile = 5 " 5mb
autocmd BufWinEnter * if get(b:, 'LargeFile_mode') || line2byte(line("$") + 1) > 1000000
\ | echom "vimrc: handling large file."
\ | set syntax=off
\ | let &ft = &ft.".ycmblacklisted"
\ | endif
" Enable soft-wrapping for text files
au FileType text,markdown,html,xhtml,eruby,vim setlocal wrap linebreak nolist
au FileType mail,markdown,gitcommit setlocal spell
au FileType json setlocal equalprg=json_pp
" XXX: only works for whole files
" au FileType css setlocal equalprg=csstidy\ -\ --silent=true\ --template=default
" For all text files set 'textwidth' to 78 characters.
" au FileType text setlocal textwidth=78
" Follow symlinks when opening a file {{{
" NOTE: this happens with directory symlinks anyway (due to Vim's chdir/getcwd
" magic when getting filenames).
" Sources:
" - https://github.com/tpope/vim-fugitive/issues/147#issuecomment-7572351
" - http://www.reddit.com/r/vim/comments/yhsn6/is_it_possible_to_work_around_the_symlink_bug/c5w91qw
function! MyFollowSymlink(...)
if exists('w:no_resolve_symlink') && w:no_resolve_symlink
return
endif
if &ft == 'help'
return
endif
let fname = a:0 ? a:1 : expand('%')
if fname =~ '^\w\+:/'
" Do not mess with 'fugitive://' etc.
return
endif
let fname = simplify(fname)
let resolvedfile = resolve(fname)
if resolvedfile == fname
return
endif
let resolvedfile = fnameescape(resolvedfile)
let sshm = &shm
set shortmess+=A " silence ATTENTION message about swap file (would get displayed twice)
redraw " Redraw now, to avoid hit-enter prompt.
exec 'file ' . resolvedfile
let &shm=sshm
unlet! b:git_dir
call fugitive#detect(resolvedfile)
if &modifiable
" Only display a note when editing a file, especially not for `:help`.
redraw " Redraw now, to avoid hit-enter prompt.
echomsg 'Resolved symlink: =>' resolvedfile
endif
endfunction
command! -bar FollowSymlink call MyFollowSymlink()
command! ToggleFollowSymlink let w:no_resolve_symlink = !get(w:, 'no_resolve_symlink', 0) | echo "w:no_resolve_symlink =>" w:no_resolve_symlink
au BufReadPost * nested call MyFollowSymlink(expand('%'))
" Automatically load .vimrc source when saved
au BufWritePost $MYVIMRC,~/.dotfiles/vimrc,$MYVIMRC.local source $MYVIMRC
au BufWritePost $MYGVIMRC,~/.dotfiles/gvimrc source $MYGVIMRC
" if (has("gui_running"))
" au FocusLost * stopinsert
" endif
" autocommands for fugitive {{{2
" Source: http://vimcasts.org/episodes/fugitive-vim-browsing-the-git-object-database/
au User Fugitive
\ if fugitive#buffer().type() =~# '^\%(tree\|blob\)' |
\ nnoremap <buffer> .. :edit %:h<CR> |
\ endif
au BufReadPost fugitive://* set bufhidden=delete
" Expand tabs for Debian changelog. This is probably not the correct way.
au BufNewFile,BufRead */debian/changelog,changelog.dch set expandtab
" Ignore certain files with vim-stay.
au BufNewFile,BufRead */.git/addp-hunk-edit.diff let b:stay_ignore = 1
" Python
" irrelevant, using python-pep8-indent
" let g:pyindent_continue = '&sw * 1'
" let g:pyindent_open_paren = '&sw * 1'
" let g:pyindent_nested_paren = '&sw'
" python-mode
let g:pymode_options = 0 " do not change relativenumber
let g:pymode_indent = 0 " use vim-python-pep8-indent (upstream of pymode)
let g:pymode_lint = 0 " prefer syntastic; pymode has problems when PyLint was invoked already before VirtualEnvActivate..!?!
let g:pymode_virtualenv = 0 " use virtualenv plugin (required for pylint?!)
let g:pymode_doc = 0 " use pydoc
let g:pymode_rope_completion = 0 " use YouCompleteMe instead (python-jedi)
let g:pymode_syntax_space_errors = 0 " using MyWhitespaceSetup
let g:pymode_trim_whitespaces = 0
let g:pymode_debug = 0
let g:pymode_rope = 0
let g:pydoc_window_lines=0.5 " use 50% height
let g:pydoc_perform_mappings=0
" let python_space_error_highlight = 1 " using MyWhitespaceSetup
" C
au FileType C setlocal formatoptions-=c formatoptions-=o formatoptions-=r
fu! Select_c_style()
if search('^\t', 'n', 150)
setlocal shiftwidth=8 noexpandtab
el
setlocal shiftwidth=4 expandtab
en
endf
au FileType c call Select_c_style()
au FileType make setlocal noexpandtab
" Disable highlighting of markdownError (Ref: https://github.com/tpope/vim-markdown/issues/79).
autocmd FileType markdown hi link markdownError NONE
augroup END
" Trailing whitespace highlighting {{{2
" Map to toogle EOLWS syntax highlighting
noremap <silent> <leader>se :let g:MyAuGroupEOLWSactive = (synIDattr(synIDtrans(hlID("EOLWS")), "bg", "cterm") == -1)<cr>
\:call MyAuGroupEOLWS(mode())<cr>
let g:MyAuGroupEOLWSactive = 0
function! MyAuGroupEOLWS(mode)
if g:MyAuGroupEOLWSactive && &buftype == ''
hi EOLWS ctermbg=red guibg=red
syn clear EOLWS
" match whitespace not preceded by a backslash
if a:mode == "i"
syn match EOLWS excludenl /[\\]\@<!\s\+\%#\@!$/ containedin=ALL
else
syn match EOLWS excludenl /[\\]\@<!\s\+$\| \+\ze\t/ containedin=ALLBUT,gitcommitDiff |
endif
else
syn clear EOLWS
hi clear EOLWS
endif
endfunction
augroup vimrcExEOLWS
au!
" highlight EOLWS ctermbg=red guibg=red
" based on solarizedTrailingSpace
highlight EOLWS term=underline cterm=underline ctermfg=1
au InsertEnter * call MyAuGroupEOLWS("i")
" highlight trailing whitespace, space before tab and tab not at the
" beginning of the line (except in comments), only for normal buffers:
au InsertLeave,BufWinEnter * call MyAuGroupEOLWS("n")
" fails with gitcommit: filetype | syn match EOLWS excludenl /[^\t]\zs\t\+/ containedin=ALLBUT,gitcommitComment
" add this for Python (via python_highlight_all?!):
" au FileType python
" \ if g:MyAuGroupEOLWSactive |
" \ syn match EOLWS excludenl /^\t\+/ containedin=ALL |
" \ endif
augroup END "}}}
" automatically save and reload viminfo across Vim instances
" Source: http://vimhelp.appspot.com/vim_faq.txt.html#faq-17.3
augroup viminfo_onfocus
au!
" au FocusLost * wviminfo
" au FocusGained * rviminfo
augroup end
endif " has("autocmd") }}}
" Shorten a given (absolute) file path, via external `shorten_path` script.
" This mainly shortens entries from Zsh's `hash -d` list.
let s:_cache_shorten_path = {}
let s:_has_functional_shorten_path = 1
let s:shorten_path_exe = executable('shorten_path')
\ ? 'shorten_path'
\ : filereadable(expand("$HOME/.dotfiles/usr/bin/shorten_path"))
\ ? expand("$HOME/.dotfiles/usr/bin/shorten_path")
\ : expand("/home/$SUDO_USER/.dotfiles/usr/bin/shorten_path")
function! ShortenPath(path, ...)
if !len(a:path) || !s:_has_functional_shorten_path
return a:path
endif
let base = a:0 ? a:1 : ""
let annotate = a:0 > 1 ? a:2 : 0
let cache_key = base . ":" . a:path . ":" . annotate
if !exists('s:_cache_shorten_path[cache_key]')
let shorten_path = [s:shorten_path_exe]
if annotate
let shorten_path += ['-a']
endif
let cmd = shorten_path + [a:path, base]
let output = s:systemlist(cmd)
let lastline = empty(output) ? '' : output[-1]
let s:_cache_shorten_path[cache_key] = lastline
if v:shell_error
try
let tmpfile = tempname()
let system_cmd = join(map(copy(cmd), 'fnameescape(v:val)'))
call system(system_cmd.' 2>'.tmpfile)
if v:shell_error == 127
let s:_has_functional_shorten_path = 0
endif
echohl ErrorMsg
echom printf('There was a problem running %s: %s (%d)',
\ cmd, join(readfile(tmpfile), "\n"), v:shell_error)
echohl None
return a:path
finally
call delete(tmpfile)
endtry
endif
endif
return s:_cache_shorten_path[cache_key]
endfun
function! My_get_qfloclist_type(bufnr)
let isLoc = getbufvar(a:bufnr, 'isLoc', -1) " via vim-qf.
if isLoc != -1
return isLoc ? 'll' : 'qf'
endif
" A hacky way to distinguish qf from loclist windows/buffers.
" https://github.com/vim-airline/vim-airline/blob/83b6dd11a8829bbd934576e76bfbda6559ed49e1/autoload/airline/extensions/quickfix.vim#L27-L43.
" Changes:
" - Caching!
" - Match opening square bracket at least. Apart from that it could be
" localized.
" if &ft !=# 'qf'
" return ''
" endif
let type = getbufvar(a:bufnr, 'my_qfloclist_type', '')
if type != ''
return type
endif
redir => buffers
silent ls -
redir END
let type = 'unknown'
for buf in split(buffers, '\n')
if match(buf, '\v^\s*'.a:bufnr.'\s\S+\s+"\[') > -1
if match(buf, '\cQuickfix') > -1
let type = 'qf'
break
else
let type = 'll'
break
endif
endif
endfor
call setbufvar(a:bufnr, 'my_qfloclist_type', type)
return type
endfunction
function! s:systemlist(l) abort
- let cmd = a:l
if !has('nvim')
- let cmd = join(map(copy(cmd), 'fnameescape(v:val)'))
+ let cmd = join(map(copy(a:l), 'fnameescape(v:val)'))
+ else
+ let cmd = a:l
endif
return systemlist(cmd)
endfunction
" Shorten a given filename by truncating path segments.
let g:_cache_shorten_filename = {}
let g:_cache_shorten_filename_git = {}
function! ShortenString(s, maxlen)
if len(a:s) <= a:maxlen
return a:s
endif
return a:s[0:a:maxlen-1] . 'â¦'
endfunction
function! ShortenFilename(...) " {{{
" Args: bufname ('%' for default), maxlength, cwd
let cwd = a:0 > 2 ? a:3 : getcwd()
" Maxlen from a:2 (used for cache key) and caching.
let maxlen = a:0>1 ? a:2 : max([10, winwidth(0)-50])
" get bufname from a:1, defaulting to bufname('%') {{{
if a:0 && type(a:1) == type('') && a:1 !=# '%'
let bufname = expand(a:1) " tilde-expansion.
else
if !a:0 || a:1 == '%'
let bufnr = bufnr('%')
else
let bufnr = a:1
endif
let bufname = bufname(bufnr)
let ft = getbufvar(bufnr, '&filetype')
if !len(bufname)
if ft == 'qf'
let type = My_get_qfloclist_type(bufnr)
" XXX: uses current window. Also not available after ":tab split".
let qf_title = get(w:, 'quickfix_title', '')
if qf_title != ''
return ShortenString('['.type.'] '.qf_title, maxlen)
elseif type == 'll'
let alt_name = expand('#')
" For location lists the alternate file is the corresponding buffer
" and the quickfix list does not have an alternate buffer
" (but not always)!?!
if len(alt_name)
return '[loc] '.ShortenFilename(alt_name, maxlen-5)
endif
return '[loc]'
endif
return '[qf]'
else
let bt = getbufvar(bufnr, '&buftype')
if bt != '' && ft != ''
" Use &ft for name (e.g. with 'startify' and quickfix windows).
" if &ft == 'qf'
" let alt_name = expand('#')
" if len(alt_name)
" return '[loc] '.ShortenFilename(alt_name)
" else
" return '[qf]'
" endif
let alt_name = expand('#')
if len(alt_name)
return '['.&ft.'] '.ShortenFilename(expand('#'))
else
return '['.&ft.']'
endif
else
" TODO: get Vim's original "[No Name]" somehow
return '[No Name]'
endif
endif
end
if ft ==# 'help'
return '[?] '.fnamemodify(bufname, ':t')
endif
if bufname =~# '^__'
return bufname
endif
" '^\[ref-\w\+:.*\]$'
if bufname =~# '^\[.*\]$'
return bufname
endif
endif
" }}}
" {{{ fugitive
if bufname =~# '^fugitive:///'
let [gitdir, fug_path] = split(bufname, '//')[1:2]
" Caching based on bufname and timestamp of gitdir.
let git_ftime = getftime(gitdir)
if exists('g:_cache_shorten_filename_git[bufname]')
\ && g:_cache_shorten_filename_git[bufname][0] == git_ftime
let [commit_name, fug_type, fug_path]
\ = g:_cache_shorten_filename_git[bufname][1:-1]
else
let fug_buffer = fugitive#buffer(bufname)
let fug_type = fug_buffer.type()
" if fug_path =~# '^\x\{7,40\}\>'
let commit = matchstr(fug_path, '\v\w*')
if len(commit) > 1
let git_argv = ['git', '--git-dir='.gitdir]
let commit = systemlist(git_argv + ['rev-parse', '--short', commit])[0]
let commit_name = systemlist(git_argv + ['name-rev', '--name-only', commit])[0]
if commit_name !=# 'undefined'
" Remove current branch name (master~4 => ~4).
let HEAD = get(systemlist(git_argv + ['symbolic-ref', '--quiet', '--short', 'HEAD']), 0, '')
let len_HEAD = len(HEAD)
if len_HEAD > len(commit_name) && commit_name[0:len_HEAD-1] == HEAD
let commit_name = commit_name[len_HEAD:-1]
endif
" let commit .= '('.commit_name.')'
let commit_name .= '('.commit.')'
else
let commit_name = commit
endif
else
let commit_name = commit
endif
" endif
if fug_type !=# 'commit'
let fug_path = substitute(fug_path, '\v\w*/', '', '')
if len(fug_path)
let fug_path = ShortenFilename(fug_buffer.repo().tree(fug_path))
endif
else
let fug_path = 'NOT_USED'
endif
" Set cache.
let g:_cache_shorten_filename_git[bufname]
\ = [git_ftime, commit_name, fug_type, fug_path]
endif
if fug_type ==# 'blob'
return 'λ:' . commit_name . ':' . fug_path
elseif fug_type ==# 'file'
return 'λ:' . fug_path . '@' . commit_name
elseif fug_type ==# 'commit'
" elseif fug_path =~# '^\x\{7,40\}\>'
let work_tree = fugitive#buffer(bufname).repo().tree()
if cwd[0:len(work_tree)-1] == work_tree
let rel_work_tree = ''
else
let rel_work_tree = ShortenPath(fnamemodify(work_tree.'/', ':.'))
endif
return 'λ:' . rel_work_tree . '@' . commit_name
endif
throw "fug_type: ".fug_type." not handled: ".fug_path
endif " }}}
" Check for cache (avoiding fnamemodify): {{{
let cache_key = bufname.'::'.cwd.'::'.maxlen
if has_key(g:_cache_shorten_filename, cache_key)
return g:_cache_shorten_filename[cache_key]
endif
" Make path relative first, which might not work with the result from
" `shorten_path`.
let rel_path = fnamemodify(bufname, ":.")
let bufname = ShortenPath(rel_path, cwd, 1)
" }}}
" Loop over all segments/parts, to mark symlinks.
" XXX: symlinks get resolved currently anyway!?
" NOTE: consider using another method like http://stackoverflow.com/questions/13165941/how-to-truncate-long-file-path-in-vim-powerline-statusline
let maxlen_of_parts = 7 " including slash/dot
let maxlen_of_subparts = 1 " split at hypen/underscore; including split
let s:PS = exists('+shellslash') ? (&shellslash ? '/' : '\') : "/"
let parts = split(bufname, '\ze['.escape(s:PS, '\').']')
let i = 0
let n = len(parts)
let wholepath = '' " used for symlink check
while i < n
let wholepath .= parts[i]
" Shorten part, if necessary:
" TODO: use pathshorten(fnamemodify(path, ':~')) as fallback?!
if i < n-1 && len(bufname) > maxlen && len(parts[i]) > maxlen_of_parts
" Let's see if there are dots or hyphens to truncate at, e.g.
" 'vim-pkg-debian' => 'v-p-dâ¦'
let w = split(parts[i], '\ze[_-]')
if len(w) > 1
let parts[i] = ''
for j in w
if len(j) > maxlen_of_subparts-1
let parts[i] .= j[0:max([maxlen_of_subparts-2, 1])] "."â¦"
else
let parts[i] .= j
endif
endfor
else
let parts[i] = parts[i][0:max([maxlen_of_parts-2, 1])].'â¦'
endif
endif
let i += 1
endwhile
let r = join(parts, '')
if len(r) > maxlen
" echom len(r) maxlen
let i = 0
let n -= 1
while i < n && len(join(parts, '')) > maxlen
if i > 0 || parts[i][0] != '~'
let j = 0
let parts[i] = matchstr(parts[i], '.\{-}\w')
" if i == 0 && parts[i][0] != '/'
" let parts[i] = parts[i][0]
" else
" let parts[i] = matchstr(parts[i], 1)
" endif
endif
let i += 1
endwhile
let r = join(parts, '')
endif
let g:_cache_shorten_filename[cache_key] = r
" echom "ShortenFilename" r
return r
endfunction "}}}
" Shorten filename, and append suffix(es), e.g. for modified buffers. {{{2
fun! ShortenFilenameWithSuffix(...)
let r = call('ShortenFilename', a:000)
if &modified
let r .= ',+'
endif
return r
endfun
" }}}
" Opens an edit command with the path of the currently edited file filled in
" Normal mode: <Leader>e
nnoremap <Leader>ee :e <C-R>=expand("%:p:h") . "/" <CR>
nnoremap <Leader>EE :sp <C-R>=expand("%:p:h") . "/" <CR>
" gt: next tab or buffer (source: http://j.mp/dotvimrc)
" enhanced to support range (via v:count)
fun! MyGotoNextTabOrBuffer(...)
let c = a:0 ? a:1 : v:count
exec (c ? c : '') . (tabpagenr('$') == 1 ? 'bn' : 'tabnext')
endfun
fun! MyGotoPrevTabOrBuffer()
exec (v:count ? v:count : '') . (tabpagenr('$') == 1 ? 'bp' : 'tabprevious')
endfun
nnoremap <silent> <Plug>NextTabOrBuffer :<C-U>call MyGotoNextTabOrBuffer()<CR>
nnoremap <silent> <Plug>PrevTabOrBuffer :<C-U>call MyGotoPrevTabOrBuffer()<CR>
" Ctrl-Space: split into new tab.
" Disables diff mode, which gets taken over from the old buffer.
nnoremap <C-Space> :tab sp \| set nodiff<cr>
nnoremap <A-Space> :tabnew<cr>
" For terminal.
nnoremap <C-@> :tab sp \| set nodiff<cr>
" Opens a tab edit command with the path of the currently edited file filled in
map <Leader>te :tabe <C-R>=expand("%:p:h") . "/" <CR>
map <a-o> <C-W>o
" Avoid this to be done accidentally (when zooming is meant). ":on" is more
" explicit.
map <C-W><C-o> <Nop>
" does not work, even with lilyterm.. :/
" TODO: <C-1>..<C-0> for tabs; not possible; only certain C-sequences get
" through to the terminal Vim
" nmap <C-Insert> :tabnew<cr>
" nmap <C-Del> :tabclose<cr>
nmap <A-Del> :tabclose<cr>
" nmap <C-1> 1gt<cr>
" Prev/next tab.
nmap <C-PageUp> <Plug>PrevTabOrBuffer
nmap <C-PageDown> <Plug>NextTabOrBuffer
map <A-,> <Plug>PrevTabOrBuffer
map <A-.> <Plug>NextTabOrBuffer
map <C-S-Tab> <Plug>PrevTabOrBuffer
map <C-Tab> <Plug>NextTabOrBuffer
" Switch to most recently used tab.
" Source: http://stackoverflow.com/a/2120168/15690
fun! MyGotoMRUTab()
if !exists('g:mrutab')
let g:mrutab = 1
endif
if tabpagenr('$') == 1
echomsg "There is only one tab!"
return
endif
if g:mrutab > tabpagenr('$') || g:mrutab == tabpagenr()
let g:mrutab = tabpagenr() > 1 ? tabpagenr()-1 : tabpagenr('$')
endif
exe "tabn ".g:mrutab
endfun
" Overrides Vim's gh command (start select-mode, but I don't use that).
" It can be simulated using v<C-g> also.
nnoremap <silent> gh :call MyGotoMRUTab()<CR>
" nnoremap ° :call MyGotoMRUTab()<CR>
" nnoremap <C-^> :call MyGotoMRUTab()<CR>
augroup MyTL
au!
au TabLeave * let g:mrutab = tabpagenr()
augroup END
" Map <A-1> .. <A-9> to goto tab or buffer.
for i in range(9)
exec 'nmap <M-' .(i+1).'> :call MyGotoNextTabOrBuffer('.(i+1).')<cr>'
endfor
fun! MyGetNonDefaultServername()
" Not for gvim in general (uses v:servername by default), and the global
" server ("G").
let sname = v:servername
if len(sname)
if has('nvim')
if sname !~# '^/tmp/nvim'
let sname = substitute(fnamemodify(v:servername, ':t:r'), '^nvim-', '', '')
return sname
endif
elseif sname !~# '\v^GVIM.*' " && sname =~# '\v^G\d*$'
return sname
endif
endif
return ''
endfun
fun! MyGetSessionName()
" Use / auto-set g:MySessionName
if !len(get(g:, "MySessionName", ""))
if len(v:this_session)
let g:MySessionName = fnamemodify(v:this_session, ':t:r')
elseif len($TERM_INSTANCE_NAME)
let g:MySessionName = substitute($TERM_INSTANCE_NAME, '^vim-', '', '')
else
return ''
end
endif
return g:MySessionName
endfun
" titlestring handling, with tmux support {{{
" Set titlestring, used to set terminal title (pane title in tmux).
set title
" Setup titlestring on BufEnter, when v:servername is available.
fun! MySetupTitleString()
let title = 'â '
let session_name = MyGetSessionName()
if len(session_name)
let title .= '['.session_name.'] '
else
" Add non-default servername to titlestring.
let sname = MyGetNonDefaultServername()
if len(sname)
let title .= '['.sname.'] '
endif
endif
" Call the function and use its result, rather than including it.
" (for performance reasons).
let title .= substitute(
\ ShortenFilenameWithSuffix('%', 15).' ('.ShortenPath(getcwd()).')',
\ '%', '%%', 'g')
if len(s:my_context)
let title .= ' {'.s:my_context.'}'
endif
" Easier to type/find than the unicode symbol prefix.
let title .= ' - vim'
" Append $_TERM_TITLE_SUFFIX (e.g. user@host) to title (set via zsh, used
" with SSH).
if len($_TERM_TITLE_SUFFIX)
let title .= $_TERM_TITLE_SUFFIX
endif
" Setup tmux window name, see ~/.dotfiles/oh-my-zsh/lib/termsupport.zsh.
if len($TMUX)
\ && (!len($_tmux_name_reset) || $_tmux_name_reset != $TMUX . '_' . $TMUX_PANE)
let tmux_auto_rename=systemlist('tmux show-window-options -t '.$TMUX_PANE.' -v automatic-rename 2>/dev/null')
" || $(tmux show-window-options -t $TMUX_PANE | grep '^automatic-rename' | cut -f2 -d\ )
" echom string(tmux_auto_rename)
if !len(tmux_auto_rename) || tmux_auto_rename[0] != "off"
" echom "Resetting tmux name to 0."
call system('tmux set-window-option -t '.$TMUX_PANE.' -q automatic-rename off')
call system('tmux rename-window -t '.$TMUX_PANE.' 0')
endif
endif
let &titlestring = title
" Set icon text according to &titlestring (used for minimized windows).
let &iconstring = '(v) '.&titlestring
endfun
augroup vimrc_title
au!
" XXX: might not get called with fugitive buffers (title is the (closed) fugitive buffer).
autocmd BufEnter,BufWritePost * call MySetupTitleString()
if exists('##TextChanged')
autocmd TextChanged * call MySetupTitleString()
endif
augroup END
" Make Vim set the window title according to &titlestring.
if !has('gui_running') && empty(&t_ts)
if len($TMUX)
let &t_ts = "\e]2;"
let &t_fs = "\007"
elseif &term =~ "^screen.*"
let &t_ts="\ek"
let &t_fs="\e\\"
endif
endif
fun! MySetSessionName(name)
let g:MySessionName = a:name
call MySetupTitleString()
endfun
"}}}
" Inserts the path of the currently edited file into a command
" Command mode: Ctrl+P
" cmap <C-P> <C-R>=expand("%:p:h") . "/" <CR>
" Change to current file's dir
nnoremap <Leader>cd :lcd <C-R>=expand('%:p:h')<CR><CR>
" yankstack, see also unite's history/yank {{{1
if &rtp =~ '\<yankstack\>'
" Do not map s/S (used by vim-sneak).
" let g:yankstack_yank_keys = ['c', 'C', 'd', 'D', 's', 'S', 'x', 'X', 'y', 'Y']
let g:yankstack_yank_keys = ['c', 'C', 'd', 'D', 'x', 'X', 'y', 'Y']
" Setup yankstack now to make yank/paste related mappings work.
call yankstack#setup()
endif
" Command-line maps to act on the current search (with incsearch). {{{
" E.g. '?foo$m' will move the matched line to where search started.
" Source: http://www.reddit.com/r/vim/comments/1yfzg2/does_anyone_actually_use_easymotion/cfkaxw5
" NOTE: with vim-oblique, '?' and '/' are mapped, and not in getcmdtype().
fun! MyCmdMapNotForColon(from, to, ...)
let init = a:0 ? 0 : 1
if init
exec printf('cnoremap <expr> %s MyCmdMapNotForColon("%s", "%s", 1)',
\ a:from, a:from, a:to)
return
endif
if index([':', '>', '@', '-', '='], getcmdtype()) == 0
return a:from
endif
return a:to
endfun
call MyCmdMapNotForColon('$d', "<CR>:delete<CR>``")
call MyCmdMapNotForColon('$m', "<CR>:move''<CR>")
call MyCmdMapNotForColon('$c', "<CR>:copy''<CR>")
call MyCmdMapNotForColon('$t', "<CR>:t''<CR>") " synonym for :copy
" Allow to quickly enter a single $.
cnoremap $$ $
" }}}
" sneak {{{1
" Overwrite yankstack with sneak maps.
" Ref: https://github.com/maxbrunsfeld/vim-yankstack/issues/39
nmap s <Plug>Sneak_s
nmap S <Plug>Sneak_S
xmap s <Plug>Sneak_s
xmap S <Plug>Sneak_S
omap s <Plug>Sneak_s
omap S <Plug>Sneak_S
" Use streak mode, also for Sneak_f/Sneak_t.
let g:sneak#streak=2
let g:sneak#s_next = 1 " clever-s
let g:sneak#target_labels = "sfjktunbqz/SFKGHLTUNBRMQZ?"
" Replace 'f' with inclusive 1-char Sneak.
nmap f <Plug>Sneak_f
nmap F <Plug>Sneak_F
xmap f <Plug>Sneak_f
xmap F <Plug>Sneak_F
omap f <Plug>Sneak_f
omap F <Plug>Sneak_F
" Replace 't' with exclusive 1-char Sneak.
nmap t <Plug>Sneak_t
nmap T <Plug>Sneak_T
xmap t <Plug>Sneak_t
xmap T <Plug>Sneak_T
omap t <Plug>Sneak_t
omap T <Plug>Sneak_T
" IDEA: just use 'f' for sneak, leaving 's' at its default.
" nmap f <Plug>Sneak_s
" nmap F <Plug>Sneak_S
" xmap f <Plug>Sneak_s
" xmap F <Plug>Sneak_S
" omap f <Plug>Sneak_s
" omap F <Plug>Sneak_S
" }}}1
" GoldenView {{{1
let g:goldenview__enable_default_mapping = 0
let g:goldenview__enable_at_startup = 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.