diff --git a/tools/.gitignore b/tools/.gitignore deleted file mode 100644 index e69de29bb..000000000 diff --git a/tools/IRC_Bot/SRB2MS_Bot.php b/tools/IRC_Bot/SRB2MS_Bot.php deleted file mode 100644 index 842083bf9..000000000 --- a/tools/IRC_Bot/SRB2MS_Bot.php +++ /dev/null @@ -1,227 +0,0 @@ - - * SRB2MS.php Copyright (c) 2004 by Logan Arias of Sonic Team JR. - * - * the Rest is Copyright (c) 2004 Logan Arias - * This is LGPL! that means you can change and use as you like - * - * Full LGPL License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -include_once('./SmartIRC.php'); - -class SRB2MS_BOT -{ - - function ListGamesPM(&$irc, &$data) - { - $fd = fsockopen("srb2.servegame.org", 28900, $errno, $errstr, 5); - if ($fd) - { - $buff = "000012360000"; - fwrite($fd, $buff); - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'Running SRB2 NetGames '); - while (1) - { - $content=fgets($fd, 13); // skip 13 first bytes - $content=fgets($fd, 1024); - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "$content"); - //echo "$content"; - if (feof($fd)) break; - } - } - else - { - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, 'The SRB2 MasterServer is not up'); - } - } - - function ListGamesChan(&$irc, &$data) - { - $fd = fsockopen("192.168.0.2", 28900, $errno, $errstr, 5); - if ($fd) - { - $buff = "000012360000"; - fwrite($fd, $buff); - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'Running SRB2 NetGames '); - while (1) - { - $content=fgets($fd, 13); // skip 13 first bytes - $content=fgets($fd, 1024); - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$content"); - //echo "$content"; - if (feof($fd)) break; - } - } - else - { - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'The SRB2 MasterServer is not up'); - } - } - - function BeenInvited(&$irc, &$data) - { - if ($data->message == '#srb2fun') - $irc->join($data->message); - - foreach ($irc->channel['#srb2fun']->ops as $invitenick => $key ) - { - if ($data->nick == $invitenick) - { - $irc->join($data->message); - return; - } - if ($data->nick == 'Logan_GBA') - { - $irc->join($data->message); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key ) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, "Sorry, but I don't like you, or your channel, $data->message"); - return; - } - } - //$irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "Sorry, but I don't like you, or your channel, $data->message"); - } - - function Talk(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key) - { - if ($data->nick == $nick) - { - $msg = str_replace("!talk ", '', "$data->message"); - $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', $msg); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, 'Stop talking to me!'); - return; - } - } - } - - function Action(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key) - { - if ($data->nick == $nick) - { - $msg = str_replace("!action ", '', "$data->message"); - $irc->message(SMARTIRC_TYPE_ACTION, '#srb2fun', $msg); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, 'Stop talking to me!'); - return; - } - } - } - - function Kick(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key) - { - if ($data->nick == $nick) - { - $msg = str_replace("!kick ", '', "$data->message"); - $irc->kick('#srb2fun', $msg); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, 'Stop talking to me!'); - return; - } - } - } - - function DebugPM(&$irc, &$data) - { - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "from:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->from"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "nick:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->nick"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "ident:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->ident"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "host:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->host"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "channel:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->channel"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "message:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->message"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "type:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->type"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "rawmessage:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->rawmessage"); - } - -} - -// the Bot is the Class SRB2MS_BOT -$bot = &new SRB2MS_BOT(); -// Create SmartIRC, and name it as irc for use to, well, do irc stuff ^_^ -$esperirc = &new Net_SmartIRC(); -//no Excess Flood! -//$esperirc->setSendDelay(300); -// To Debug or Not -//$esperirc->setDebug(SMARTIRC_DEBUG_IRCMESSAGES); -// Do connect to the Internet -$esperirc->setUseSockets(TRUE); -// Register the trigger !listgames as to call ListGames with the class of SRB2MS_BOT -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!gamelist$', $bot, 'ListGamesPM'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!gamelist$', $bot, 'ListGamesChan'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_INVITE, '', $bot, 'BeenInvited'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_ALL, '', $bot, 'DebugPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!talk', $bot, 'Talk'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!action', $bot, 'Action'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!kick', $bot, 'Kick'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!ban', $bot, 'Ban'); -// If you fail once, try agian -$esperirc->setAutoRetry(TRUE); -// Connect to EsperNet -$esperirc->connect('cosmos.esper.net', 6667); -// kep a list of all the users in the channel -$esperirc->setChannelSyncing(TRUE); -// Reconnect as needed -$esperirc->setAutoReconnect(TRUE); -// Use the name SRB2MS, and set other stuff -$esperirc->login('SRB2MS2', 'Net_SmartIRC Client '.SMARTIRC_VERSION.' (SRB2MS_Bot.php)', 0, 'Net_SmartIRC'); -// Join #srb2fun and #srb2general -$esperirc->join((array('#srb2general,#srb2fun'))); -// SRB2MS_Pass.php have "$esperirc->message(SMARTIRC_TYPE_QUERY, 'nickserv', 'identify ');" -include('./SRB2MS_Pass.php'); -// Idle -$esperirc->listen(); -// Rejoin? -$esperirc->reconnect(); -?> diff --git a/tools/IRC_Bot/SRB2MS_Bot_beta.php b/tools/IRC_Bot/SRB2MS_Bot_beta.php deleted file mode 100644 index 3933d5405..000000000 --- a/tools/IRC_Bot/SRB2MS_Bot_beta.php +++ /dev/null @@ -1,739 +0,0 @@ - - * SRB2MS.php Copyright (c) 2004 by Logan Arias of Sonic Team JR. - * - * the Rest is Copyright (c) 2004 Logan Arias - * This is LGPL! that means you can change and use as you like - * - * Full LGPL License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -include_once('./SmartIRC.php'); -define('MAGPIE_DIR', './magpierss/'); -// define('MAGPIE_CACHE_AGE', 30); // half-min -require_once(MAGPIE_DIR.'rss_fetch.inc'); -require_once(MAGPIE_DIR.'rss_utils.inc'); -$today = getdate(); -$lastupdatetime = mktime($today['hours'],$today['minutes']-6,0,$today['mon'], $today['mday'], $today['year']); -$lastlisttime = mktime($today['hours'],$today['minutes']-1,0,$today['mon'], $today['mday'], $today['year']); - -class SRB2MS_BOT -{ - - function ListUsersPM(&$irc, &$data) - { - global $rssdatabase; - if ($rssdatabase->users[0]) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'List of RSS users'); - foreach ($rssdatabase->users as $users) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "$users"); - } - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'there are no RSS users'); - } - } - - function RSSupdateuser(&$irc, &$data) - { - global $rssdatabase; - if ($rssdatabase->OnList("$data->nick")) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->message, "I am trying to update $data->nick to $data->message from the list"); - if ($rssdatabase->ReplaceUser("$data->nick","$data->message")) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->message, "I have changed $data->nick to $data->message on the list"); - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->message, "$data->nick was not on the list"); - } - } - } - - function RSScheckuser(&$irc, &$data) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "I going to check if you are on the list"); - global $rssdatabase; - if ($rssdatabase->OnList("$data->nick")) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "you are on the list"); - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "you are not on the list"); - } - } - - function RSSremoveuser(&$irc, &$data) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "I am trying to remove $data->nick from the list"); - global $rssdatabase; - if ($rssdatabase->DeleteUser("$data->nick")) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "I have removed $data->nick from the list"); - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "$data->nick is not on the list"); - } - } - - function RSSadduser(&$irc, &$data) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "I am trying to add you $data->nick to the list"); - global $rssdatabase; - if ($rssdatabase->AddUser("$data->nick")) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "I have added $data->nick to the list"); - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "$data->nick is already on the list"); - } - } -/* - function RSSListGamesPM(&$irc, &$data) - { - $content = $this->GenFeed(); - $SRB2MSRSS10 = new MagpieRSS( $content ); - if ($SRB2MSRSS10) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'Running SRB2 netgames '); - foreach ($SRB2MSRSS10->items as $item) - { - $description = $item['dc']['description']; - $title = $item['title']; - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "Name: $title $description"); - } - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, '.magpie_error()'); - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'The SRB2 MasterServer RSS feed is not up'); - } - } -*/ - function RSSListUpdate(&$irc) - { - global $lastupdatetime; - global $SRB2MS_mute; - if ($SRB2MS_mute) - { - return; - } - $RSS10content = $this->GenFeed(); - $SRB2MSRSS10 = new MagpieRSS( $RSS10content ); - if ($SRB2MSRSS10) - { - //$irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', 'Running SRB2 netgames '); - foreach ($SRB2MSRSS10->items as $item) - { - if ( $item['title'] == "No servers" ) - { - // NOP - } - elseif ( $item['title'] == "No master server" ) - { - // NOP - } - else - { - $published = parse_w3cdtf($item['dc']['date']); - if ( $published >= $lastupdatetime ) - { - $title = $item['title']; - $serveraddress = $item['srb2ms']['address']; - $serverport = $item['srb2ms']['port']; - $serverversion = $item['srb2ms']['version']; - //if ( $serverversion == "1.09.3" ) - //{ - // $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun' , "New Server, $serveraddress:$serverport Name: $title"); - //} - //else - { - $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun' , "New Server, $serveraddress:$serverport Name: $title Version: $serverversion"); - } - //$irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2general', "New Server, Name: $title $description"); - } - else - { - // NOP - } - } - - } - $today = getdate(); - // update time - $lastupdatetime = mktime($today['hours'],$today['minutes'],0,$today['mon'], $today['mday'], $today['year']); - } - else - { - $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', '.magpie_error()'); - $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', 'The SRB2 MasterServer RSS feed is not up'); - } - } - - function Mute(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key ) - { - if ($data->nick == $nick || $data->nick == 'Logan_GBA') - { - global $lastupdatetime; - $today = getdate(); - // update time - $lastupdatetime = mktime($today['hours'],$today['minutes'],0,$today['mon'], $today['mday'], $today['year']); - $GLOBALS['SRB2MS_mute'] = TRUE; - return; - } - } - } - - function Unmute(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key ) - { - if ($data->nick == $nick || $data->nick == 'Logan_GBA') - { - $GLOBALS['SRB2MS_mute'] = FALSE; - return; - } - } - } - - - function Mute2(&$irc, &$data) - { - if ($data->nick == 'Logan_GBA') - { - global $lastupdatetime; - $today = getdate(); - // update time - $lastupdatetime = mktime($today['hours'],$today['minutes'],0,$today['mon'], $today['mday'], $today['year']); - $GLOBALS['SRB2MS_mute'] = TRUE; - } - } - - function Unmute2(&$irc, &$data) - { - if ($data->nick == 'Logan_GBA') - { - $GLOBALS['SRB2MS_mute'] = FALSE; - } - } - - function RSSListGames(&$irc, &$data) - { - global $lastlisttime; - $content = $this->GenFeed(); - $today = getdate(); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'testing feed'); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$content"); - //$content1 = $this->Gettextfromserver(); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$content1"); - $SRB2MSRSS10 = new MagpieRSS( $content ); - if ($SRB2MSRSS10) - { - if ((mktime($today['hours'],$today['minutes']-2,0,$today['mon'], $today['mday'], $today['year'])) >= $lastlisttime) - { - //$irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', 'Running SRB2 netgames '); - foreach ($SRB2MSRSS10->items as $item) - { - if ( $item['title'] == "No servers" ) - { - //0$description = $item['dc']['description']; - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "No SRB2 Games are running, so why don't you start one?"); - } - elseif ( $item['title'] == "No master server" ) - { - $description = $item['dc']['description']; - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$description"); - } - else - { - $title = $item['title']; - $serveraddress = $item['srb2ms']['address']; - $serverport = $item['srb2ms']['port']; - $serverversion = $item['srb2ms']['version']; - //if ( $serverport == " 5029" ) - //{ - // $serverport = "5029"; - //} - //if ( $serverversion == "1.09.3" ) - //{ - // $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun' , "$serveraddress:$serverport Name: $title"); - //} - //else - { - $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun' , "$serveraddress:$serverport Name: $title Version: $serverversion"); - } - - } - - } - $today = getdate(); - $lastlisttime = mktime($today['hours'],$today['minutes'],0,$today['mon'], $today['mday'], $today['year']); - } - - } - else - { - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, ".magpie_error()"); - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'The SRB2 MasterServer RSS feed is not up'); - } - } - - function RSSListGamesPM(&$irc, &$data) - { - global $lastlisttime; - $content = $this->GenFeed(); - $today = getdate(); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'testing feed'); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$content"); - //$content1 = $this->Gettextfromserver(); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$content1"); - $SRB2MSRSS10 = new MagpieRSS( $content ); - if ($SRB2MSRSS10) - { - //if ((mktime($today['hours'],$today['minutes']-2,0,$today['mon'], $today['mday'], $today['year'])) >= $lastlisttime) - { - //$irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', 'Running SRB2 netgames '); - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "Running SRB2 netgames from http://srb2.servegame.org/"); - foreach ($SRB2MSRSS10->items as $item) - { - if ( $item['title'] == "No servers" ) - { - //0$description = $item['dc']['description']; - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "No SRB2 Games are running, so why don't you start one?"); - } - elseif ( $item['title'] == "No master server" ) - { - $description = $item['dc']['description']; - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$description"); - } - else - { - $title = $item['title']; - $serveraddress = $item['srb2ms']['address']; - $serverport = $item['srb2ms']['port']; - $serverversion = $item['srb2ms']['version']; - //if ( $serverport == " 5029" ) - //{ - // $serverport = "5029"; - //} - //if ( $serverversion == "1.09.3" ) - //{ - // $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun' , "$serveraddress:$serverport Name: $title"); - //} - //else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "$serveraddress:$serverport Name: $title Version: $serverversion"); - } - - } - - } - $today = getdate(); - $lastlisttime = mktime($today['hours'],$today['minutes'],0,$today['mon'], $today['mday'], $today['year']); - } - - } - else - { - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, ".magpie_error()"); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'The SRB2 MasterServer RSS feed is not up'); - } - } - - function ListGamesPM(&$irc, &$data) - { - $fd = fsockopen("srb2.servegame.org", 28900, $errno, $errstr, 5); - if ($fd) - { - $buff = "000012360000"; - fwrite($fd, $buff); - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'Running SRB2 netgames '); - while (1) - { - $content=fgets($fd, 13); // skip 13 first bytes - $content=fgets($fd, 1024); - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "$content"); - //echo "$content"; - if (feof($fd)) break; - } - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'The SRB2 MasterServer is not up'); - } - } - - function ListGamesChan(&$irc, &$data) - { - global $lastlisttime; - $today = getdate(); - $fd = fsockopen("srb2.servegame.org", 28900, $errno, $errstr, 5); - if ($fd) - { - stream_set_timeout ($fd, 5); - $buff = "000012360000"; - fwrite($fd, $buff); - if ( (mktime($today['hours'],$today['minutes']-5,0,$today['mon'], $today['mday'], $today['year'])) >= $lastlisttime ) - { - $content = ""; - while (1) - { - fgets($fd, 13); // skip 13 first bytes - $content = fgets($fd, 1024); - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$content"); - $today = getdate(); - $lastlisttime = mktime($today['hours'],$today['minutes'],0,$today['mon'], $today['mday'], $today['year']); - if (feof($fd)) break; - } - } - } - else - { - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'The SRB2 MasterServer is not up'); - } - } - - function byebye(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $quitnick => $key ) - { - if ($data->nick == $quitnick) - { - $irc->setAutoReconnect(FALSE); - $irc->setAutoRetry(FALSE); - $irc->quit('This quit was done by' + "$data->nick"); - return; - } - } - } - - function BeenInvited(&$irc, &$data) - { - if ($data->message == '#srb2fun') - $irc->join($data->message); - - foreach ($irc->channel['#srb2fun']->ops as $invitenick => $key ) - { - if ($data->nick == $invitenick) - { - $irc->join($data->message); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key ) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, "Sorry, but I don't like you, or your channel, $data->message"); - return; - } - } - //$irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "Sorry, but I don't like you, or your channel, $data->message"); - } - - function Talk(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key) - { - if ($data->nick == $nick) - { - $msg = str_replace("!talk ", '', "$data->message"); - $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', $msg); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, 'Stop talking to me!'); - return; - } - } - } - - function Action(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key) - { - if ($data->nick == $nick) - { - $msg = str_replace("!action ", '', "$data->message"); - $irc->message(SMARTIRC_TYPE_ACTION, '#srb2fun', $msg); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, 'Stop talking to me!'); - return; - } - } - } - - function Kick(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key) - { - if ($data->nick == $nick) - { - $msg = str_replace("!kick ", '', "$data->message"); - $irc->kick('#srb2fun', $msg); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, 'Stop talking to me!'); - return; - } - } - } - - function DebugPM(&$irc, &$data) - { -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "from:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->from"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "nick:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->nick"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "ident:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->ident"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "host:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->host"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "channel:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->channel"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "message:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->message"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "type:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->type"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "rawmessage:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->rawmessage"); - - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "from: $data->from"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "nick: $data->nick"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "ident: $data->ident"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "host: $data->host"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "channel: $data->channel"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "message: $data->message"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "type: $data->type"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "rawmessage: $data->rawmessage"); - } - - function GetRSS10datafromserver() - { - $content = ""; - $fd = fsockopen("srb2.servegame.org", 28900, $errno, $errstr, 5); - if ($fd) - { - $buff = "000012400000"; - fwrite($fd, $buff); - while (1) - { - fgets($fd, 13); // skip 13 first bytes - $content .= fgets($fd, 1024); - if (feof($fd)) break; - } - fclose($fd); - } - else - { - $content = ''; - $content .= ''; - $content .= ''; - $content .= ''; - $content .= ''; - $content .= ''; - $content .= "\n"; - $content .= ' '; - $content .= 'No master serverThe master server is not running'; - } - return "$content"; - } - - function GenFeed() - { - $content = ''; - $content .= "\n"; - $content .= 'GetRSS10datafromserver(); - $content .= "$feed"; - $content .= ''; - return $content; - } -} - -class RSSDataBase_Class -{ - var $users = array(); - - function OnList($User) - { - $userbeenfound = FALSE; - foreach ($this->users as $Userlist) - { - if ($Userlist == $User) { - $userbeenfound = TRUE; } - } - return $userbeenfound; - } - - function AddUser($User) - { - $userbeenfound = FALSE; - foreach ($this->users as $Userlist) - { - if ($Userlist == $User) { - $userbeenfound = TRUE; } - } - if (!$userbeenfound) { - $this->users[] = $User; - } - return !$userbeenfound; - } - - function DeleteUser($User) - { - $userbeenfound = FALSE; - foreach ($this->users as $index => $Userlist) - { - if ($Userlist == $User) - { - $userbeenfound = TRUE; - $id = $index; - } - } - if ($userbeenfound) - { - unset($this->users[$id]); - $this->users = array_values($this->users); - } - return $userbeenfound; - } - function ReplaceUser($oldUser,$newUser) - { - $userbeenfound = FALSE; - foreach ($this->users as $index => $Userlist) - { - if ($Userlist == $oldUser) - { - $userbeenfound = TRUE; - $id = $index; - } - } - if ($userbeenfound) - { - $this->users[$id] = $newUser; - } - return $userbeenfound; - } -} -// gobal var for muting the Bot -$SRB2MS_mute = FALSE; -//$SRB2MSRSS10 = fetch_rss( 'http://srb2.servegame.org/RSS1.0.php' ); -// thing to hold RSS stuff -$rssdatabase = &new RSSDataBase_Class(); -// PHP error reporting -//error_reporting(E_ERROR); -// the Bot is the Class SRB2MS_BOT -$bot = &new SRB2MS_BOT(); -// Create SmartIRC, and name it as irc for use to, well, do irc stuff ^_^ -$esperirc = &new Net_SmartIRC(); -// To Debug or Not -//$esperirc->setDebug(SMARTIRC_DEBUG_ALL); -// Do connect to the Internet -$esperirc->setUseSockets(TRUE); -// kep a list of all the users in the channel -$esperirc->setChannelSyncing(TRUE); -// Register the triggers with the class of SRB2MS_BOT -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!gamelist$', $bot, 'ListGamesChan'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!gamelist$', $bot, 'ListGamesPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!RSSgamelist$', $bot, 'RSSListGamesPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!gamelist0$', $bot, 'RSSListGames'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!gamelist$', $bot, 'RSSListGamesPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!gamelist$', $bot, 'RSSListGamesPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!addme$', $bot, 'RSSadduser'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!removeme$', $bot, 'RSSremoveuser'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!listusers$', $bot, 'ListUsersPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_NICKCHANGE, '', $bot, 'RSSupdateuser'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!checkme$', $bot, 'RSScheckuser'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!shutdown$', $bot, 'byebye'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!mute$', $bot, 'Mute'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!unmute$', $bot, 'Unmute'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!shutup$', $bot, 'Mute2'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!talktome$', $bot, 'Unmute2'); -$esperirc->registerTimehandler(120000, $bot, 'RSSListUpdate'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!gamelist$', $bot, 'ListGamesChan'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_INVITE, '', $bot, 'BeenInvited'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!talk', $bot, 'Talk'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!action', $bot, 'Action'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!kick', $bot, 'Kick'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!ban', $bot, 'Ban'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_ALL, '', $bot, 'DebugPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_KICK | SMARTIRC_TYPE_QUIT | SMARTIRC_TYPE_PART, '', $bot, 'DebugPM'); -// If you fail once, try agian -$esperirc->setAutoRetry(TRUE); -// Connect to EsperNet -//$esperirc->connect('irc.esper.net', 6667); -$esperirc->connect('excalibur.esper.net', 6667); -// Reconnect as needed -$esperirc->setAutoReconnect(TRUE); -// Use the name SRB2MS, and set other stuff -$esperirc->login('SRB2MS', 'Net_SmartIRC Client '.SMARTIRC_VERSION.' (SRB2MS_Bot.php)', 0, 'Net_SmartIRC'); -// Join #srb2fun -$esperirc->join(array('#srb2fun')); -// SRB2MS_Pass.php have "$esperirc->message(SMARTIRC_TYPE_QUERY, 'nickserv', 'identify ');" -include('./SRB2MS_Pass.php'); -// Idle -$esperirc->listen(); -// Rejoin? -$esperirc->reconnect(); - -?> diff --git a/tools/IRC_Bot/SmartIRC.php b/tools/IRC_Bot/SmartIRC.php deleted file mode 100644 index e0167a8e5..000000000 --- a/tools/IRC_Bot/SmartIRC.php +++ /dev/null @@ -1,2553 +0,0 @@ - and - * Latest versions of Net_SmartIRC you will find on the project homepage - * or get it through PEAR since SmartIRC is an official PEAR package. - * See . - * - * Official Projet Homepage: - * - * Net_SmartIRC conforms to RFC 2812 (Internet Relay Chat: Client Protocol) - * - * Copyright (c) 2002-2003 Mirco 'meebey' Bauer - * - * Full LGPL License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -// ------- PHP code ---------- -include_once('SmartIRC/defines.php'); -include_once('SmartIRC/irccommands.php'); -include_once('SmartIRC/messagehandler.php'); -define('SMARTIRC_VERSION', '1.0.0 ($Revision: 1.54.2.14 $)'); -define('SMARTIRC_VERSIONSTRING', 'Net_SmartIRC '.SMARTIRC_VERSION); - -/** - * main SmartIRC class - * - * @package Net_SmartIRC - * @version 0.5.5 - * @author Mirco 'meebey' Bauer - * @access public - */ -class Net_SmartIRC_base -{ - /** - * @var resource - * @access private - */ - var $_socket; - - /** - * @var string - * @access private - */ - var $_address; - - /** - * @var integer - * @access private - */ - var $_port; - - /** - * @var string - * @access private - */ - var $_nick; - - /** - * @var string - * @access private - */ - var $_username; - - /** - * @var string - * @access private - */ - var $_realname; - - /** - * @var string - * @access private - */ - var $_usermode; - - /** - * @var string - * @access private - */ - var $_password; - - /** - * @var boolean - * @access private - */ - var $_state = false; - - /** - * @var array - * @access private - */ - var $_actionhandler = array(); - - /** - * @var array - * @access private - */ - var $_timehandler = array(); - - /** - * @var integer - * @access private - */ - var $_debug = SMARTIRC_DEBUG_NOTICE; - - /** - * @var array - * @access private - */ - var $_messagebuffer = array(); - - /** - * @var integer - * @access private - */ - var $_messagebuffersize; - - /** - * @var boolean - * @access private - */ - var $_usesockets = false; - - /** - * @var integer - * @access private - */ - var $_receivedelay = 100; - - /** - * @var integer - * @access private - */ - var $_senddelay = 250; - - /** - * @var integer - * @access private - */ - var $_logdestination = SMARTIRC_STDOUT; - - /** - * @var resource - * @access private - */ - var $_logfilefp = 0; - - /** - * @var string - * @access private - */ - var $_logfile = 'Net_SmartIRC.log'; - - /** - * @var integer - * @access private - */ - var $_disconnecttime = 1000; - - /** - * @var boolean - * @access private - */ - var $_loggedin = false; - - /** - * @var boolean - * @access private - */ - var $_benchmark = false; - - /** - * @var integer - * @access private - */ - var $_benchmark_starttime; - - /** - * @var integer - * @access private - */ - var $_benchmark_stoptime; - - /** - * @var integer - * @access private - */ - var $_actionhandlerid = 0; - - /** - * @var integer - * @access private - */ - var $_timehandlerid = 0; - - /** - * @var array - * @access private - */ - var $_motd = array(); - - /** - * @var array - * @access private - */ - var $_channels = array(); - - /** - * @var boolean - * @access private - */ - var $_channelsyncing = false; - - /** - * @var string - * @access private - */ - var $_ctcpversion; - - /** - * @var mixed - * @access private - */ - var $_mintimer = false; - - /** - * @var integer - * @access private - */ - var $_maxtimer = 300000; - - /** - * @var integer - * @access private - */ - var $_txtimeout = 300; - - /** - * @var integer - * @access private - */ - var $_rxtimeout = 300; - - /** - * @var integer - * @access private - */ - var $_selecttimeout; - - /** - * @var integer - * @access private - */ - var $_lastrx; - - /** - * @var integer - * @access private - */ - var $_lasttx; - - /** - * @var boolean - * @access private - */ - var $_autoreconnect = false; - - /** - * @var boolean - * @access private - */ - var $_autoretry = false; - - /** - * All IRC replycodes, the index is the replycode name. - * - * @see $SMARTIRC_replycodes - * @var array - * @access public - */ - var $replycodes; - - /** - * All numeric IRC replycodes, the index is the numeric replycode. - * - * @see $SMARTIRC_nreplycodes - * @var array - * @access public - */ - var $nreplycodes; - - /** - * Stores all channels in this array where we are joined, works only if channelsyncing is activated. - * Eg. for accessing a user, use it like this: (in this example the SmartIRC object is stored in $irc) - * $irc->channel['#test']->users['meebey']->nick; - * - * @see setChannelSyncing() - * @see Net_SmartIRC_channel - * @see Net_SmartIRC_channeluser - * @var array - * @access public - */ - var $channel; - - /** - * Constructor. Initiales the messagebuffer and "links" the replycodes from - * global into properties. Also some PHP runtime settings are configured. - * - * @access public - * @return void - */ - function Net_SmartIRC_base() - { - // precheck - $this->_checkPHPVersion(); - - ob_implicit_flush(true); - @set_time_limit(0); - ignore_user_abort(true); - $this->_messagebuffer[SMARTIRC_CRITICAL] = array(); - $this->_messagebuffer[SMARTIRC_HIGH] = array(); - $this->_messagebuffer[SMARTIRC_MEDIUM] = array(); - $this->_messagebuffer[SMARTIRC_LOW] = array(); - $this->replycodes = &$GLOBALS['SMARTIRC_replycodes']; - $this->nreplycodes = &$GLOBALS['SMARTIRC_nreplycodes']; - - // hack till PHP allows (PHP5) $object->method($param)->$object - $this->channel = &$this->_channels; - // another hack - $this->user = &$this->_users; - - if (isset($_SERVER['REQUEST_METHOD'])) { - // the script is called from a browser, lets set default log destination - // to SMARTIRC_BROWSEROUT (makes browser friendly output) - $this->setLogdestination(SMARTIRC_BROWSEROUT); - } - } - - /** - * Enables/disables the usage of real sockets. - * - * Enables/disables the usage of real sockets instead of fsocks - * (works only if your PHP build has loaded the PHP socket extension) - * Default: false - * - * @param bool $boolean - * @return void - * @access public - */ - function setUseSockets($boolean) - { - if ($boolean === true) { - if (@extension_loaded('sockets')) { - $this->_usesockets = true; - } else { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: socket extension not loaded, trying to load it...', __FILE__, __LINE__); - - if (strtoupper(substr(PHP_OS, 0,3) == 'WIN')) { - $load_status = @dl('php_sockets.dll'); - } else { - $load_status = @dl('sockets.so'); - } - - if ($load_status) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: socket extension succesfully loaded', __FILE__, __LINE__); - $this->_usesockets = true; - } else { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: couldn\'t load the socket extension', __FILE__, __LINE__); - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: your PHP build doesn\'t support real sockets, will use fsocks instead', __FILE__, __LINE__); - $this->_usesockets = false; - } - } - } else { - $this->_usesockets = false; - } - } - - /** - * Sets the level of debug messages. - * - * Sets the debug level (bitwise), useful for testing/developing your code. - * Here the list of all possible debug levels: - * SMARTIRC_DEBUG_NONE - * SMARTIRC_DEBUG_NOTICE - * SMARTIRC_DEBUG_CONNECTION - * SMARTIRC_DEBUG_SOCKET - * SMARTIRC_DEBUG_IRCMESSAGES - * SMARTIRC_DEBUG_MESSAGETYPES - * SMARTIRC_DEBUG_ACTIONHANDLER - * SMARTIRC_DEBUG_TIMEHANDLER - * SMARTIRC_DEBUG_MESSAGEHANDLER - * SMARTIRC_DEBUG_CHANNELSYNCING - * SMARTIRC_DEBUG_MODULES - * SMARTIRC_DEBUG_USERSYNCING - * SMARTIRC_DEBUG_ALL - * - * Default: SMARTIRC_DEBUG_NOTICE - * - * @see DOCUMENTATION - * @see SMARTIRC_DEBUG_NOTICE - * @param integer $level - * @return void - * @access public - */ - function setDebug($level) - { - $this->_debug = $level; - } - - /** - * Enables/disables the benchmark engine. - * - * @param boolean $boolean - * @return void - * @access public - */ - function setBenchmark($boolean) - { - if (is_bool($boolean)) { - $this->_benchmark = $boolean; - } else { - $this->_benchmark = false; - } - } - - /** - * Deprecated, use setChannelSyncing() instead! - * - * @deprecated - * @param boolean $boolean - * @return void - * @access public - */ - function setChannelSynching($boolean) - { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: you are using setChannelSynching() which is a deprecated method, use setChannelSyncing() instead!', __FILE__, __LINE__); - $this->setChannelSyncing($boolean); - } - - /** - * Enables/disables channel syncing. - * - * Channel syncing means, all users on all channel we are joined are tracked in the - * channel array. This makes it very handy for botcoding. - * - * @param boolean $boolean - * @return void - * @access public - */ - function setChannelSyncing($boolean) - { - if (is_bool($boolean)) { - $this->_channelsyncing = $boolean; - } else { - $this->_channelsyncing = false; - } - - if ($this->_channelsyncing == true) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: Channel syncing enabled', __FILE__, __LINE__); - } else { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: Channel syncing disabled', __FILE__, __LINE__); - } - } - - /** - * Sets the CTCP version reply string. - * - * @param string $versionstring - * @return void - * @access public - */ - function setCtcpVersion($versionstring) - { - $this->_ctcpversion = $versionstring; - } - - /** - * Sets the destination of all log messages. - * - * Sets the destination of log messages. - * $type can be: - * SMARTIRC_FILE for saving the log into a file - * SMARTIRC_STDOUT for echoing the log to stdout - * SMARTIRC_SYSLOG for sending the log to the syslog - * Default: SMARTIRC_STDOUT - * - * @see SMARTIRC_STDOUT - * @param integer $type must be on of the constants - * @return void - * @access public - */ - function setLogdestination($type) - { - switch ($type) { - case (SMARTIRC_FILE || - SMARTIRC_STDOUT || - SMARTIRC_SYSLOG || - SMARTIRC_BROWSEROUT || - SMARTIRC_NONE): - $this->_logdestination = $type; - break; - default: - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: unknown logdestination type ('.$type.'), will use STDOUT instead', __FILE__, __LINE__); - $this->_logdestination = SMARTIRC_STDOUT; - } - } - - /** - * Sets the file for the log if the destination is set to file. - * - * Sets the logfile, if {@link setLogdestination logdestination} is set to SMARTIRC_FILE. - * This should be only used with full path! - * - * @param string $file - * @return void - * @access public - */ - function setLogfile($file) - { - $this->_logfile = $file; - } - - /** - * Sets the delaytime before closing the socket when disconnect. - * - * @param integer $milliseconds - * @return void - * @access public - */ - function setDisconnecttime($milliseconds) - { - if (is_integer($milliseconds) && $milliseconds >= 100) { - $this->_disconnecttime = $milliseconds; - } else { - $this->_disconnecttime = 100; - } - } - - /** - * Sets the delay for receiving data from the IRC server. - * - * Sets the delaytime between messages that are received, this reduces your CPU load. - * Don't set this too low (min 100ms). - * Default: 100 - * - * @param integer $milliseconds - * @return void - * @access public - */ - function setReceivedelay($milliseconds) - { - if (is_integer($milliseconds) && $milliseconds >= 100) { - $this->_receivedelay = $milliseconds; - } else { - $this->_receivedelay = 100; - } - } - - /** - * Sets the delay for sending data to the IRC server. - * - * Sets the delaytime between messages that are sent, because IRC servers doesn't like floods. - * This will avoid sending your messages too fast to the IRC server. - * Default: 250 - * - * @param integer $milliseconds - * @return void - * @access public - */ - function setSenddelay($milliseconds) - { - if (is_integer($milliseconds)) { - $this->_senddelay = $milliseconds; - } else { - $this->_senddelay = 250; - } - } - - /** - * Enables/disables autoreconnecting. - * - * @param boolean $boolean - * @return void - * @access public - */ - function setAutoReconnect($boolean) - { - if (is_bool($boolean)) { - $this->_autoreconnect = $boolean; - } else { - $this->_autoreconnect = false; - } - } - - /** - * Enables/disables autoretry for connecting to a server. - * - * @param boolean $boolean - * @return void - * @access public - */ - function setAutoRetry($boolean) - { - if (is_bool($boolean)) { - $this->_autoretry = $boolean; - } else { - $this->_autoretry = false; - } - } - - /** - * Sets the receive timeout. - * - * If the timeout occurs, the connection will be reinitialized - * Default: 300 seconds - * - * @param integer $seconds - * @return void - * @access public - */ - function setReceiveTimeout($seconds) - { - if (is_integer($seconds)) { - $this->_rxtimeout = $seconds; - } else { - $this->_rxtimeout = 300; - } - } - - /** - * Sets the transmit timeout. - * - * If the timeout occurs, the connection will be reinitialized - * Default: 300 seconds - * - * @param integer $seconds - * @return void - * @access public - */ - function setTransmitTimeout($seconds) - { - if (is_integer($seconds)) { - $this->_txtimeout = $seconds; - } else { - $this->_txtimeout = 300; - } - } - - /** - * Starts the benchmark (sets the counters). - * - * @return void - * @access public - */ - function startBenchmark() - { - $this->_benchmark_starttime = $this->_microint(); - $this->log(SMARTIRC_DEBUG_NOTICE, 'benchmark started', __FILE__, __LINE__); - } - - /** - * Stops the benchmark and displays the result. - * - * @return void - * @access public - */ - function stopBenchmark() - { - $this->_benchmark_stoptime = $this->_microint(); - $this->log(SMARTIRC_DEBUG_NOTICE, 'benchmark stopped', __FILE__, __LINE__); - - if ($this->_benchmark) { - $this->showBenchmark(); - } - } - - /** - * Shows the benchmark result. - * - * @return void - * @access public - */ - function showBenchmark() - { - $this->log(SMARTIRC_DEBUG_NOTICE, 'benchmark time: '.((float)$this->_benchmark_stoptime-(float)$this->_benchmark_starttime), __FILE__, __LINE__); - } - - /** - * Adds an entry to the log. - * - * Adds an entry to the log with Linux style log format. - * Possible $level constants (can also be combined with "|"s) - * SMARTIRC_DEBUG_NONE - * SMARTIRC_DEBUG_NOTICE - * SMARTIRC_DEBUG_CONNECTION - * SMARTIRC_DEBUG_SOCKET - * SMARTIRC_DEBUG_IRCMESSAGES - * SMARTIRC_DEBUG_MESSAGETYPES - * SMARTIRC_DEBUG_ACTIONHANDLER - * SMARTIRC_DEBUG_TIMEHANDLER - * SMARTIRC_DEBUG_MESSAGEHANDLER - * SMARTIRC_DEBUG_CHANNELSYNCING - * SMARTIRC_DEBUG_MODULES - * SMARTIRC_DEBUG_USERSYNCING - * SMARTIRC_DEBUG_ALL - * - * @see SMARTIRC_DEBUG_NOTICE - * @param integer $level bit constants (SMARTIRC_DEBUG_*) - * @param string $entry the new log entry - * @return void - * @access public - */ - function log($level, $entry, $file = null, $line = null) - { - // prechecks - if (!(is_integer($level)) || - !($level & SMARTIRC_DEBUG_ALL)) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: invalid log level passed to log() ('.$level.')', __FILE__, __LINE__); - return; - } - - if (!($level & $this->_debug) || - ($this->_logdestination == SMARTIRC_NONE)) { - return; - } - - if (substr($entry, -1) != "\n") { - $entry .= "\n"; - } - - if ($file !== null && - $line !== null) { - $file = basename($file); - $entry = $file.'('.$line.') '.$entry; - } else { - $entry = 'unknown(0) '.$entry; - } - - $formatedentry = date('M d H:i:s ').$entry; - switch ($this->_logdestination) { - case SMARTIRC_STDOUT: - echo $formatedentry; - flush(); - break; - case SMARTIRC_BROWSEROUT: - echo '
'.htmlentities($formatedentry).'
'; - break; - case SMARTIRC_FILE: - if (!is_resource($this->_logfilefp)) { - if ($this->_logfilefp === null) { - // we reconncted and don't want to destroy the old log entries - $this->_logfilefp = @fopen($this->_logfile,'a'); - } else { - $this->_logfilefp = @fopen($this->_logfile,'w'); - } - } - @fwrite($this->_logfilefp, $formatedentry); - fflush($this->_logfilefp); - break; - case SMARTIRC_SYSLOG: - define_syslog_variables(); - if (!is_int($this->_logfilefp)) { - $this->_logfilefp = openlog('Net_SmartIRC', LOG_NDELAY, LOG_DAEMON); - } - syslog(LOG_INFO, $entry); - break; - } - } - - /** - * Returns the full motd. - * - * @return array - * @access public - */ - function getMotd() - { - return $this->_motd; - } - - /** - * Returns the usermode. - * - * @return string - * @access public - */ - function getUsermode() - { - return $this->_usermode; - } - - /** - * Creates the sockets and connects to the IRC server on the given port. - * - * @param string $address - * @param integer $port - * @return void - * @access public - */ - function connect($address, $port) - { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connecting', __FILE__, __LINE__); - $this->_address = $address; - $this->_port = $port; - - if ($this->_usesockets == true) { - $this->log(SMARTIRC_DEBUG_SOCKET, 'DEBUG_SOCKET: using real sockets', __FILE__, __LINE__); - $this->_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); - $result = @socket_connect($this->_socket, $this->_address, $this->_port); - } else { - $this->log(SMARTIRC_DEBUG_SOCKET, 'DEBUG_SOCKET: using fsockets', __FILE__, __LINE__); - $result = @fsockopen($this->_address, $this->_port, $errno, $errstr); - } - - if ($result === false) { - if ($this->_usesockets == true) { - $error = socket_strerror(socket_last_error($this->_socket)); - } else { - $error = $errstr.' ('.$errno.')'; - } - - $error_msg = 'couldn\'t connect to "'.$address.'" reason: "'.$error.'"'; - $this->log(SMARTIRC_DEBUG_NOTICE, 'DEBUG_NOTICE: '.$error_msg, __FILE__, __LINE__); - // TODO! muss return wert sein - $this->throwError($error_msg); - - // doesn't work somehow.... I only want to retry 4 times! no endless loop (causes segfault) - static $tries = 0; - if ($this->_autoretry == true && $tries < 5) { - $this->reconnect(); - $tries++; - } else { - die(); - } - } else { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connected', __FILE__, __LINE__); - - if ($this->_usesockets != true) { - $this->_socket = $result; - $this->log(SMARTIRC_DEBUG_SOCKET, 'DEBUG_SOCKET: activating nonblocking fsocket mode', __FILE__, __LINE__); - socket_set_blocking($this->_socket, false); - } - } - - $this->_lastrx = time(); - $this->_lasttx = $this->_lastrx; - $this->_updatestate(); - - if ($result !== false) { - return true; - } else { - return false; - } - } - - /** - * Disconnects from the IRC server nicely with a QUIT or just destroys the socket. - * - * Disconnects from the IRC server in the given quickness mode. - * $quickdisconnect: - * true, just close the socket - * false, send QUIT and wait {@link $_disconnectime $_disconnectime} before closing the socket - * - * @param boolean $quickdisconnect default: false - * @return boolean - * @access public - */ - function disconnect($quickdisconnect = false) - { - if ($this->_state() == SMARTIRC_STATE_CONNECTED) { - if ($quickdisconnect == false) { - $this->_send('QUIT', SMARTIRC_CRITICAL); - usleep($this->_disconnecttime*1000); - } - - if ($this->_usesockets == true) { - @socket_shutdown($this->_socket); - @socket_close($this->_socket); - } else { - fclose($this->_socket); - } - - $this->_updatestate(); - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: disconnected', __FILE__, __LINE__); - } else { - return false; - } - - if ($this->_channelsyncing == true) { - // let's clean our channel array - $this->_channels = array(); - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: cleaned channel array', __FILE__, __LINE__); - } - - if ($this->_logdestination == SMARTIRC_FILE) { - fclose($this->_logfilefp); - $this->_logfilefp = null; - } else if ($this->_logdestination == SMARTIRC_SYSLOG) { - closelog(); - } - - return true; - } - - /** - * Reconnects to the IRC server with the same login info, - * it also rejoins the channels - * - * @return void - * @access public - */ - function reconnect() - { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: reconnecting...', __FILE__, __LINE__); - - // remember in which channels we are joined - $channels = array(); - foreach ($this->_channels as $value) { - if (empty($value->key)) { - $channels[] = array('name' => $value->name); - } else { - $channels[] = array('name' => $value->name, 'key' => $value->key); - } - } - - $this->disconnect(true); - $this->connect($this->_address, $this->_port); - $this->login($this->_nick, $this->_realname, $this->_usermode, $this->_username, $this->_password); - - // rejoin the channels - foreach ($channels as $value) { - if (isset($value['key'])) { - $this->join($value['name'], $value['key']); - } else { - $this->join($value['name']); - } - } - } - - /** - * login and register nickname on the IRC network - * - * Registers the nickname and user information on the IRC network. - * - * @param string $nick - * @param string $realname - * @param integer $usermode - * @param string $username - * @param string $password - * @return void - * @access public - */ - function login($nick, $realname, $usermode = 0, $username = null, $password = null) - { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: logging in', __FILE__, __LINE__); - - $this->_nick = str_replace(' ', '', $nick); - $this->_realname = $realname; - - if ($username !== null) { - $this->_username = str_replace(' ', '', $username); - } else { - $this->_username = str_replace(' ', '', exec('whoami')); - } - - if ($password !== null) { - $this->_password = $password; - $this->_send('PASS '.$this->_password, SMARTIRC_CRITICAL); - } - - if (!is_numeric($usermode)) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'DEBUG_NOTICE: login() usermode ('.$usermode.') is not valid, will use 0 instead', __FILE__, __LINE__); - $usermode = 0; - } - - $this->_send('NICK '.$this->_nick, SMARTIRC_CRITICAL); - $this->_send('USER '.$this->_username.' '.$usermode.' '.SMARTIRC_UNUSED.' :'.$this->_realname, SMARTIRC_CRITICAL); - } - - // - - /** - * checks if we or the given user is joined to the specified channel and returns the result - * ChannelSyncing is required for this. - * - * @see setChannelSyncing - * @param string $channel - * @param string $nickname - * @return boolean - * @access public - */ - function isJoined($channel, $nickname = null) - { - if ($this->_channelsyncing != true) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isJoined() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); - return false; - } - - if ($nickname === null) { - $nickname = $this->_nick; - } - - if (isset($this->_channels[strtolower($channel)]->users[strtolower($nickname)])) { - return true; - } - - return false; - } - - /** - * Checks if we or the given user is opped on the specified channel and returns the result. - * ChannelSyncing is required for this. - * - * @see setChannelSyncing - * @param string $channel - * @param string $nickname - * @return boolean - * @access public - */ - function isOpped($channel, $nickname = null) - { - if ($this->_channelsyncing != true) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isOpped() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); - return false; - } - - if ($nickname === null) { - $nickname = $this->_nick; - } - - if ($this->isJoined($channel, $nickname)) { - if ($this->_channels[strtolower($channel)]->users[strtolower($nickname)]->op) { - return true; - } - } - - return false; - } - - /** - * Checks if we or the given user is voiced on the specified channel and returns the result. - * ChannelSyncing is required for this. - * - * @see setChannelSyncing - * @param string $channel - * @param string $nickname - * @return boolean - * @access public - */ - function isVoiced($channel, $nickname = null) - { - if ($this->_channelsyncing != true) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isVoiced() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); - return false; - } - - if ($nickname === null) { - $nickname = $this->_nick; - } - - if ($this->isJoined($channel, $nickname)) { - if ($this->_channels[strtolower($channel)]->users[strtolower($nickname)]->voice) { - return true; - } - } - - return false; - } - - /** - * Checks if the hostmask is on the specified channel banned and returns the result. - * ChannelSyncing is required for this. - * - * @see setChannelSyncing - * @param string $channel - * @param string $hostmask - * @return boolean - * @access public - */ - function isBanned($channel, $hostmask) - { - if ($this->_channelsyncing != true) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isBanned() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); - return false; - } - - if ($this->isJoined($channel)) { - $result = array_search($hostmask, $this->_channels[strtolower($channel)]->bans); - - if ($result !== false) { - return true; - } - } - - return false; - } - - /** - * goes into receive mode - * - * Goes into receive and idle mode. Only call this if you want to "spawn" the bot. - * No further lines of PHP code will be processed after this call, only the bot methods! - * - * @return boolean - * @access public - */ - function listen() - { - if ($this->_state() == SMARTIRC_STATE_CONNECTED) { - $this->_rawreceive(); - return true; - } else { - return false; - } - } - - /** - * waits for a special message type and puts the answer in $result - * - * Creates a special actionhandler for that given TYPE and returns the answer. - * This will only receive the requested type, immediately quit and disconnect from the IRC server. - * Made for showing IRC statistics on your homepage, or other IRC related information. - * - * @param integer $messagetype see in the documentation 'Message Types' - * @return array answer from the IRC server for this $messagetype - * @access public - */ - function listenFor($messagetype) - { - $listenfor = &new Net_SmartIRC_listenfor(); - $this->registerActionhandler($messagetype, '.*', $listenfor, 'handler'); - $this->listen(); - $result = $listenfor->result; - - if (isset($listenfor)) { - unset($listenfor); - } - - return $result; - } - - /** - * waits for a special message type and puts the answer in $result - * - * Creates a special actionhandler for that given TYPE and returns the answer. - * This will only receive the requested type, immediately quit and disconnect from the IRC server. - * Made for showing IRC statistics on your homepage, or other IRC related information. - * This special version of listenFor() stores the whole ircdata object, not just the message! - * - * @param integer $messagetype see in the documentation 'Message Types' - * @return array answer from the IRC server for this $messagetype - * @access public - */ - function objListenFor($messagetype) - { - $objlistenfor = &new Net_SmartIRC_objListenFor(); - $this->registerActionhandler($messagetype, '.*', $objlistenfor, 'handler'); - $this->listen(); - $result = $objlistenfor->result; - - if (isset($objlistenfor)) { - unset($objlistenfor); - } - - return $result; - } - - /** - * registers a new actionhandler and returns the assigned id - * - * Registers an actionhandler in Net_SmartIRC for calling it later. - * The actionhandler id is needed for unregistering the actionhandler. - * - * @see example.php - * @param integer $handlertype bits constants, see in this documentation Message Types - * @param string $regexhandler the message that has to be in the IRC message in regex syntax - * @param object $object a reference to the objects of the method - * @param string $methodname the methodname that will be called when the handler happens - * @return integer assigned actionhandler id - * @access public - */ - function registerActionhandler($handlertype, $regexhandler, &$object, $methodname) - { - // precheck - if (!$this->_isValidType($handlertype)) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: passed invalid handlertype to registerActionhandler()', __FILE__, __LINE__); - return false; - } - - $id = $this->_actionhandlerid++; - $newactionhandler = &new Net_SmartIRC_actionhandler(); - - $newactionhandler->id = $id; - $newactionhandler->type = $handlertype; - $newactionhandler->message = $regexhandler; - $newactionhandler->object = &$object; - $newactionhandler->method = $methodname; - - $this->_actionhandler[] = &$newactionhandler; - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: actionhandler('.$id.') registered', __FILE__, __LINE__); - return $id; - } - - /** - * unregisters an existing actionhandler - * - * @param integer $handlertype - * @param string $regexhandler - * @param object $object - * @param string $methodname - * @return boolean - * @access public - */ - function unregisterActionhandler($handlertype, $regexhandler, &$object, $methodname) - { - // precheck - if (!$this->_isValidType($handlertype)) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: passed invalid handlertype to unregisterActionhandler()', __FILE__, __LINE__); - return false; - } - - $handler = &$this->_actionhandler; - $handlercount = count($handler); - - for ($i = 0; $i < $handlercount; $i++) { - $handlerobject = &$handler[$i]; - - if ($handlerobject->type == $handlertype && - $handlerobject->message == $regexhandler && - $handlerobject->method == $methodname) { - - $id = $handlerobject->id; - - if (isset($this->_actionhandler[$i])) { - unset($this->_actionhandler[$i]); - } - - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: actionhandler('.$id.') unregistered', __FILE__, __LINE__); - $this->_reorderactionhandler(); - return true; - } - } - - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: could not find actionhandler type: "'.$handlertype.'" message: "'.$regexhandler.'" method: "'.$methodname.'" from object "'.get_class($object).'" _not_ unregistered', __FILE__, __LINE__); - return false; - } - - /** - * unregisters an existing actionhandler via the id - * - * @param integer $id - * @return boolean - * @access public - */ - function unregisterActionid($id) - { - $handler = &$this->_actionhandler; - $handlercount = count($handler); - for ($i = 0; $i < $handlercount; $i++) { - $handlerobject = &$handler[$i]; - - if ($handlerobject->id == $id) { - if (isset($this->_actionhandler[$i])) { - unset($this->_actionhandler[$i]); - } - - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: actionhandler('.$id.') unregistered', __FILE__, __LINE__); - $this->_reorderactionhandler(); - return true; - } - } - - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: could not find actionhandler id: '.$id.' _not_ unregistered', __FILE__, __LINE__); - return false; - } - - /** - * registers a timehandler and returns the assigned id - * - * Registers a timehandler in Net_SmartIRC, which will be called in the specified interval. - * The timehandler id is needed for unregistering the timehandler. - * - * @see example7.php - * @param integer $interval interval time in milliseconds - * @param object $object a reference to the objects of the method - * @param string $methodname the methodname that will be called when the handler happens - * @return integer assigned timehandler id - * @access public - */ - function registerTimehandler($interval, &$object, $methodname) - { - $id = $this->_timehandlerid++; - $newtimehandler = &new Net_SmartIRC_timehandler(); - - $newtimehandler->id = $id; - $newtimehandler->interval = $interval; - $newtimehandler->object = &$object; - $newtimehandler->method = $methodname; - $newtimehandler->lastmicrotimestamp = $this->_microint(); - - $this->_timehandler[] = &$newtimehandler; - $this->log(SMARTIRC_DEBUG_TIMEHANDLER, 'DEBUG_TIMEHANDLER: timehandler('.$id.') registered', __FILE__, __LINE__); - - if (($interval < $this->_mintimer) || ($this->_mintimer == false)) { - $this->_mintimer = $interval; - } - - return $id; - } - - /** - * unregisters an existing timehandler via the id - * - * @see example7.php - * @param integer $id - * @return boolean - * @access public - */ - function unregisterTimeid($id) - { - $handler = &$this->_timehandler; - $handlercount = count($handler); - for ($i = 0; $i < $handlercount; $i++) { - $handlerobject = &$handler[$i]; - - if ($handlerobject->id == $id) { - if (isset($this->_timehandler[$i])) { - unset($this->_timehandler[$i]); - } - - $this->log(SMARTIRC_DEBUG_TIMEHANDLER, 'DEBUG_TIMEHANDLER: timehandler('.$id.') unregistered', __FILE__, __LINE__); - $this->_reordertimehandler(); - $this->_updatemintimer(); - return true; - } - } - - $this->log(SMARTIRC_DEBUG_TIMEHANDLER, 'DEBUG_TIMEHANDLER: could not find timehandler id: '.$id.' _not_ unregistered', __FILE__, __LINE__); - return false; - } - - // - /** - * changes a already used nickname to a new nickname plus 3 random digits - * - * @return void - * @access private - */ - function _nicknameinuse() - { - $newnickname = substr($this->_nick, 0, 5).rand(0, 999); - $this->changeNick($newnickname, SMARTIRC_CRITICAL); - } - - /** - * sends an IRC message - * - * Adds a message to the messagequeue, with the optional priority. - * $priority: - * SMARTIRC_CRITICAL - * SMARTIRC_HIGH - * SMARTIRC_MEDIUM - * SMARTIRC_LOW - * - * @param string $data - * @param integer $priority must be one of the priority constants - * @return boolean - * @access private - */ - function _send($data, $priority = SMARTIRC_MEDIUM) - { - switch ($priority) { - case SMARTIRC_CRITICAL: - $this->_rawsend($data); - return true; - break; - case (SMARTIRC_HIGH|| - SMARTIRC_MEDIUM|| - SMARTIRC_LOW): - $this->_messagebuffer[$priority][] = $data; - return true; - break; - default: - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: message ('.$data.') with an invalid priority passed ('.$priority.'), message is ignored!', __FILE__, __LINE__); - return false; - } - } - - /** - * checks the buffer if there are messages to send - * - * @return void - * @access private - */ - function _checkbuffer() - { - if (!$this->_loggedin) { - return; - } - - static $highsent = 0; - static $lastmicrotimestamp = 0; - - if ($lastmicrotimestamp == 0) { - $lastmicrotimestamp = $this->_microint(); - } - - $highcount = count($this->_messagebuffer[SMARTIRC_HIGH]); - $mediumcount = count($this->_messagebuffer[SMARTIRC_MEDIUM]); - $lowcount = count($this->_messagebuffer[SMARTIRC_LOW]); - $this->_messagebuffersize = $highcount+$mediumcount+$lowcount; - - // don't send them too fast - if ($this->_microint() >= ($lastmicrotimestamp+($this->_senddelay/1000))) { - if ($highcount > 0 && $highsent <= 2) { - $this->_rawsend(array_shift($this->_messagebuffer[SMARTIRC_HIGH])); - $lastmicrotimestamp = $this->_microint(); - $highsent++; - } else if ($mediumcount > 0) { - $this->_rawsend(array_shift($this->_messagebuffer[SMARTIRC_MEDIUM])); - $lastmicrotimestamp = $this->_microint(); - $highsent = 0; - } else if ($lowcount > 0) { - $this->_rawsend(array_shift($this->_messagebuffer[SMARTIRC_LOW])); - $lastmicrotimestamp = $this->_microint(); - } - } - } - - /** - * Checks the running timers and calls the registered timehandler, - * when the interval is reached. - * - * @return void - * @access private - */ - function _checktimer() - { - if (!$this->_loggedin) { - return; - } - - // has to be count() because the array may change during the loop! - for ($i = 0; $i < count($this->_timehandler); $i++) { - $handlerobject = &$this->_timehandler[$i]; - $microtimestamp = $this->_microint(); - if ($microtimestamp >= ($handlerobject->lastmicrotimestamp+($handlerobject->interval/1000))) { - $methodobject = &$handlerobject->object; - $method = $handlerobject->method; - $handlerobject->lastmicrotimestamp = $microtimestamp; - - if (@method_exists($methodobject, $method)) { - $this->log(SMARTIRC_DEBUG_TIMEHANDLER, 'DEBUG_TIMEHANDLER: calling method "'.get_class($methodobject).'->'.$method.'"', __FILE__, __LINE__); - $methodobject->$method($this); - } - } - } - } - - /** - * Checks if a receive or transmit timeout occured and reconnects if configured - * - * @return void - * @access private - */ - function _checktimeout() - { - if ($this->_autoreconnect == true) { - $timestamp = time(); - if ($this->_lastrx < ($timestamp - $this->_rxtimeout)) { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: receive timeout detected, doing reconnect...', __FILE__, __LINE__); - $this->reconnect(); - } else if ($this->_lasttx < ($timestamp - $this->_txtimeout)) { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: transmit timeout detected, doing reconnect...', __FILE__, __LINE__); - $this->reconnect(); - } - } - } - - /** - * sends a raw message to the IRC server (don't use this!!) - * - * Use message() or _send() instead. - * - * @param string $data - * @return boolean - * @access private - */ - function _rawsend($data) - { - if ($this->_state() == SMARTIRC_STATE_CONNECTED) { - $this->log(SMARTIRC_DEBUG_IRCMESSAGES, 'DEBUG_IRCMESSAGES: sent: "'.$data.'"', __FILE__, __LINE__); - - if ($this->_usesockets == true) { - $result = @socket_write($this->_socket, $data.SMARTIRC_CRLF); - } else { - $result = @fwrite($this->_socket, $data.SMARTIRC_CRLF); - } - - - if ($result === false) { - return false; - } else { - $this->_lasttx = time(); - return true; - } - } else { - return false; - } - } - - /** - * goes into main idle loop for waiting messages from the IRC server - * - * @return void - * @access private - */ - function _rawreceive() - { - $lastpart = ''; - $rawdataar = array(); - - while ($this->_state() == SMARTIRC_STATE_CONNECTED) { - $this->_checkbuffer(); - - $timeout = $this->_selecttimeout(); - if ($this->_usesockets == true) { - $sread = array($this->_socket); - $result = @socket_select($sread, $w = null, $e = null, 0, $timeout*1000); - - if ($result == 1) { - // the socket got data to read - $rawdata = @socket_read($this->_socket, 10240); - } else if ($result === false) { - // panic! panic! something went wrong! - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: socket_select() returned false, something went wrong! Reason: '.socket_strerror(socket_last_error()), __FILE__, __LINE__); - exit; - } else { - // no data - $rawdata = null; - } - } else { - usleep($this->_receivedelay*1000); - $rawdata = @fread($this->_socket, 10240); - } - - $this->_checktimer(); - $this->_checktimeout(); - - if ($rawdata !== null && !empty($rawdata)) { - $this->_lastrx = time(); - $rawdata = str_replace("\r", '', $rawdata); - $rawdata = $lastpart.$rawdata; - - $lastpart = substr($rawdata, strrpos($rawdata ,"\n")+1); - $rawdata = substr($rawdata, 0, strrpos($rawdata ,"\n")); - $rawdataar = explode("\n", $rawdata); - } - - // loop through our received messages - while (count($rawdataar) > 0) { - $rawline = array_shift($rawdataar); - $validmessage = false; - - $this->log(SMARTIRC_DEBUG_IRCMESSAGES, 'DEBUG_IRCMESSAGES: received: "'.$rawline.'"', __FILE__, __LINE__); - - // building our data packet - $ircdata = &new Net_SmartIRC_data(); - $ircdata->rawmessage = $rawline; - $lineex = explode(' ', $rawline); - $ircdata->rawmessageex = $lineex; - $messagecode = $lineex[0]; - - if (substr($rawline, 0, 1) == ':') { - $validmessage = true; - $line = substr($rawline, 1); - $lineex = explode(' ', $line); - - // conform to RFC 2812 - $from = $lineex[0]; - $messagecode = $lineex[1]; - $exclamationpos = strpos($from, '!'); - $atpos = strpos($from, '@'); - $colonpos = strpos($line, ' :'); - if ($colonpos !== false) { - // we want the exact position of ":" not beginning from the space - $colonpos += 1; - } - $ircdata->nick = substr($from, 0, $exclamationpos); - $ircdata->ident = substr($from, $exclamationpos+1, ($atpos-$exclamationpos)-1); - $ircdata->host = substr($from, $atpos+1); - $ircdata->type = $this->_gettype($rawline); - $ircdata->from = $from; - if ($colonpos !== false) { - $ircdata->message = substr($line, $colonpos+1); - $ircdata->messageex = explode(' ', $ircdata->message); - } - - if ($ircdata->type & (SMARTIRC_TYPE_CHANNEL| - SMARTIRC_TYPE_ACTION| - SMARTIRC_TYPE_MODECHANGE| - SMARTIRC_TYPE_KICK| - SMARTIRC_TYPE_PART| - SMARTIRC_TYPE_JOIN)) { - $ircdata->channel = $lineex[2]; - } else if ($ircdata->type & (SMARTIRC_TYPE_WHO| - SMARTIRC_TYPE_BANLIST| - SMARTIRC_TYPE_TOPIC| - SMARTIRC_TYPE_CHANNELMODE)) { - $ircdata->channel = $lineex[3]; - } else if ($ircdata->type & SMARTIRC_TYPE_NAME) { - $ircdata->channel = $lineex[4]; - } - - if ($ircdata->channel !== null) { - if (substr($ircdata->channel, 0, 1) == ':') { - $ircdata->channel = substr($ircdata->channel, 1); - } - } - - $this->log(SMARTIRC_DEBUG_MESSAGEPARSER, 'DEBUG_MESSAGEPARSER: ircdata nick: "'.$ircdata->nick. - '" ident: "'.$ircdata->ident. - '" host: "'.$ircdata->host. - '" type: "'.$ircdata->type. - '" from: "'.$ircdata->from. - '" channel: "'.$ircdata->channel. - '" message: "'.$ircdata->message. - '"', __FILE__, __LINE__); - } - - // lets see if we have a messagehandler for it - $this->_handlemessage($messagecode, $ircdata); - - if ($validmessage == true) { - // now the actionhandlers are comming - $this->_handleactionhandler($ircdata); - } - - if (isset($ircdata)) { - unset($ircdata); - } - } - } - } - - /** - * sends the pong for keeping alive - * - * Sends the PONG signal as reply of the PING from the IRC server. - * - * @param string $data - * @return void - * @access private - */ - function _pong($data) - { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: Ping? Pong!', __FILE__, __LINE__); - $this->_send('PONG '.$data, SMARTIRC_CRITICAL); - } - - /** - * returns the calculated selecttimeout value - * - * @return integer selecttimeout in microseconds - * @access private - */ - function _selecttimeout() { - if ($this->_messagebuffersize == 0) { - $this->_selecttimeout = null; - - if ($this->_mintimer != false) { - $this->_calculateselecttimeout($this->_mintimer); - } - - if ($this->_autoreconnect == true) { - $this->_calculateselecttimeout($this->_rxtimeout*1000); - } - - $this->_calculateselecttimeout($this->_maxtimer); - return $this->_selecttimeout; - } else { - return $this->_senddelay; - } - } - - /** - * calculates the selecttimeout value - * - * @return void - * @access private - */ - function _calculateselecttimeout($microseconds) - { - if (($this->_selecttimeout > $microseconds) || $this->_selecttimeout === null) { - $this->_selecttimeout = $microseconds; - } - } - - /** - * updates _mintimer to the smallest timer interval - * - * @return void - * @access private - */ - function _updatemintimer() - { - $timerarray = array(); - foreach ($this->_timehandler as $values) { - $timerarray[] = $values->interval; - } - - $result = array_multisort($timerarray, SORT_NUMERIC, SORT_ASC); - if ($result == true && isset($timerarray[0])) { - $this->_mintimer = $timerarray[0]; - } else { - $this->_mintimer = false; - } - } - - /** - * reorders the actionhandler array, needed after removing one - * - * @return void - * @access private - */ - function _reorderactionhandler() - { - $orderedactionhandler = array(); - foreach ($this->_actionhandler as $value) { - $orderedactionhandler[] = $value; - } - $this->_actionhandler = &$orderedactionhandler; - } - - /** - * reorders the timehandler array, needed after removing one - * - * @return void - * @access private - */ - function _reordertimehandler() - { - $orderedtimehandler = array(); - foreach ($this->_timehandler as $value) { - $orderedtimehandler[] = $value; - } - $this->_timehandler = &$orderedtimehandler; - } - - /** - * reorders the modules array, needed after removing one - * - * @return void - * @access private - */ - function _reordermodules() - { - $orderedmodules = array(); - foreach ($this->_modules as $value) { - $orderedmodules[] = $value; - } - $this->_modules = &$orderedmodules; - } - - /** - * determines the messagetype of $line - * - * Analyses the type of an IRC message and returns the type. - * - * @param string $line - * @return integer SMARTIRC_TYPE_* constant - * @access private - */ - function _gettype($line) - { - if (preg_match('/^:[^ ]+? [0-9]{3} .+$/', $line) == 1) { - $lineex = explode(' ', $line); - $code = $lineex[1]; - - switch ($code) { - case SMARTIRC_RPL_WELCOME: - case SMARTIRC_RPL_YOURHOST: - case SMARTIRC_RPL_CREATED: - case SMARTIRC_RPL_MYINFO: - case SMARTIRC_RPL_BOUNCE: - return SMARTIRC_TYPE_LOGIN; - case SMARTIRC_RPL_LUSERCLIENT: - case SMARTIRC_RPL_LUSEROP: - case SMARTIRC_RPL_LUSERUNKNOWN: - case SMARTIRC_RPL_LUSERME: - case SMARTIRC_RPL_LUSERCHANNELS: - return SMARTIRC_TYPE_INFO; - case SMARTIRC_RPL_MOTDSTART: - case SMARTIRC_RPL_MOTD: - case SMARTIRC_RPL_ENDOFMOTD: - return SMARTIRC_TYPE_MOTD; - case SMARTIRC_RPL_NAMREPLY: - case SMARTIRC_RPL_ENDOFNAMES: - return SMARTIRC_TYPE_NAME; - case SMARTIRC_RPL_WHOREPLY: - case SMARTIRC_RPL_ENDOFWHO: - return SMARTIRC_TYPE_WHO; - case SMARTIRC_RPL_LISTSTART: - return SMARTIRC_TYPE_NONRELEVANT; - case SMARTIRC_RPL_LIST: - case SMARTIRC_RPL_LISTEND: - return SMARTIRC_TYPE_LIST; - case SMARTIRC_RPL_BANLIST: - case SMARTIRC_RPL_ENDOFBANLIST: - return SMARTIRC_TYPE_BANLIST; - case SMARTIRC_RPL_TOPIC: - return SMARTIRC_TYPE_TOPIC; - case SMARTIRC_RPL_WHOISUSER: - case SMARTIRC_RPL_WHOISSERVER: - case SMARTIRC_RPL_WHOISOPERATOR: - case SMARTIRC_RPL_WHOISIDLE: - case SMARTIRC_RPL_ENDOFWHOIS: - case SMARTIRC_RPL_WHOISCHANNELS: - return SMARTIRC_TYPE_WHOIS; - case SMARTIRC_RPL_WHOWASUSER: - case SMARTIRC_RPL_ENDOFWHOWAS: - return SMARTIRC_TYPE_WHOWAS; - case SMARTIRC_RPL_UMODEIS: - return SMARTIRC_TYPE_USERMODE; - case SMARTIRC_RPL_CHANNELMODEIS: - return SMARTIRC_TYPE_CHANNELMODE; - case SMARTIRC_ERR_NICKNAMEINUSE: - case SMARTIRC_ERR_NOTREGISTERED: - return SMARTIRC_TYPE_ERROR; - default: - $this->log(SMARTIRC_DEBUG_IRCMESSAGES, 'DEBUG_IRCMESSAGES: replycode UNKNOWN ('.$code.'): "'.$line.'"', __FILE__, __LINE__); - } - } - - if (preg_match('/^:.*? PRIVMSG .* :'.chr(1).'ACTION .*'.chr(1).'$/', $line) == 1) { - return SMARTIRC_TYPE_ACTION; - } else if (preg_match('/^:.*? PRIVMSG .* :'.chr(1).'.*'.chr(1).'$/', $line) == 1) { - return SMARTIRC_TYPE_CTCP; - } else if (preg_match('/^:.*? PRIVMSG (\&|\#|\+|\!).* :.*$/', $line) == 1) { - return SMARTIRC_TYPE_CHANNEL; - } else if (preg_match('/^:.*? PRIVMSG .*:.*$/', $line) == 1) { - return SMARTIRC_TYPE_QUERY; - } else if (preg_match('/^:.*? NOTICE .* :.*$/', $line) == 1) { - return SMARTIRC_TYPE_NOTICE; - } else if (preg_match('/^:.*? INVITE .* .*$/', $line) == 1) { - return SMARTIRC_TYPE_INVITE; - } else if (preg_match('/^:.*? JOIN .*$/', $line) == 1) { - return SMARTIRC_TYPE_JOIN; - } else if (preg_match('/^:.*? TOPIC .* :.*$/', $line) == 1) { - return SMARTIRC_TYPE_TOPICCHANGE; - } else if (preg_match('/^:.*? NICK .*$/', $line) == 1) { - return SMARTIRC_TYPE_NICKCHANGE; - } else if (preg_match('/^:.*? KICK .* .*$/', $line) == 1) { - return SMARTIRC_TYPE_KICK; - } else if (preg_match('/^:.*? PART .*$/', $line) == 1) { - return SMARTIRC_TYPE_PART; - } else if (preg_match('/^:.*? MODE .* .*$/', $line) == 1) { - return SMARTIRC_TYPE_MODECHANGE; - } else if (preg_match('/^:.*? QUIT :.*$/', $line) == 1) { - return SMARTIRC_TYPE_QUIT; - } else { - $this->log(SMARTIRC_DEBUG_MESSAGETYPES, 'DEBUG_MESSAGETYPES: SMARTIRC_TYPE_UNKNOWN!: "'.$line.'"', __FILE__, __LINE__); - return SMARTIRC_TYPE_UNKNOWN; - } - } - - /** - * updates the current connection state - * - * @return boolean - * @access private - */ - function _updatestate() - { - $rtype = get_resource_type($this->_socket); - if ((is_resource($this->_socket)) && - ($this->_socket !== false) && - ($rtype == 'socket' || $rtype == 'Socket' || $rtype == 'stream')) { - - $this->_state = true; - return true; - } else { - $this->_state = false; - $this->_loggedin = false; - return false; - } - } - - /** - * returns the current connection state - * - * @return integer SMARTIRC_STATE_CONNECTED or SMARTIRC_STATE_DISCONNECTED - * @access private - */ - function _state() - { - $result = $this->_updatestate(); - - if ($result == true) { - return SMARTIRC_STATE_CONNECTED; - } else { - return SMARTIRC_STATE_DISCONNECTED; - } - } - - /** - * tries to find a messagehandler for the received message ($ircdata) and calls it - * - * @param string $messagecode - * @param object $ircdata - * @return void - * @access private - */ - function _handlemessage($messagecode, &$ircdata) - { - $found = false; - - if (is_numeric($messagecode)) { - if (!array_key_exists($messagecode, $this->nreplycodes)) { - $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: ignoring unreconzied messagecode! "'.$messagecode.'"', __FILE__, __LINE__); - $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: this IRC server ('.$this->_address.') doesn\'t conform to the RFC 2812!', __FILE__, __LINE__); - return; - } - - $methodname = 'event_'.strtolower($this->nreplycodes[$messagecode]); - $_methodname = '_'.$methodname; - $_codetype = 'by numeric'; - } else if (is_string($messagecode)) { // its not numericcode so already a name/string - $methodname = 'event_'.strtolower($messagecode); - $_methodname = '_'.$methodname; - $_codetype = 'by string'; - } - - // if exists call internal method for the handling - if (@method_exists($this, $_methodname)) { - $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: calling internal method "'.get_class($this).'->'.$_methodname.'" ('.$_codetype.')', __FILE__, __LINE__); - $this->$_methodname($ircdata); - $found = true; - } - - // if exist, call user defined method for the handling - if (@method_exists($this, $methodname)) { - $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: calling user defined method "'.get_class($this).'->'.$methodname.'" ('.$_codetype.')', __FILE__, __LINE__); - $this->$methodname($ircdata); - $found = true; - } - - if ($found == false) { - $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: no method found for "'.$messagecode.'" ('.$methodname.')', __FILE__, __LINE__); - } - } - - /** - * tries to find a actionhandler for the received message ($ircdata) and calls it - * - * @param object $ircdata - * @return void - * @access private - */ - function _handleactionhandler(&$ircdata) - { - $handler = &$this->_actionhandler; - $handlercount = count($handler); - for ($i = 0; $i < $handlercount; $i++) { - $handlerobject = &$handler[$i]; - - if (substr($handlerobject->message, 0, 1) == '/') { - $regex = $handlerobject->message; - } else { - $regex = '/'.$handlerobject->message.'/'; - } - - if (($handlerobject->type & $ircdata->type) && - (preg_match($regex, $ircdata->message) == 1)) { - - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: actionhandler match found for id: '.$i.' type: '.$ircdata->type.' message: "'.$ircdata->message.'" regex: "'.$regex.'"', __FILE__, __LINE__); - - $methodobject = &$handlerobject->object; - $method = $handlerobject->method; - - if (@method_exists($methodobject, $method)) { - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: calling method "'.get_class($methodobject).'->'.$method.'"', __FILE__, __LINE__); - $methodobject->$method($this, $ircdata); - } else { - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: method doesn\'t exist! "'.get_class($methodobject).'->'.$method.'"', __FILE__, __LINE__); - } - - break; - } - } - } - - /** - * getting current microtime, needed for benchmarks - * - * @return float - * @access private - */ - function _microint() - { - $tmp = microtime(); - $parts = explode(' ', $tmp); - $floattime = (float)$parts[0] + (float)$parts[1]; - return $floattime; - } - - /** - * adds an user to the channelobject or updates his info - * - * @param object $channel - * @param object $newuser - * @return void - * @access private - */ - function _adduser(&$channel, &$newuser) - { - $lowerednick = strtolower($newuser->nick); - if (isset($channel->users[$lowerednick])) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: updating user: '.$newuser->nick.' on channel: '.$channel->name, __FILE__, __LINE__); - - // lets update the existing user - $currentuser = &$channel->users[$lowerednick]; - - if ($newuser->ident !== null) { - $currentuser->ident = $newuser->ident; - } - if ($newuser->host !== null) { - $currentuser->host = $newuser->host; - } - if ($newuser->realname !== null) { - $currentuser->realname = $newuser->realname; - } - if ($newuser->op !== null) { - $currentuser->op = $newuser->op; - } - if ($newuser->voice !== null) { - $currentuser->voice = $newuser->voice; - } - if ($newuser->ircop !== null) { - $currentuser->ircop = $newuser->ircop; - } - if ($newuser->away !== null) { - $currentuser->away = $newuser->away; - } - if ($newuser->server !== null) { - $currentuser->server = $newuser->server; - } - if ($newuser->hopcount !== null) { - $currentuser->hopcount = $newuser->hopcount; - } - } else { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding user: '.$newuser->nick.' to channel: '.$channel->name, __FILE__, __LINE__); - - // he is new just add the reference to him - $channel->users[$lowerednick] = &$newuser; - } - - $user = &$channel->users[$lowerednick]; - if ($user->op) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding op: '.$user->nick.' to channel: '.$channel->name, __FILE__, __LINE__); - $channel->ops[$user->nick] = true; - } - if ($user->voice) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding voice: '.$user->nick.' to channel: '.$channel->name, __FILE__, __LINE__); - $channel->voices[$user->nick] = true; - } - } - - /** - * removes an user from one channel or all if he quits - * - * @param object $ircdata - * @return void - * @access private - */ - function _removeuser(&$ircdata) - { - if ($ircdata->type & (SMARTIRC_TYPE_PART|SMARTIRC_TYPE_QUIT)) { - $nick = $ircdata->nick; - } else if ($ircdata->type & SMARTIRC_TYPE_KICK) { - $nick = $ircdata->rawmessageex[3]; - } else { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: unknown TYPE ('.$ircdata->type.') in _removeuser(), trying default', __FILE__, __LINE__); - $nick = $ircdata->nick; - } - - $lowerednick = strtolower($nick); - - if ($this->_nick == $nick) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: we left channel: '.$ircdata->channel.' destroying...', __FILE__, __LINE__); - unset($this->_channels[strtolower($ircdata->channel)]); - } else { - if ($ircdata->type & SMARTIRC_TYPE_QUIT) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: user '.$nick.' quit, removing him from all channels', __FILE__, __LINE__); - // remove the user from all channels - foreach ($this->_channels as $channelkey => $channelvalue) { - // loop through all channels - $channel = &$this->_channels[$channelkey]; - foreach ($channel->users as $userkey => $uservalue) { - // loop through all user in this channel - - if ($nick == $uservalue->nick) { - // found him - // kill him - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: found him on channel: '.$channel->name.' destroying...', __FILE__, __LINE__); - unset($channel->users[$lowerednick]); - - if (isset($channel->ops[$nick])) { - // die! - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from op list', __FILE__, __LINE__); - unset($channel->ops[$nick]); - } - - if (isset($channel->voices[$nick])) { - // die!! - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from voice list', __FILE__, __LINE__); - unset($channel->voices[$nick]); - } - - // ups this was not DukeNukem 3D - } - } - } - } else { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing user: '.$nick.' from channel: '.$ircdata->channel, __FILE__, __LINE__); - $channel = &$this->_channels[strtolower($ircdata->channel)]; - unset($channel->users[$lowerednick]); - - if (isset($channel->ops[$nick])) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from op list', __FILE__, __LINE__); - unset($channel->ops[$nick]); - } - - if (isset($channel->voices[$nick])) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from voice list', __FILE__, __LINE__); - unset($channel->voices[$nick]); - } - } - } - } - - /** - * @return void - * @access private - */ - function _checkPHPVersion() - { - // doing nothing at the moment - } - - /** - * checks if the passed handlertype is valid - * - * @param integer $handlertype - * @return boolean - * @access private - */ - function _isValidType($handlertype) { - if ($handlertype & SMARTIRC_TYPE_ALL ) { - return true; - } else { - return false; - } - } - - // - - function isError($object) { - return (bool)(is_object($object) && (strtolower(get_class($object)) == 'net_smartirc_error')); - } - - function &throwError($message) { - return new Net_SmartIRC_Error($message); - } -} - -class Net_SmartIRC extends Net_SmartIRC_messagehandler -{ - // empty -} - -/** - * @access public - */ -class Net_SmartIRC_data -{ - /** - * @var string - * @access public - */ - var $from; - - /** - * @var string - * @access public - */ - var $nick; - - /** - * @var string - * @access public - */ - var $ident; - - /** - * @var string - * @access public - */ - var $host; - - /** - * @var string - * @access public - */ - var $channel; - - /** - * @var string - * @access public - */ - var $message; - - /** - * @var array - * @access public - */ - var $messageex = array(); - - /** - * @var integer - * @access public - */ - var $type; - - /** - * @var string - * @access public - */ - var $rawmessage; - - /** - * @var array - * @access public - */ - var $rawmessageex = array(); -} - -/** - * @access public - */ -class Net_SmartIRC_actionhandler -{ - /** - * @var integer - * @access public - */ - var $id; - - /** - * @var integer - * @access public - */ - var $type; - - /** - * @var string - * @access public - */ - var $message; - - /** - * @var object - * @access public - */ - var $object; - - /** - * @var string - * @access public - */ - var $method; -} - -/** - * @access public - */ -class Net_SmartIRC_timehandler -{ - /** - * @var integer - * @access public - */ - var $id; - - /** - * @var integer - * @access public - */ - var $interval; - - /** - * @var integer - * @access public - */ - var $lastmicrotimestamp; - - /** - * @var object - * @access public - */ - var $object; - - /** - * @var string - * @access public - */ - var $method; -} - -/** - * @access public - */ -class Net_SmartIRC_channel -{ - /** - * @var string - * @access public - */ - var $name; - - /** - * @var string - * @access public - */ - var $key; - - /** - * @var array - * @access public - */ - var $users = array(); - - /** - * @var array - * @access public - */ - var $ops = array(); - - /** - * @var array - * @access public - */ - var $voices = array(); - - /** - * @var array - * @access public - */ - var $bans = array(); - - /** - * @var string - * @access public - */ - var $topic; - - /** - * @var string - * @access public - */ - var $mode; -} - -/** - * @access public - */ -class Net_SmartIRC_user -{ - /** - * @var string - * @access public - */ - var $nick; - - /** - * @var string - * @access public - */ - var $ident; - - /** - * @var string - * @access public - */ - var $host; - - /** - * @var string - * @access public - */ - var $realname; - - /** - * @var boolean - * @access public - */ - var $ircop; - - /** - * @var boolean - * @access public - */ - var $away; - - /** - * @var string - * @access public - */ - var $server; - - /** - * @var integer - * @access public - */ - var $hopcount; -} - -/** - * @access public - */ -class Net_SmartIRC_channeluser extends Net_SmartIRC_user -{ - /** - * @var boolean - * @access public - */ - var $op; - - /** - * @var boolean - * @access public - */ - var $voice; -} - -/** - * @access public - */ -class Net_SmartIRC_ircuser extends Net_SmartIRC_user -{ - /** - * @var array - * @access public - */ - var $joinedchannels = array(); -} - -/** - * @access public - */ -class Net_SmartIRC_listenfor -{ - /** - * @var array - * @access public - */ - var $result = array(); - - /** - * stores the received answer into the result array - * - * @param object $irc - * @param object $ircdata - * @return void - */ - function handler(&$irc, &$ircdata) - { - $irc->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: listenfor handler called', __FILE__, __LINE__); - $this->result[] = $ircdata->message; - $irc->disconnect(true); - } -} - -// so we don't break BC! -/** - * @access public - */ -class Net_SmartIRC_objListenFor -{ - /** - * @var array - * @access public - */ - var $result = array(); - - /** - * stores the received answer into the result array - * - * @param object $irc - * @param object $ircdata - * @return void - */ - function handler(&$irc, &$ircdata) - { - $irc->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: objListenFor handler called', __FILE__, __LINE__); - $this->result[] = $ircdata; - $irc->disconnect(true); - } -} - -class Net_SmartIRC_Error -{ - var $error_msg; - - function Net_SmartIRC_Error($message) - { - $this->error_msg = $message; - } - - function getMessage() - { - return $this->error_msg; - } -} -?> \ No newline at end of file diff --git a/tools/IRC_Bot/SmartIRC/defines.php b/tools/IRC_Bot/SmartIRC/defines.php deleted file mode 100644 index c095b13fc..000000000 --- a/tools/IRC_Bot/SmartIRC/defines.php +++ /dev/null @@ -1,234 +0,0 @@ - - * - * Full LGPL License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -// don't change this! unless you know what you do -define('SMARTIRC_CRLF', "\r\n"); -define('SMARTIRC_UNUSED', '*'); -define('SMARTIRC_STDOUT', 0); -define('SMARTIRC_FILE', 1); -define('SMARTIRC_SYSLOG', 2); -define('SMARTIRC_BROWSEROUT', 3); -define('SMARTIRC_NONE', 4); -define('SMARTIRC_LOW', 0); -define('SMARTIRC_MEDIUM', 1); -define('SMARTIRC_HIGH', 2); -define('SMARTIRC_CRITICAL', 3); -define('SMARTIRC_STATE_DISCONNECTED', 0); -define('SMARTIRC_STATE_CONNECTING', 1); -define('SMARTIRC_STATE_CONNECTED', 2); -define('SMARTIRC_DEBUG_NONE', 0); -define('SMARTIRC_DEBUG_NOTICE', 1); -define('SMARTIRC_DEBUG_CONNECTION', 2); -define('SMARTIRC_DEBUG_SOCKET', 4); -define('SMARTIRC_DEBUG_IRCMESSAGES', 8); -define('SMARTIRC_DEBUG_MESSAGETYPES', 16); -define('SMARTIRC_DEBUG_ACTIONHANDLER', 32); -define('SMARTIRC_DEBUG_TIMEHANDLER', 64); -define('SMARTIRC_DEBUG_MESSAGEHANDLER', 128); -define('SMARTIRC_DEBUG_CHANNELSYNCING', 256); -define('SMARTIRC_DEBUG_MODULES', 512); -define('SMARTIRC_DEBUG_USERSYNCING', 1024); -define('SMARTIRC_DEBUG_MESSAGEPARSER', 2048); -define('SMARTIRC_DEBUG_ALL', 4095); -define('SMARTIRC_TYPE_UNKNOWN', 1); -define('SMARTIRC_TYPE_CHANNEL', 2); -define('SMARTIRC_TYPE_QUERY', 4); -define('SMARTIRC_TYPE_CTCP', 8); -define('SMARTIRC_TYPE_NOTICE', 16); -define('SMARTIRC_TYPE_WHO', 32); -define('SMARTIRC_TYPE_JOIN', 64); -define('SMARTIRC_TYPE_INVITE', 128); -define('SMARTIRC_TYPE_ACTION', 256); -define('SMARTIRC_TYPE_TOPICCHANGE', 512); -define('SMARTIRC_TYPE_NICKCHANGE', 1024); -define('SMARTIRC_TYPE_KICK', 2048); -define('SMARTIRC_TYPE_QUIT', 4096); -define('SMARTIRC_TYPE_LOGIN', 8192); -define('SMARTIRC_TYPE_INFO', 16384); -define('SMARTIRC_TYPE_LIST', 32768); -define('SMARTIRC_TYPE_NAME', 65536); -define('SMARTIRC_TYPE_MOTD', 131072); -define('SMARTIRC_TYPE_MODECHANGE', 262144); -define('SMARTIRC_TYPE_PART', 524288); -define('SMARTIRC_TYPE_ERROR', 1048576); -define('SMARTIRC_TYPE_BANLIST', 2097152); -define('SMARTIRC_TYPE_TOPIC', 4194304); -define('SMARTIRC_TYPE_NONRELEVANT', 8388608); -define('SMARTIRC_TYPE_WHOIS', 16777216); -define('SMARTIRC_TYPE_WHOWAS', 33554432); -define('SMARTIRC_TYPE_USERMODE', 67108864); -define('SMARTIRC_TYPE_CHANNELMODE', 134217728); -define('SMARTIRC_TYPE_CTCP_REQUEST', 268435456); -define('SMARTIRC_TYPE_CTCP_REPLY', 536870912); -define('SMARTIRC_TYPE_ALL', 1073741823); - -$SMARTIRC_replycodes = array( -'RPL_WELCOME' => '001', -'RPL_YOURHOST' => '002', -'RPL_CREATED' => '003', -'RPL_MYINFO' => '004', -'RPL_BOUNCE' => '005', -'RPL_TRACELINK' => '200', -'RPL_TRACECONNECTING' => '201', -'RPL_TRACEHANDSHAKE' => '202', -'RPL_TRACEUNKNOWN' => '203', -'RPL_TRACEOPERATOR' => '204', -'RPL_TRACEUSER' => '205', -'RPL_TRACESERVER' => '206', -'RPL_TRACESERVICE' => '207', -'RPL_TRACENEWTYPE' => '208', -'RPL_TRACECLASS' => '209', -'RPL_TRACERECONNECT' => '210', -'RPL_STATSLINKINFO' => '211', -'RPL_STATSCOMMANDS' => '212', -'RPL_ENDOFSTATS' => '219', -'RPL_UMODEIS' => '221', -'RPL_SERVLIST' => '234', -'RPL_SERVLISTEND' => '235', -'RPL_STATSUPTIME' => '242', -'RPL_STATSOLINE' => '243', -'RPL_LUSERCLIENT' => '251', -'RPL_LUSEROP' => '252', -'RPL_LUSERUNKNOWN' => '253', -'RPL_LUSERCHANNELS' => '254', -'RPL_LUSERME' => '255', -'RPL_ADMINME' => '256', -'RPL_ADMINLOC1' => '257', -'RPL_ADMINLOC2' => '258', -'RPL_ADMINEMAIL' => '259', -'RPL_TRACELOG' => '261', -'RPL_TRACEEND' => '262', -'RPL_TRYAGAIN' => '263', -'RPL_AWAY' => '301', -'RPL_USERHOST' => '302', -'RPL_ISON' => '303', -'RPL_UNAWAY' => '305', -'RPL_NOWAWAY' => '306', -'RPL_WHOISUSER' => '311', -'RPL_WHOISSERVER' => '312', -'RPL_WHOISOPERATOR' => '313', -'RPL_WHOWASUSER' => '314', -'RPL_ENDOFWHO' => '315', -'RPL_WHOISIDLE' => '317', -'RPL_ENDOFWHOIS' => '318', -'RPL_WHOISCHANNELS' => '319', -'RPL_LISTSTART' => '321', -'RPL_LIST' => '322', -'RPL_LISTEND' => '323', -'RPL_CHANNELMODEIS' => '324', -'RPL_UNIQOPIS' => '325', -'RPL_NOTOPIC' => '331', -'RPL_TOPIC' => '332', -'RPL_INVITING' => '341', -'RPL_SUMMONING' => '342', -'RPL_INVITELIST' => '346', -'RPL_ENDOFINVITELIST' => '347', -'RPL_EXCEPTLIST' => '348', -'RPL_ENDOFEXCEPTLIST' => '349', -'RPL_VERSION' => '351', -'RPL_WHOREPLY' => '352', -'RPL_NAMREPLY' => '353', -'RPL_LINKS' => '364', -'RPL_ENDOFLINKS' => '365', -'RPL_ENDOFNAMES' => '366', -'RPL_BANLIST' => '367', -'RPL_ENDOFBANLIST' => '368', -'RPL_ENDOFWHOWAS' => '369', -'RPL_INFO' => '371', -'RPL_MOTD' => '372', -'RPL_ENDOFINFO' => '374', -'RPL_MOTDSTART' => '375', -'RPL_ENDOFMOTD' => '376', -'RPL_YOUREOPER' => '381', -'RPL_REHASHING' => '382', -'RPL_YOURESERVICE' => '383', -'RPL_TIME' => '391', -'RPL_USERSSTART' => '392', -'RPL_USERS' => '393', -'RPL_ENDOFUSERS' => '394', -'RPL_NOUSERS' => '395', -'ERR_NOSUCHNICK' => '401', -'ERR_NOSUCHSERVER' => '402', -'ERR_NOSUCHCHANNEL' => '403', -'ERR_CANNOTSENDTOCHAN' => '404', -'ERR_TOOMANYCHANNELS' => '405', -'ERR_WASNOSUCHNICK' => '406', -'ERR_TOOMANYTARGETS' => '407', -'ERR_NOSUCHSERVICE' => '408', -'ERR_NOORIGIN' => '409', -'ERR_NORECIPIENT' => '411', -'ERR_NOTEXTTOSEND' => '412', -'ERR_NOTOPLEVEL' => '413', -'ERR_WILDTOPLEVEL' => '414', -'ERR_BADMASK' => '415', -'ERR_UNKNOWNCOMMAND' => '421', -'ERR_NOMOTD' => '422', -'ERR_NOADMININFO' => '423', -'ERR_FILEERROR' => '424', -'ERR_NONICKNAMEGIVEN' => '431', -'ERR_ERRONEUSNICKNAME' => '432', -'ERR_NICKNAMEINUSE' => '433', -'ERR_NICKCOLLISION' => '436', -'ERR_UNAVAILRESOURCE' => '437', -'ERR_USERNOTINCHANNEL' => '441', -'ERR_NOTONCHANNEL' => '442', -'ERR_USERONCHANNEL' => '443', -'ERR_NOLOGIN' => '444', -'ERR_SUMMONDISABLED' => '445', -'ERR_USERSDISABLED' => '446', -'ERR_NOTREGISTERED' => '451', -'ERR_NEEDMOREPARAMS' => '461', -'ERR_ALREADYREGISTRED' => '462', -'ERR_NOPERMFORHOST' => '463', -'ERR_PASSWDMISMATCH' => '464', -'ERR_YOUREBANNEDCREEP' => '465', -'ERR_YOUWILLBEBANNED' => '466', -'ERR_KEYSET' => '467', -'ERR_CHANNELISFULL' => '471', -'ERR_UNKNOWNMODE' => '472', -'ERR_INVITEONLYCHAN' => '473', -'ERR_BANNEDFROMCHAN' => '474', -'ERR_BADCHANNELKEY' => '475', -'ERR_BADCHANMASK' => '476', -'ERR_NOCHANMODES' => '477', -'ERR_BANLISTFULL' => '478', -'ERR_NOPRIVILEGES' => '481', -'ERR_CHANOPRIVSNEEDED' => '482', -'ERR_CANTKILLSERVER' => '483', -'ERR_RESTRICTED' => '484', -'ERR_UNIQOPPRIVSNEEDED' => '485', -'ERR_NOOPERHOST' => '491', -'ERR_UMODEUNKNOWNFLAG' => '501', -'ERR_USERSDONTMATCH' => '502', -); - -$SMARTIRC_nreplycodes = array(); - -foreach ($SMARTIRC_replycodes as $key => $value) { - define('SMARTIRC_'.$key, $value); - $SMARTIRC_nreplycodes[$value] = $key; -} -?> \ No newline at end of file diff --git a/tools/IRC_Bot/SmartIRC/irccommands.php b/tools/IRC_Bot/SmartIRC/irccommands.php deleted file mode 100644 index 3c7b76c13..000000000 --- a/tools/IRC_Bot/SmartIRC/irccommands.php +++ /dev/null @@ -1,433 +0,0 @@ - - * - * Full LGPL License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -class Net_SmartIRC_irccommands extends Net_SmartIRC_base -{ - /** - * sends a new message - * - * Sends a message to a channel or user. - * - * @see DOCUMENTATION - * @param integer $type specifies the type, like QUERY/ACTION or CTCP see 'Message Types' - * @param string $destination can be a user or channel - * @param string $message the message - * @return boolean - * @access public - */ - function message($type, $destination, $message, $priority = SMARTIRC_MEDIUM) - { - switch ($type) { - case SMARTIRC_TYPE_CHANNEL: - case SMARTIRC_TYPE_QUERY: - $this->_send('PRIVMSG '.$destination.' :'.$message, $priority); - break; - case SMARTIRC_TYPE_ACTION: - $this->_send('PRIVMSG '.$destination.' :'.chr(1).'ACTION '.$message.chr(1), $priority); - break; - case SMARTIRC_TYPE_NOTICE: - $this->_send('NOTICE '.$destination.' :'.$message, $priority); - break; - case SMARTIRC_TYPE_CTCP: // backwards compatibilty - case SMARTIRC_TYPE_CTCP_REPLY: - $this->_send('NOTICE '.$destination.' :'.chr(1).$message.chr(1), $priority); - break; - case SMARTIRC_TYPE_CTCP_REQUEST: - $this->_send('PRIVMSG '.$destination.' :'.chr(1).$message.chr(1), $priority); - break; - default: - return false; - } - - return true; - } - - /** - * returns an object reference to the specified channel - * - * If the channel does not exist (because not joint) false will be returned. - * - * @param string $channelname - * @return object reference to the channel object - * @access public - */ - function &channel($channelname) - { - if (isset($this->_channels[strtolower($channelname)])) { - return $this->_channels[strtolower($channelname)]; - } else { - return false; - } - } - - // - /** - * Joins one or more IRC channels with an optional key. - * - * @param mixed $channelarray - * @param string $key - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function join($channelarray, $key = null, $priority = SMARTIRC_MEDIUM) - { - if (!is_array($channelarray)) { - $channelarray = array($channelarray); - } - - $channellist = implode(',', $channelarray); - - if ($key !== null) { - $this->_send('JOIN '.$channellist.' '.$key, $priority); - } else { - $this->_send('JOIN '.$channellist, $priority); - } - } - - /** - * parts from one or more IRC channels with an optional reason - * - * @param mixed $channelarray - * @param string $reason - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function part($channelarray, $reason = null, $priority = SMARTIRC_MEDIUM) - { - if (!is_array($channelarray)) { - $channelarray = array($channelarray); - } - - $channellist = implode(',', $channelarray); - - if ($reason !== null) { - $this->_send('PART '.$channellist.' :'.$reason, $priority); - } else { - $this->_send('PART '.$channellist, $priority); - } - } - - /** - * Kicks one or more user from an IRC channel with an optional reason. - * - * @param string $channel - * @param mixed $nicknamearray - * @param string $reason - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function kick($channel, $nicknamearray, $reason = null, $priority = SMARTIRC_MEDIUM) - { - if (!is_array($nicknamearray)) { - $nicknamearray = array($nicknamearray); - } - - $nicknamelist = implode(',', $nicknamearray); - - if ($reason !== null) { - $this->_send('KICK '.$channel.' '.$nicknamelist.' :'.$reason, $priority); - } else { - $this->_send('KICK '.$channel.' '.$nicknamelist, $priority); - } - } - - /** - * gets a list of one ore more channels - * - * Requests a full channellist if $channelarray is not given. - * (use it with care, usualy its a looooong list) - * - * @param mixed $channelarray - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function getList($channelarray = null, $priority = SMARTIRC_MEDIUM) - { - if ($channelarray !== null) { - if (!is_array($channelarray)) { - $channelarray = array($channelarray); - } - - $channellist = implode(',', $channelarray); - $this->_send('LIST '.$channellist, $priority); - } else { - $this->_send('LIST', $priority); - } - } - - /** - * requests all nicknames of one or more channels - * - * The requested nickname list also includes op and voice state - * - * @param mixed $channelarray - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function names($channelarray = null, $priority = SMARTIRC_MEDIUM) - { - if ($channelarray !== null) { - if (!is_array($channelarray)) { - $channelarray = array($channelarray); - } - - $channellist = implode(',', $channelarray); - $this->_send('NAMES '.$channellist, $priority); - } else { - $this->_send('NAMES', $priority); - } - } - - /** - * sets a new topic of a channel - * - * @param string $channel - * @param string $newtopic - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function setTopic($channel, $newtopic, $priority = SMARTIRC_MEDIUM) - { - $this->_send('TOPIC '.$channel.' :'.$newtopic, $priority); - } - - /** - * gets the topic of a channel - * - * @param string $channel - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function getTopic($channel, $priority = SMARTIRC_MEDIUM) - { - $this->_send('TOPIC '.$channel, $priority); - } - - /** - * sets or gets the mode of an user or channel - * - * Changes/requests the mode of the given target. - * - * @param string $target the target, can be an user (only yourself) or a channel - * @param string $newmode the new mode like +mt - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function mode($target, $newmode = null, $priority = SMARTIRC_MEDIUM) - { - if ($newmode !== null) { - $this->_send('MODE '.$target.' '.$newmode, $priority); - } else { - $this->_send('MODE '.$target, $priority); - } - } - - /** - * ops an user in the given channel - * - * @param string $channel - * @param string $nickname - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function op($channel, $nickname, $priority = SMARTIRC_MEDIUM) - { - $this->mode($channel, '+o '.$nickname, $priority); - } - - /** - * deops an user in the given channel - * - * @param string $channel - * @param string $nickname - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function deop($channel, $nickname, $priority = SMARTIRC_MEDIUM) - { - $this->mode($channel, '-o '.$nickname, $priority); - } - - /** - * voice a user in the given channel - * - * @param string $channel - * @param string $nickname - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function voice($channel, $nickname, $priority = SMARTIRC_MEDIUM) - { - $this->mode($channel, '+v '.$nickname, $priority); - } - - /** - * devoice a user in the given channel - * - * @param string $channel - * @param string $nickname - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function devoice($channel, $nickname, $priority = SMARTIRC_MEDIUM) - { - $this->mode($channel, '-v '.$nickname, $priority); - } - - /** - * bans a hostmask for the given channel or requests the current banlist - * - * The banlist will be requested if no hostmask is specified - * - * @param string $channel - * @param string $hostmask - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function ban($channel, $hostmask = null, $priority = SMARTIRC_MEDIUM) - { - if ($hostmask !== null) { - $this->mode($channel, '+b '.$hostmask, $priority); - } else { - $this->mode($channel, 'b', $priority); - } - } - - /** - * unbans a hostmask on the given channel - * - * @param string $channel - * @param string $hostmask - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function unban($channel, $hostmask, $priority = SMARTIRC_MEDIUM) - { - $this->mode($channel, '-b '.$hostmask, $priority); - } - - /** - * invites a user to the specified channel - * - * @param string $nickname - * @param string $channel - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function invite($nickname, $channel, $priority = SMARTIRC_MEDIUM) - { - $this->_send('INVITE '.$nickname.' '.$channel, $priority); - } - - /** - * changes the own nickname - * - * Trys to set a new nickname, nickcollisions are handled. - * - * @param string $newnick - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function changeNick($newnick, $priority = SMARTIRC_MEDIUM) - { - $this->_send('NICK '.$newnick, $priority); - $this->_nick = $newnick; - } - - /** - * requests a 'WHO' from the specified target - * - * @param string $target - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function who($target, $priority = SMARTIRC_MEDIUM) - { - $this->_send('WHO '.$target, $priority); - } - - /** - * requests a 'WHOIS' from the specified target - * - * @param string $target - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function whois($target, $priority = SMARTIRC_MEDIUM) - { - $this->_send('WHOIS '.$target, $priority); - } - - /** - * requests a 'WHOWAS' from the specified target - * (if he left the IRC network) - * - * @param string $target - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function whowas($target, $priority = SMARTIRC_MEDIUM) - { - $this->_send('WHOWAS '.$target, $priority); - } - - /** - * sends QUIT to IRC server and disconnects - * - * @param string $quitmessage optional quitmessage - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function quit($quitmessage = null, $priority = SMARTIRC_MEDIUM) - { - if ($quitmessage !== null) { - $this->_send('QUIT :'.$quitmessage, $priority); - } else { - $this->_send('QUIT', $priority); - } - } -} -?> \ No newline at end of file diff --git a/tools/IRC_Bot/SmartIRC/messagehandler.php b/tools/IRC_Bot/SmartIRC/messagehandler.php deleted file mode 100644 index 54c46169e..000000000 --- a/tools/IRC_Bot/SmartIRC/messagehandler.php +++ /dev/null @@ -1,411 +0,0 @@ - - * - * Full LGPL License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -class Net_SmartIRC_messagehandler extends Net_SmartIRC_irccommands -{ - /* misc */ - function _event_ping(&$ircdata) - { - $this->_pong(substr($ircdata->rawmessage, 5)); - } - - function _event_error(&$ircdata) - { - if ($this->_autoretry == true) { - $this->reconnect(); - } else { - $this->disconnect(true); - } - } - - function _event_join(&$ircdata) - { - if ($this->_channelsyncing == true) { - if ($this->_nick == $ircdata->nick) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: joining channel: '.$ircdata->channel, __FILE__, __LINE__); - $channel = &new Net_SmartIRC_channel(); - $channel->name = $ircdata->channel; - $this->_channels[strtolower($channel->name)] = &$channel; - - $this->who($channel->name); - $this->mode($channel->name); - $this->ban($channel->name); - } - - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: '.$ircdata->nick.' joins channel: '.$ircdata->channel, __FILE__, __LINE__); - $channel = &$this->_channels[strtolower($ircdata->channel)]; - $user = &new Net_SmartIRC_channeluser(); - $user->nick = $ircdata->nick; - $user->ident = $ircdata->ident; - $user->host = $ircdata->host; - - $this->_adduser($channel, $user); - $this->who($user->nick); - } - } - - function _event_part(&$ircdata) - { - if ($this->_channelsyncing == true) { - $this->_removeuser($ircdata); - } - } - - function _event_kick(&$ircdata) - { - if ($this->_channelsyncing == true) { - $this->_removeuser($ircdata); - } - } - - function _event_quit(&$ircdata) - { - if ($this->_channelsyncing == true) { - $this->_removeuser($ircdata); - } - } - - function _event_nick(&$ircdata) - { - if ($this->_channelsyncing == true) { - $newnick = substr($ircdata->rawmessageex[2], 1); - $lowerednewnick = strtolower($newnick); - $lowerednick = strtolower($ircdata->nick); - - foreach ($this->_channels as $channelkey => $channelvalue) { - // loop through all channels - $channel = &$this->_channels[$channelkey]; - foreach ($channel->users as $userkey => $uservalue) { - // loop through all user in this channel - - if ($ircdata->nick == $uservalue->nick) { - // found him - // time for updating the object and his nickname - $channel->users[$lowerednewnick] = $channel->users[$lowerednick]; - $channel->users[$lowerednewnick]->nick = $newnick; - - if ($lowerednewnick != $lowerednick) { - unset($channel->users[$lowerednick]); - } - - // he was maybe op or voice, update comming - if (isset($channel->ops[$ircdata->nick])) { - $channel->ops[$newnick] = $channel->ops[$ircdata->nick]; - unset($channel->ops[$ircdata->nick]); - } - if (isset($channel->voices[$ircdata->nick])) { - $channel->voices[$newnick] = $channel->voices[$ircdata->nick]; - unset($channel->voices[$ircdata->nick]); - } - - break; - } - } - } - } - } - - function _event_mode(&$ircdata) - { - // check if its own usermode - if ($ircdata->rawmessageex[2] == $this->_nick) { - $this->_usermode = substr($ircdata->rawmessageex[3], 1); - } else if ($this->_channelsyncing == true) { - // it's not, and we do channel syching - $channel = &$this->_channels[strtolower($ircdata->channel)]; - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: updating channel mode for: '.$channel->name, __FILE__, __LINE__); - $mode = $ircdata->rawmessageex[3]; - $parameters = array_slice($ircdata->rawmessageex, 4); - - $add = false; - $remove = false; - $channelmode = ''; - $modelength = strlen($mode); - for ($i = 0; $i < $modelength; $i++) { - switch($mode[$i]) { - case '-': - $remove = true; - $add = false; - break; - case '+': - $add = true; - $remove = false; - break; - // user modes - case 'o': - $nick = array_shift($parameters); - $lowerednick = strtolower($nick); - if ($add) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding op: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); - $channel->ops[$nick] = true; - $channel->users[$lowerednick]->op = true; - } - if ($remove) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing op: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); - unset($channel->ops[$nick]); - $channel->users[$lowerednick]->op = false; - } - break; - case 'v': - $nick = array_shift($parameters); - $lowerednick = strtolower($nick); - if ($add) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding voice: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); - $channel->voices[$nick] = true; - $channel->users[$lowerednick]->voice = true; - } - if ($remove) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing voice: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); - unset($channel->voices[$nick]); - $channel->users[$lowerednick]->voice = false; - } - break; - case 'k': - $key = array_shift($parameters); - if ($add) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: stored channel key for: '.$channel->name, __FILE__, __LINE__); - $channel->key = $key; - } - if ($remove) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removed channel key for: '.$channel->name, __FILE__, __LINE__); - $channel->key = ''; - } - break; - default: - // channel modes - if ($mode[$i] == 'b') { - $hostmask = array_shift($parameters); - if ($add) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding ban: '.$hostmask.' for: '.$channel->name, __FILE__, __LINE__); - $channel->bans[$hostmask] = true; - } - if ($remove) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing ban: '.$hostmask.' for: '.$channel->name, __FILE__, __LINE__); - unset($channel->bans[$hostmask]); - } - } else { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: storing unknown channelmode ('.$mode.') in channel->mode for: '.$channel->name, __FILE__, __LINE__); - if ($add) { - $channel->mode .= $mode[$i]; - } - if ($remove) { - $channel->mode = str_replace($mode[$i], '', $channel->mode); - } - } - } - } - } - } - - function _event_topic(&$ircdata) - { - if ($this->_channelsyncing == true) { - $channel = &$this->_channels[strtolower($ircdata->rawmessageex[2])]; - $channel->topic = $ircdata->message; - } - } - - function _event_privmsg(&$ircdata) - { - if ($ircdata->type == SMARTIRC_TYPE_CTCP) { - // substr must be 1,4 because of \001 in CTCP messages - if (substr($ircdata->message, 1, 4) == 'PING') { - $this->message(SMARTIRC_TYPE_CTCP, $ircdata->nick, 'PING '.substr($ircdata->message, 5, -1)); - } elseif (substr($ircdata->message, 1, 7) == 'VERSION') { - if (!empty($this->_ctcpversion)) { - $versionstring = $this->_ctcpversion.' | using '.SMARTIRC_VERSIONSTRING; - } else { - $versionstring = SMARTIRC_VERSIONSTRING; - } - - $this->message(SMARTIRC_TYPE_CTCP, $ircdata->nick, 'VERSION '.$versionstring); - } - } - } - - /* rpl_ */ - function _event_rpl_welcome(&$ircdata) - { - $this->_loggedin = true; - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: logged in', __FILE__, __LINE__); - - // updating our nickname, that we got (maybe cutted...) - $this->_nick = $ircdata->rawmessageex[2]; - } - - function _event_rpl_motdstart(&$ircdata) - { - $this->_motd[] = $ircdata->message; - } - - function _event_rpl_motd(&$ircdata) - { - $this->_motd[] = $ircdata->message; - } - - function _event_rpl_endofmotd(&$ircdata) - { - $this->_motd[] = $ircdata->message; - } - - function _event_rpl_umodeis(&$ircdata) - { - $this->_usermode = $ircdata->message; - } - - function _event_rpl_channelmodeis(&$ircdata) { - if ($this->_channelsyncing == true && $this->isJoined($ircdata->channel)) { - $mode = $ircdata->rawmessageex[4]; - $parameters = array_slice($ircdata->rawmessageex, 5); - - $ircdata->rawmessageex = array( 0 => '', - 1 => '', - 2 => '', - 3 => $mode); - - foreach ($parameters as $value) { - $ircdata->rawmessageex[] = $value; - } - - // let _mode() handle the received mode - $this->_event_mode($ircdata); - } - } - - function _event_rpl_whoreply(&$ircdata) - { - if ($this->_channelsyncing == true) { - $nick = $ircdata->rawmessageex[7]; - if ($ircdata->channel == '*') { - // we got who info without channel info, so we need to search the user - // on all channels and update him - foreach ($this->_channels as $channel) { - if ($this->isJoined($channel->name, $nick)) { - $ircdata->channel = $channel->name; - $this->_event_rpl_whoreply($ircdata); - } - } - } else { - if (!$this->isJoined($ircdata->channel, $nick)) { - return; - } - - $channel = &$this->_channels[strtolower($ircdata->channel)]; - - $user = &new Net_SmartIRC_channeluser(); - $user->ident = $ircdata->rawmessageex[4]; - $user->host = $ircdata->rawmessageex[5]; - $user->server = $ircdata->rawmessageex[6]; - $user->nick = $ircdata->rawmessageex[7]; - - $user->op = false; - $user->voice = false; - $user->ircop = false; - - $usermode = $ircdata->rawmessageex[8]; - $usermodelength = strlen($usermode); - for ($i = 0; $i < $usermodelength; $i++) { - switch ($usermode[$i]) { - case 'H': - $user->away = false; - break; - case 'G': - $user->away = true; - break; - case '@': - $user->op = true; - break; - case '+': - $user->voice = true; - break; - case '*': - $user->ircop = true; - break; - } - } - - $user->hopcount = substr($ircdata->rawmessageex[9], 1); - $user->realname = implode(array_slice($ircdata->rawmessageex, 10), ' '); - - $this->_adduser($channel, $user); - } - } - } - - function _event_rpl_namreply(&$ircdata) - { - if ($this->_channelsyncing == true) { - $channel = &$this->_channels[strtolower($ircdata->channel)]; - - $userarray = explode(' ', rtrim($ircdata->message)); - $userarraycount = count($userarray); - for ($i = 0; $i < $userarraycount; $i++) { - $user = &new Net_SmartIRC_channeluser(); - - $usermode = substr($userarray[$i], 0, 1); - switch ($usermode) { - case '@': - $user->op = true; - $user->nick = substr($userarray[$i], 1); - break; - case '+': - $user->voice = true; - $user->nick = substr($userarray[$i], 1); - break; - default: - $user->nick = $userarray[$i]; - } - - $this->_adduser($channel, $user); - } - } - } - - function _event_rpl_banlist(&$ircdata) - { - if ($this->_channelsyncing == true && $this->isJoined($ircdata->channel)) { - $channel = &$this->_channels[strtolower($ircdata->channel)]; - $hostmask = $ircdata->rawmessageex[4]; - $channel->bans[$hostmask] = true; - } - } - - function _event_rpl_topic(&$ircdata) - { - if ($this->_channelsyncing == true) { - $channel = &$this->_channels[strtolower($ircdata->channel)]; - $topic = substr(implode(array_slice($ircdata->rawmessageex, 4), ' '), 1); - $channel->topic = $topic; - } - } - - /* err_ */ - function _event_err_nicknameinuse(&$ircdata) - { - $this->_nicknameinuse(); - } -} -?> \ No newline at end of file diff --git a/tools/IRC_Bot/magpierss/AUTHORS b/tools/IRC_Bot/magpierss/AUTHORS deleted file mode 100644 index 7d7f3f53e..000000000 --- a/tools/IRC_Bot/magpierss/AUTHORS +++ /dev/null @@ -1 +0,0 @@ -kellan diff --git a/tools/IRC_Bot/magpierss/CHANGES b/tools/IRC_Bot/magpierss/CHANGES deleted file mode 100644 index b186af5c9..000000000 --- a/tools/IRC_Bot/magpierss/CHANGES +++ /dev/null @@ -1,37 +0,0 @@ -Version 0.7 ------------ - - support for input and output charset encoding - based on the work in FoF, uses iconv or mbstring if available - - - -Version 0.6 ------------ - - basic support for Atom syndication format - including support for Atom content constructs - - fixed support for private feeds (HTTP Auth and SSL) - (thanks to silverorange.com for providing test feeds) - - support for some broken webservers - -Version 0.52 ------------ - - support GZIP content negoiation - - PHP 4.3.2 support - -Version 0.4 ------------ - - improved error handling, better access for script authors - - included example scripts of working with MagpieRSS - - new Smarty plugin for RSS date parsing - -Version 0.3 ------------ - - added support for conditional gets (Last-Modified, ETag) - - now use Snoopy to handle fetching RSS files - -Version 0.2 ------------ - - MAJOR CLEAN UP - - removed kludgy $options array in favour of constants - - phased out returning arrays - - added better error handling - - re-worked comments diff --git a/tools/IRC_Bot/magpierss/ChangeLog b/tools/IRC_Bot/magpierss/ChangeLog deleted file mode 100644 index d52a58782..000000000 --- a/tools/IRC_Bot/magpierss/ChangeLog +++ /dev/null @@ -1,346 +0,0 @@ -2004-11-21 22:45 kellan - - * rss_fetch.inc: detab, bump version - -2004-11-21 20:52 kellan - - * rss_fetch.inc, rss_parse.inc: cache on $url . $output_encoding - otherwise we can get munged output - * rss_parse.inc: don't set ERROR on notice or warning (rss_fetch - dies on parse errors) - * rss_fetch.inc: add encoding defines (fix timeout error reporting) - -2004-11-21 17:21 kellan - - * rss_parse.inc: incorporate steve's patch - -2004-11-21 16:26 kellan - - * rss_parse.inc: remove old debugging functions, totally - arbitrarily. might break stuff. can't really explain why i'm - doing this. - -2004-10-28 12:52 kellan - - * rss_parse.inc: fixed '=' instead of '==' - -2004-10-25 21:48 kellan - - * rss_parse.inc: chance epoch to timestamp to conform w/ php naming - conventions - -2004-06-15 09:00 kellan - - * rss_parse.inc: [no log message] - -2004-04-26 11:16 kellan - - * rss_fetch.inc: bump version - -2004-04-26 09:36 kellan - - * rss_parse.inc: fix field doubling - -2004-04-24 14:47 kellan - - * CHANGES, ChangeLog: updated - -2004-04-24 14:35 kellan - - * rss_fetch.inc: bumped version - -2004-04-24 13:52 kellan - - * rss_parse.inc: support arbitrary atom content constructs - - some refactoring - -2004-04-24 13:15 kellan - - * rss_parse.inc: support summary content contstruct. add normalize - function - -2004-03-27 13:29 kellan - - * extlib/Snoopy.class.inc: accept self-signed certs - -2004-03-27 09:53 kellan - - * extlib/Snoopy.class.inc: fixed SSL support * set status * set - error on bad curl - - (also ripped out big chunks of dead weight (submit_form) which - were getting in my way - -2004-01-24 23:25 kellan - - * rss_parse.inc: make RSS 1.0's rdf:about available - -2004-01-24 23:07 kellan - - * rss_parse.inc: clean up text, and line formats. add support item - rdf:about - -2004-01-24 20:40 kellan - - * CHANGES, ChangeLog: update changes - -2004-01-24 20:37 kellan - - * rss_fetch.inc: updated version - -2004-01-24 20:35 kellan - - * rss_parse.inc: whitespace - -2004-01-24 20:23 kellan - - * extlib/Snoopy.class.inc: support badly formatted http headers - -2004-01-24 20:20 kellan - - * rss_parse.inc: added alpha atom parsing support - -2003-06-25 19:34 kellan - - * extlib/Snoopy.class.inc: fixed fread 4.3.2 compatibility problems - -2003-06-13 08:31 kellan - - * rss_fetch.inc: reset cache on 304 - -2003-06-12 18:37 kellan - - * rss_cache.inc, rss_fetch.inc, rss_parse.inc, rss_utils.inc: - bumped up version numbers - -2003-06-12 18:32 kellan - - * htdocs/index.html: updated news - -2003-06-12 18:27 kellan - - * NEWS: a manual blog :) - -2003-06-12 18:22 kellan - - * htdocs/index.html: fully qualified img - -2003-06-12 18:20 kellan - - * htdocs/index.html: clean up. added badge. - -2003-06-12 18:04 kellan - - * rss_utils.inc: clean up regex - -2003-06-12 18:02 kellan - - * rss_cache.inc: suppress some warnings - -2003-05-30 17:44 kellan - - * extlib/Snoopy.class.inc: more comments, cleaned up notice - -2003-05-30 12:14 kellan - - * extlib/Snoopy.class.inc: don't advertise gzip support if the user - hasn't built php with gzinflate support - -2003-05-12 19:32 kellan - - * ChangeLog: changes - -2003-05-12 19:11 kellan - - * htdocs/index.html: announce 0.5 - -2003-05-12 18:42 kellan - - * htdocs/index.html: change - -2003-05-12 18:39 kellan - - * rss_fetch.inc: use gzip - -2003-05-12 18:37 kellan - - * extlib/Snoopy.class.inc: added support gzip encoded content - negoiation - -2003-05-12 18:32 kellan - - * rss_cache.inc, rss_fetch.inc, rss_parse.inc, rss_utils.inc: fixed - typoes - -2003-04-26 18:44 kellan - - * rss_parse.inc: fix minor typo - -2003-04-18 05:19 kellan - - * htdocs/cookbook.html: updated cookbook to show more code for - limiting items - -2003-03-03 13:02 kellan - - * rss_parse.inc, scripts/magpie_slashbox.php: committed (or - adpated) patch from Nicola (www.technick.com) to quell 'Undefined - Indexes' notices - -2003-03-03 12:59 kellan - - * rss_fetch.inc: commited patch from nicola (www.technick.com) to - quell 'undefined indexes' notices. - - * Magpie now automatically includes its version in the - user-agent, & whether cacheing is turned on. - -2003-02-11 22:22 kellan - - * CHANGES, ChangeLog: ChangeLog now auto-generated by cvs2cl - -2003-02-11 21:21 kellan - - * rss_fetch.inc: better errors, hopefully stomped on pesky notices - -2003-02-11 21:19 kellan - - * rss_parse.inc: check to see is xml is supported, if not die - - also throw better xml errors - -2003-02-11 21:18 kellan - - * rss_cache.inc: hopefully cleared up some notices that were being - thrown into the log - - fixed a debug statement that was being called as an error - -2003-02-11 21:15 kellan - - * scripts/: magpie_simple.php, magpie_slashbox.php: moved - magpie_simple to magpie_slashbox, and replaced it with a simpler - demo. - -2003-02-11 21:02 kellan - - * INSTALL, README, TROUBLESHOOTING: Improved documentation. Better - install instructions. - - TROUBLESHOOTING cover common installation and usage problems - -2003-01-22 11:40 kellan - - * htdocs/cookbook.html: added cookbook.html - -2003-01-21 20:47 kellan - - * cookbook: a magpie cookbook - -2003-01-20 07:09 kellan - - * ChangeLog: updated - -2003-01-20 06:23 kellan - - * scripts/simple_smarty.php: minor clean up - -2003-01-20 06:15 kellan - - * scripts/README: added smarty url - -2003-01-20 06:14 kellan - - * magpie_simple.php, htdocs/index.html, scripts/README, - scripts/magpie_debug.php, scripts/magpie_simple.php, - scripts/simple_smarty.php, - scripts/smarty_plugin/modifier.rss_date_parse.php, - scripts/templates/simple.smarty: Added scripts directory for - examples on how to use MagpieRSS - - magpie_simple - is a simple example magpie_debug - spew all the - information from a parsed RSS feed simple_smary - example of - using magpie with Smarty template system - smarty_plugin/modifier.rss_date_parse.php - support file for the - smarty demo templates/simple.smary - template for the smarty demo - -2003-01-20 06:11 kellan - - * rss_fetch.inc, rss_parse.inc: changes to error handling to give - script authors more access to magpie's errors. - - added method magpie_error() to retrieve global MAGPIE_ERROR - variable for when fetch_rss() returns false - -2002-10-26 16:02 kellan - - * htdocs/index.html: putting the website under source control - -2002-10-26 15:43 kellan - - * AUTHORS, ChangeLog, INSTALL, README: some documentation to make - it all look official :) - -2002-10-25 20:04 kellan - - * magpie_simple.php: quxx - -2002-10-25 20:04 kellan - - * rss_parse.inc: added support for textinput and image - -2002-10-25 16:23 kellan - - * magpie_simple.php, rss_cache.inc, rss_fetch.inc, rss_parse.inc, - rss_utils.inc: switched to using Snoopy for fetching remote RSS - files. - - added support for conditional gets - -2002-10-25 16:22 kellan - - * rss_cache.inc, rss_fetch.inc, rss_parse.inc, rss_utils.inc: - Change comment style to slavishly imitate the phpinsider style - found in Smarty and Snoopy :) - -2002-10-25 16:18 kellan - - * extlib/Snoopy.class.inc: added Snoopy in order to support - conditional gets - -2002-10-23 20:19 kellan - - * magpie_simple.php, rss_cache.inc, rss_fetch.inc, rss_parse.inc: - MAJOR CLEANUP! - - * rss_fetch got rid of the options array, replaced it with a more - PHP-like solution of using defines. constants are setup, with - defaults, in the function init() - - got rid of the idiom of passing back an array, its was awkward to - deal with in PHP, and unusual (and consquently confusing to - people). now i return true/false values, and try to setup error - string where appropiate (rss_cache has the most complete example - of this) - - change the logic for interacting with the cache - - * rss_cache major re-working of how error are handled. tried to - make the code more resillient. the cache is now much more aware - of MAX_AGE, where before this was being driven out of rss_fetch - (which was silly) - - * rss_parse properly handles xml parse errors. used to sail - along blithely unaware. - -2002-09-11 08:11 kellan - - * rss_cache.inc, rss_parse.inc, magpie_simple.php, rss_fetch.inc, - rss_utils.inc: Initial revision - -2002-09-11 08:11 kellan - - * rss_cache.inc, rss_parse.inc, magpie_simple.php, rss_fetch.inc, - rss_utils.inc: initial import - diff --git a/tools/IRC_Bot/magpierss/INSTALL b/tools/IRC_Bot/magpierss/INSTALL deleted file mode 100644 index 640833d50..000000000 --- a/tools/IRC_Bot/magpierss/INSTALL +++ /dev/null @@ -1,143 +0,0 @@ -REQUIREMENTS - - MapieRSS requires a recent PHP 4+ (developed with 4.2.0) - with xml (expat) support. - - Optionally: - * PHP5 with libxml2 support. - * cURL for SSL support - * iconv (preferred) or mb_string for expanded character set support - -QUICK START - - Magpie consists of 4 files (rss_fetch.inc, rss_parser.inc, rss_cache.inc, - and rss_utils.inc), and the directory extlib (which contains a modified - version of the Snoopy HTTP client) - - Copy these 5 resources to a directory named 'magpierss' in the same - directory as your PHP script. - - At the top of your script add the following line: - - require_once('magpierss/rss_fetch.inc'); - - Now you can use the fetch_rss() method: - - $rss = fetch_rss($url); - - Done. That's it. See README for more details on using MagpieRSS. - -NEXT STEPS - - Important: you'll probably want to get the cache directory working in - order to speed up your application, and not abuse the webserver you're - downloading the RSS from. - - Optionally you can install MagpieRSS in your PHP include path in order to - make it available server wide. - - Lastly you might want to look through the constants in rss_fetch.inc see if - there is anything you want to override (the defaults are pretty good) - - For more info, or if you have trouble, see TROUBLESHOOTING - -SETTING UP CACHING - - Magpie has built-in transparent caching. With caching Magpie will only - fetch and parse RSS feeds when there is new content. Without this feature - your pages will be slow, and the sites serving the RSS feed will be annoyed - with you. - -** Simple and Automatic ** - - By default Magpie will try to create a cache directory named 'cache' in the - same directory as your PHP script. - -** Creating a Local Cache Directory ** - - Often this will fail, because your webserver doesn't have sufficient - permissions to create the directory. - - Exact instructions for how to do this will vary from install to install and - platform to platform. The steps are: - - 1. Make a directory named 'cache' - 2. Give the web server write access to that directory. - - An example of how to do this on Debian would be: - - 1. mkdir /path/to/script/cache - 2. chgrp www-data /path/to/script/cache - 3. chmod 775 /path/to/script/cache - - On other Unixes you'll need to change 'www-data' to what ever user Apache - runs as. (on MacOS X the user would be 'www') - -** Cache in /tmp ** - - Sometimes you won't be able to create a local cache directory. Some reasons - might be: - - 1. No shell account - 2. Insufficient permissions to change ownership of a directory - 3. Webserver runs as 'nobody' - - In these situations using a cache directory in /tmp can often be a good - option. - - The drawback is /tmp is public, so anyone on the box can read the cache - files. Usually RSS feeds are public information, so you'll have to decide - how much of an issue that is. - - To use /tmp as your cache directory you need to add the following line to - your script: - - define('MAGPIE_CACHE_DIR', '/tmp/magpie_cache'); - -** Global Cache ** - - If you have several applications using Magpie, you can create a single - shared cache directory, either using the /tmp cache, or somewhere else on - the system. - - The upside is that you'll distribute fetching and parsing feeds across - several applications. - -INSTALLING MAGPIE SERVER WIDE - - Rather then following the Quickstart instructions which requires you to have - a copy of Magpie per application, alternately you can place it in some - shared location. - -** Adding Magpie to Your Include Path ** - - Copy the 5 resources (rss_fetch.inc, rss_parser.inc, rss_cache.inc, - rss_utils.inc, and extlib) to a directory named 'magpierss' in your include - path. Now any PHP file on your system can use Magpie with: - - require_once('magpierss/rss_fetch.inc'); - - Different installs have different include paths, and you'll have to figure - out what your include_path is. - - From shell you can try: - - php -i | grep 'include_path' - - Alternatley you can create a phpinfo.php file with contains: - - - - Debian's default is: - - /usr/share/php - - (though more idealogically pure location would be /usr/local/share/php) - - Apple's default include path is: - - /usr/lib/php - - While the Entropy PHP build seems to use: - - /usr/local/php/lib/php \ No newline at end of file diff --git a/tools/IRC_Bot/magpierss/NEWS b/tools/IRC_Bot/magpierss/NEWS deleted file mode 100644 index 5ac6b9788..000000000 --- a/tools/IRC_Bot/magpierss/NEWS +++ /dev/null @@ -1,53 +0,0 @@ -MagpieRSS News - -MAGPIERSS 0.51 RELEASED - * important bugfix! - * fix "silent failure" when PHP doesn't have zlib - -FEED ON FEEDS USES MAGPIE - * web-based RSS aggregator built with Magpie - * easy to install, easy to use. - http://minutillo.com/steve/feedonfeeds/ - -MAGPIERSS 0.5 RELEASED - * supports transparent HTTP gzip content negotiation for reduced bandwidth usage - * quashed some undefined index notices - -MAGPIERSS 0.46 RELEASED - * minor release, more error handling clean up - * documentation fixes, simpler example - * new trouble shooting guide for installation and usage problems - http://magpierss.sourceforge.net/TROUBLESHOOTING - -MAGPIE NEWS AS RSS - * releases, bug fixes, releated stories in RSS - -MAGPIERSS COOKBOOK: SIMPLE PHP RSS HOW TOS - * answers some of the most frequently asked Magpie questions - * feedback, suggestions, requests, recipes welcome - http://magpierss.sourceforge.net/cookbook.html - -MAGPIERSS 0.4 RELEASED! - * improved error handling, more flexibility for script authors, backwards compatible - * new and better examples! including using MagpieRSS and Smarty - * new Smarty plugin for RSS date parsing - http://smarty.php.net - -INFINITE PENGUIN NOW SUPPORTS MAGPIE 0.3 - * simple, sophisticated RSS viewer - * includes auto-generated javascript ticker from RSS feed - http://www.infinitepenguins.net/rss/ - -TRAUMWIND RELEASES REX BACKEND FOR MAGPIERSS - * drop in support using regex based XML parser - * parses improperly formed XML that chokes expat - http://traumwind.de/blog/magpie/magpie_alike.php - -MAGPIERSS 0.3 RELEASED! - * Support added for HTTP Conditional GETs. - http://fishbowl.pastiche.org/archives/001132.html - -MAGPIERSS 0.2! - * Major clean up of the code. Easier to use. - * Simpler install on shared hosts. - * Better documentation and comments. diff --git a/tools/IRC_Bot/magpierss/README b/tools/IRC_Bot/magpierss/README deleted file mode 100644 index 6af7edb07..000000000 --- a/tools/IRC_Bot/magpierss/README +++ /dev/null @@ -1,48 +0,0 @@ -NAME - - MagpieRSS - a simple RSS integration tool - -SYNOPSIS - - require_once(rss_fetch.inc); - $url = $_GET['url']; - $rss = fetch_rss( $url ); - - echo "Channel Title: " . $rss->channel['title'] . "

"; - echo "

    "; - foreach ($rss->items as $item) { - $href = $item['link']; - $title = $item['title']; - echo "
  • $title
  • "; - } - echo "
"; - -DESCRIPTION - - MapieRSS is an XML-based RSS parser in PHP. It attempts to be "PHP-like", - and simple to use. - - Some features include: - - * supports RSS 0.9 - 1.0, with limited RSS 2.0 support - * supports namespaces, and modules, including mod_content and mod_event - * open minded [1] - * simple, functional interface, to object oriented backend parser - * automatic caching of parsed RSS objects makes its easy to integrate - * supports conditional GET with Last-Modified, and ETag - * uses constants for easy override of default behaviour - * heavily commented - - -1. By open minded I mean Magpie will accept any tag it finds in good faith that - it was supposed to be here. For strict validation, look elsewhere. - - -GETTING STARTED - - - -COPYRIGHT: - Copyright(c) 2002 kellan@protest.net. All rights reserved. - This software is released under the GNU General Public License. - Please read the disclaimer at the top of the Snoopy.class.inc file. diff --git a/tools/IRC_Bot/magpierss/TROUBLESHOOTING b/tools/IRC_Bot/magpierss/TROUBLESHOOTING deleted file mode 100644 index 89068d382..000000000 --- a/tools/IRC_Bot/magpierss/TROUBLESHOOTING +++ /dev/null @@ -1,152 +0,0 @@ -TROUBLESHOOTING - - -Trouble Installing MagpieRSS: - -1. Fatal error: Failed opening required '/path/to/script/rss_fetch.inc' - (include_path='.:/usr/local/lib/php:/usr/local/lib/php/pear') - -2. Cache couldn't make dir './cache'. - -3. Fatal error: Failed to load PHP's XML Extension. - http://www.php.net/manual/en/ref.xml.php - -Trouble Using MagpieRSS - -4. Warning: MagpieRSS: Failed to fetch example.com/index.rdf. - (HTTP Error: Invalid protocol "") - -5. Warning: MagpieRSS: Failed to parse RSS file. - (not well-formed (invalid token) at line 19, column 98) - -6. Warning: MagpieRSS: Failed to fetch http://localhost/rss/features.1-0.rss. - (HTTP Response: HTTP/1.1 404 Not Found) - -If you would rather provide a custom error, see the COOKBOOK -(http://magpierss.sf.net/cookbook.html) recipe 2. - -************************************************************************* -1. Fatal error: Failed opening required '/path/to/script/rss_fetch.inc' - (include_path='.:/usr/local/lib/php:/usr/local/lib/php/pear') - - This could mean that: - - a) PHP can't find the MagpieRSS files. - b) PHP found them the MagpieRSS files, but can't read them. - - a. Telling PHP where to look for MagpieRSS file. - - This might mean your PHP program can't find the MagpieRSS libraries. - Magpie relies on 4 include files, rss_fetch.inc, rss_parse.inc, - rss_cache.inc, rss_util.inc, and for normal use you'll need all 4 (see the - cookbook for exceptions). - - This can be fixed by making sure the MagpieRSS files are in your include - path. - - If you can edit your include path (for example your on a shared host) then - you need to replace: - - require_once('rss_fetch.inc'); - - -with- - - define('MAGPIE_DIR', '/path/to/magpierss/'); - require_once(MAGPIE_DIR.'rss_fetch.inc'); - - b. PHP can't read the MagpieRSS files - - All PHP libraries need to be readable by your webserver. - - On Unix you can accomplish this with: - - chmod 755 rss_fetch.inc rss_parse.inc rss_cache.inc rss_util.inc - -************************************************************************* -2. Cache couldn't make dir './cache'. - - MagpieRSS caches the results of fetched and parsed RSS to reduce the load on - both your server, and the remote server providing the RSS. It does this by - writing files to a cache directory. - - This error means the webserver doesn't have write access to the current - directory. - - a. Make a webserver writeable cache directory - - Find the webserver's group. (on my system it is 'www') - - mkdir ./cache - chgrp www directory_name - chmod g+w directory_name - - (this is the best, and desired solution) - - b. Tell MagpieRSS to create the cache directory somewhere the webserver can - write to. - - define('MAGPIE_CACHE_DIR', '/tmp/magpierss'); - - (this is not a great solution, and might have security considerations) - - c. Turn off cacheing. - - Magpie can work fine with cacheing, but it will be slower, and you might - become a nuiance to the RSS provider, but it is an option. - - define('MAGPIE_CACHE_ON', 0); - - d. And lastly, do NOT - - chmod 777 ./cache - - Any of the above solutions are better then this. - - NOTE: If none of this works for you, let me know. I've got root, and a - custom compiled Apache on almost any box I ever touch, so I can be a little - out of touch with reality. But I won't know that if I don't feedback. - -************************************************************************* 3. -3. Fatal error: Failed to load PHP's XML Extension. - http://www.php.net/manual/en/ref.xml.php - - -or- - - Fatal error: Failed to create an instance of PHP's XML parser. - http://www.php.net/manual/en/ref.xml.php - - Make sure your PHP was built with --with-xml - - This has been turned on by default for several versions of PHP, but it might - be turned off in your build. - - See php.net for details on building and configuring PHP. - - -************************************************************************* -4. Warning: MagpieRSS: Failed to fetch index.rdf. - (HTTP Error: Invalid protocol "") - - You need to put http:// in front of your the URL to your RSS feed - -************************************************************************* -5. Warning: MagpieRSS: Failed to parse RSS file. - (not well-formed (invalid token) at line 19, column 98) - - There is a problem with the RSS feed you are trying to read. - MagpieRSS is an XML parser, and therefore can't parse RSS feed with invalid - characters. Some RSS parser are based on regular expressions, and can - parse invalid RSS but they have their own problems. - - You could try contacting the author of the RSS feed, and pointing them to - the online RSS validator at: - - http://feeds.archive.org/validator/ - -************************************************************************* -6. Warning: MagpieRSS: Failed to fetch http://example.com/index.rdf - (HTTP Response: HTTP/1.1 404 Not Found) - - Its a 404! The RSS file ain't there. - - diff --git a/tools/IRC_Bot/magpierss/extlib/Snoopy.class.inc b/tools/IRC_Bot/magpierss/extlib/Snoopy.class.inc deleted file mode 100644 index 532ecba10..000000000 --- a/tools/IRC_Bot/magpierss/extlib/Snoopy.class.inc +++ /dev/null @@ -1,899 +0,0 @@ - -Copyright (c): 1999-2000 ispi, all rights reserved -Version: 1.0 - - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -You may contact the author of Snoopy by e-mail at: -monte@ispi.net - -Or, write to: -Monte Ohrt -CTO, ispi -237 S. 70th suite 220 -Lincoln, NE 68510 - -The latest version of Snoopy can be obtained from: -http://snoopy.sourceforge.com - -*************************************************/ - -class Snoopy -{ - /**** Public variables ****/ - - /* user definable vars */ - - var $host = "www.php.net"; // host name we are connecting to - var $port = 80; // port we are connecting to - var $proxy_host = ""; // proxy host to use - var $proxy_port = ""; // proxy port to use - var $agent = "Snoopy v1.0"; // agent we masquerade as - var $referer = ""; // referer info to pass - var $cookies = array(); // array of cookies to pass - // $cookies["username"]="joe"; - var $rawheaders = array(); // array of raw headers to send - // $rawheaders["Content-type"]="text/html"; - - var $maxredirs = 5; // http redirection depth maximum. 0 = disallow - var $lastredirectaddr = ""; // contains address of last redirected address - var $offsiteok = true; // allows redirection off-site - var $maxframes = 0; // frame content depth maximum. 0 = disallow - var $expandlinks = true; // expand links to fully qualified URLs. - // this only applies to fetchlinks() - // or submitlinks() - var $passcookies = true; // pass set cookies back through redirects - // NOTE: this currently does not respect - // dates, domains or paths. - - var $user = ""; // user for http authentication - var $pass = ""; // password for http authentication - - // http accept types - var $accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"; - - var $results = ""; // where the content is put - - var $error = ""; // error messages sent here - var $response_code = ""; // response code returned from server - var $headers = array(); // headers returned from server sent here - var $maxlength = 500000; // max return data length (body) - var $read_timeout = 0; // timeout on read operations, in seconds - // supported only since PHP 4 Beta 4 - // set to 0 to disallow timeouts - var $timed_out = false; // if a read operation timed out - var $status = 0; // http request status - - var $curl_path = "/usr/bin/curl"; - // Snoopy will use cURL for fetching - // SSL content if a full system path to - // the cURL binary is supplied here. - // set to false if you do not have - // cURL installed. See http://curl.haxx.se - // for details on installing cURL. - // Snoopy does *not* use the cURL - // library functions built into php, - // as these functions are not stable - // as of this Snoopy release. - - // send Accept-encoding: gzip? - var $use_gzip = true; - - /**** Private variables ****/ - - var $_maxlinelen = 4096; // max line length (headers) - - var $_httpmethod = "GET"; // default http request method - var $_httpversion = "HTTP/1.0"; // default http request version - var $_submit_method = "POST"; // default submit method - var $_submit_type = "application/x-www-form-urlencoded"; // default submit type - var $_mime_boundary = ""; // MIME boundary for multipart/form-data submit type - var $_redirectaddr = false; // will be set if page fetched is a redirect - var $_redirectdepth = 0; // increments on an http redirect - var $_frameurls = array(); // frame src urls - var $_framedepth = 0; // increments on frame depth - - var $_isproxy = false; // set if using a proxy server - var $_fp_timeout = 30; // timeout for socket connection - -/*======================================================================*\ - Function: fetch - Purpose: fetch the contents of a web page - (and possibly other protocols in the - future like ftp, nntp, gopher, etc.) - Input: $URI the location of the page to fetch - Output: $this->results the output text from the fetch -\*======================================================================*/ - - function fetch($URI) - { - - //preg_match("|^([^:]+)://([^:/]+)(:[\d]+)*(.*)|",$URI,$URI_PARTS); - $URI_PARTS = parse_url($URI); - if (!empty($URI_PARTS["user"])) - $this->user = $URI_PARTS["user"]; - if (!empty($URI_PARTS["pass"])) - $this->pass = $URI_PARTS["pass"]; - - switch($URI_PARTS["scheme"]) - { - case "http": - $this->host = $URI_PARTS["host"]; - if(!empty($URI_PARTS["port"])) - $this->port = $URI_PARTS["port"]; - if($this->_connect($fp)) - { - if($this->_isproxy) - { - // using proxy, send entire URI - $this->_httprequest($URI,$fp,$URI,$this->_httpmethod); - } - else - { - $path = $URI_PARTS["path"].(isset($URI_PARTS["query"]) ? "?".$URI_PARTS["query"] : ""); - // no proxy, send only the path - $this->_httprequest($path, $fp, $URI, $this->_httpmethod); - } - - $this->_disconnect($fp); - - if($this->_redirectaddr) - { - /* url was redirected, check if we've hit the max depth */ - if($this->maxredirs > $this->_redirectdepth) - { - // only follow redirect if it's on this site, or offsiteok is true - if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) - { - /* follow the redirect */ - $this->_redirectdepth++; - $this->lastredirectaddr=$this->_redirectaddr; - $this->fetch($this->_redirectaddr); - } - } - } - - if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) - { - $frameurls = $this->_frameurls; - $this->_frameurls = array(); - - while(list(,$frameurl) = each($frameurls)) - { - if($this->_framedepth < $this->maxframes) - { - $this->fetch($frameurl); - $this->_framedepth++; - } - else - break; - } - } - } - else - { - return false; - } - return true; - break; - case "https": - if(!$this->curl_path || (!is_executable($this->curl_path))) { - $this->error = "Bad curl ($this->curl_path), can't fetch HTTPS \n"; - return false; - } - $this->host = $URI_PARTS["host"]; - if(!empty($URI_PARTS["port"])) - $this->port = $URI_PARTS["port"]; - if($this->_isproxy) - { - // using proxy, send entire URI - $this->_httpsrequest($URI,$URI,$this->_httpmethod); - } - else - { - $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); - // no proxy, send only the path - $this->_httpsrequest($path, $URI, $this->_httpmethod); - } - - if($this->_redirectaddr) - { - /* url was redirected, check if we've hit the max depth */ - if($this->maxredirs > $this->_redirectdepth) - { - // only follow redirect if it's on this site, or offsiteok is true - if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) - { - /* follow the redirect */ - $this->_redirectdepth++; - $this->lastredirectaddr=$this->_redirectaddr; - $this->fetch($this->_redirectaddr); - } - } - } - - if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) - { - $frameurls = $this->_frameurls; - $this->_frameurls = array(); - - while(list(,$frameurl) = each($frameurls)) - { - if($this->_framedepth < $this->maxframes) - { - $this->fetch($frameurl); - $this->_framedepth++; - } - else - break; - } - } - return true; - break; - default: - // not a valid protocol - $this->error = 'Invalid protocol "'.$URI_PARTS["scheme"].'"\n'; - return false; - break; - } - return true; - } - - - -/*======================================================================*\ - Private functions -\*======================================================================*/ - - -/*======================================================================*\ - Function: _striplinks - Purpose: strip the hyperlinks from an html document - Input: $document document to strip. - Output: $match an array of the links -\*======================================================================*/ - - function _striplinks($document) - { - preg_match_all("'<\s*a\s+.*href\s*=\s* # find ]+)) # if quote found, match up to next matching - # quote, otherwise match up to next space - 'isx",$document,$links); - - - // catenate the non-empty matches from the conditional subpattern - - while(list($key,$val) = each($links[2])) - { - if(!empty($val)) - $match[] = $val; - } - - while(list($key,$val) = each($links[3])) - { - if(!empty($val)) - $match[] = $val; - } - - // return the links - return $match; - } - -/*======================================================================*\ - Function: _stripform - Purpose: strip the form elements from an html document - Input: $document document to strip. - Output: $match an array of the links -\*======================================================================*/ - - function _stripform($document) - { - preg_match_all("'<\/?(FORM|INPUT|SELECT|TEXTAREA|(OPTION))[^<>]*>(?(2)(.*(?=<\/?(option|select)[^<>]*>[\r\n]*)|(?=[\r\n]*))|(?=[\r\n]*))'Usi",$document,$elements); - - // catenate the matches - $match = implode("\r\n",$elements[0]); - - // return the links - return $match; - } - - - -/*======================================================================*\ - Function: _striptext - Purpose: strip the text from an html document - Input: $document document to strip. - Output: $text the resulting text -\*======================================================================*/ - - function _striptext($document) - { - - // I didn't use preg eval (//e) since that is only available in PHP 4.0. - // so, list your entities one by one here. I included some of the - // more common ones. - - $search = array("']*?>.*?'si", // strip out javascript - "'<[\/\!]*?[^<>]*?>'si", // strip out html tags - "'([\r\n])[\s]+'", // strip out white space - "'&(quote|#34);'i", // replace html entities - "'&(amp|#38);'i", - "'&(lt|#60);'i", - "'&(gt|#62);'i", - "'&(nbsp|#160);'i", - "'&(iexcl|#161);'i", - "'&(cent|#162);'i", - "'&(pound|#163);'i", - "'&(copy|#169);'i" - ); - $replace = array( "", - "", - "\\1", - "\"", - "&", - "<", - ">", - " ", - chr(161), - chr(162), - chr(163), - chr(169)); - - $text = preg_replace($search,$replace,$document); - - return $text; - } - -/*======================================================================*\ - Function: _expandlinks - Purpose: expand each link into a fully qualified URL - Input: $links the links to qualify - $URI the full URI to get the base from - Output: $expandedLinks the expanded links -\*======================================================================*/ - - function _expandlinks($links,$URI) - { - - preg_match("/^[^\?]+/",$URI,$match); - - $match = preg_replace("|/[^\/\.]+\.[^\/\.]+$|","",$match[0]); - - $search = array( "|^http://".preg_quote($this->host)."|i", - "|^(?!http://)(\/)?(?!mailto:)|i", - "|/\./|", - "|/[^\/]+/\.\./|" - ); - - $replace = array( "", - $match."/", - "/", - "/" - ); - - $expandedLinks = preg_replace($search,$replace,$links); - - return $expandedLinks; - } - -/*======================================================================*\ - Function: _httprequest - Purpose: go get the http data from the server - Input: $url the url to fetch - $fp the current open file pointer - $URI the full URI - $body body contents to send if any (POST) - Output: -\*======================================================================*/ - - function _httprequest($url,$fp,$URI,$http_method,$content_type="",$body="") - { - if($this->passcookies && $this->_redirectaddr) - $this->setcookies(); - - $URI_PARTS = parse_url($URI); - if(empty($url)) - $url = "/"; - $headers = $http_method." ".$url." ".$this->_httpversion."\r\n"; - if(!empty($this->agent)) - $headers .= "User-Agent: ".$this->agent."\r\n"; - if(!empty($this->host) && !isset($this->rawheaders['Host'])) - $headers .= "Host: ".$this->host."\r\n"; - if(!empty($this->accept)) - $headers .= "Accept: ".$this->accept."\r\n"; - - if($this->use_gzip) { - // make sure PHP was built with --with-zlib - // and we can handle gzipp'ed data - if ( function_exists(gzinflate) ) { - $headers .= "Accept-encoding: gzip\r\n"; - } - else { - trigger_error( - "use_gzip is on, but PHP was built without zlib support.". - " Requesting file(s) without gzip encoding.", - E_USER_NOTICE); - } - } - - if(!empty($this->referer)) - $headers .= "Referer: ".$this->referer."\r\n"; - if(!empty($this->cookies)) - { - if(!is_array($this->cookies)) - $this->cookies = (array)$this->cookies; - - reset($this->cookies); - if ( count($this->cookies) > 0 ) { - $cookie_headers .= 'Cookie: '; - foreach ( $this->cookies as $cookieKey => $cookieVal ) { - $cookie_headers .= $cookieKey."=".urlencode($cookieVal)."; "; - } - $headers .= substr($cookie_headers,0,-2) . "\r\n"; - } - } - if(!empty($this->rawheaders)) - { - if(!is_array($this->rawheaders)) - $this->rawheaders = (array)$this->rawheaders; - while(list($headerKey,$headerVal) = each($this->rawheaders)) - $headers .= $headerKey.": ".$headerVal."\r\n"; - } - if(!empty($content_type)) { - $headers .= "Content-type: $content_type"; - if ($content_type == "multipart/form-data") - $headers .= "; boundary=".$this->_mime_boundary; - $headers .= "\r\n"; - } - if(!empty($body)) - $headers .= "Content-length: ".strlen($body)."\r\n"; - if(!empty($this->user) || !empty($this->pass)) - $headers .= "Authorization: BASIC ".base64_encode($this->user.":".$this->pass)."\r\n"; - - $headers .= "\r\n"; - - // set the read timeout if needed - if ($this->read_timeout > 0) - socket_set_timeout($fp, $this->read_timeout); - $this->timed_out = false; - - fwrite($fp,$headers.$body,strlen($headers.$body)); - - $this->_redirectaddr = false; - unset($this->headers); - - // content was returned gzip encoded? - $is_gzipped = false; - - while($currentHeader = fgets($fp,$this->_maxlinelen)) - { - if ($this->read_timeout > 0 && $this->_check_timeout($fp)) - { - $this->status=-100; - return false; - } - - // if($currentHeader == "\r\n") - if(preg_match("/^\r?\n$/", $currentHeader) ) - break; - - // if a header begins with Location: or URI:, set the redirect - if(preg_match("/^(Location:|URI:)/i",$currentHeader)) - { - // get URL portion of the redirect - preg_match("/^(Location:|URI:)\s+(.*)/",chop($currentHeader),$matches); - // look for :// in the Location header to see if hostname is included - if(!preg_match("|\:\/\/|",$matches[2])) - { - // no host in the path, so prepend - $this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port; - // eliminate double slash - if(!preg_match("|^/|",$matches[2])) - $this->_redirectaddr .= "/".$matches[2]; - else - $this->_redirectaddr .= $matches[2]; - } - else - $this->_redirectaddr = $matches[2]; - } - - if(preg_match("|^HTTP/|",$currentHeader)) - { - if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$currentHeader, $status)) - { - $this->status= $status[1]; - } - $this->response_code = $currentHeader; - } - - if (preg_match("/Content-Encoding: gzip/", $currentHeader) ) { - $is_gzipped = true; - } - - $this->headers[] = $currentHeader; - } - - # $results = fread($fp, $this->maxlength); - $results = ""; - while ( $data = fread($fp, $this->maxlength) ) { - $results .= $data; - if ( - strlen($results) > $this->maxlength ) { - break; - } - } - - // gunzip - if ( $is_gzipped ) { - // per http://www.php.net/manual/en/function.gzencode.php - $results = substr($results, 10); - $results = gzinflate($results); - } - - if ($this->read_timeout > 0 && $this->_check_timeout($fp)) - { - $this->status=-100; - return false; - } - - // check if there is a a redirect meta tag - - if(preg_match("']*?content[\s]*=[\s]*[\"\']?\d+;[\s]+URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match)) - { - $this->_redirectaddr = $this->_expandlinks($match[1],$URI); - } - - // have we hit our frame depth and is there frame src to fetch? - if(($this->_framedepth < $this->maxframes) && preg_match_all("']+)'i",$results,$match)) - { - $this->results[] = $results; - for($x=0; $x_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host); - } - // have we already fetched framed content? - elseif(is_array($this->results)) - $this->results[] = $results; - // no framed content - else - $this->results = $results; - - return true; - } - -/*======================================================================*\ - Function: _httpsrequest - Purpose: go get the https data from the server using curl - Input: $url the url to fetch - $URI the full URI - $body body contents to send if any (POST) - Output: -\*======================================================================*/ - - function _httpsrequest($url,$URI,$http_method,$content_type="",$body="") - { - if($this->passcookies && $this->_redirectaddr) - $this->setcookies(); - - $headers = array(); - - $URI_PARTS = parse_url($URI); - if(empty($url)) - $url = "/"; - // GET ... header not needed for curl - //$headers[] = $http_method." ".$url." ".$this->_httpversion; - if(!empty($this->agent)) - $headers[] = "User-Agent: ".$this->agent; - if(!empty($this->host)) - $headers[] = "Host: ".$this->host; - if(!empty($this->accept)) - $headers[] = "Accept: ".$this->accept; - if(!empty($this->referer)) - $headers[] = "Referer: ".$this->referer; - if(!empty($this->cookies)) - { - if(!is_array($this->cookies)) - $this->cookies = (array)$this->cookies; - - reset($this->cookies); - if ( count($this->cookies) > 0 ) { - $cookie_str = 'Cookie: '; - foreach ( $this->cookies as $cookieKey => $cookieVal ) { - $cookie_str .= $cookieKey."=".urlencode($cookieVal)."; "; - } - $headers[] = substr($cookie_str,0,-2); - } - } - if(!empty($this->rawheaders)) - { - if(!is_array($this->rawheaders)) - $this->rawheaders = (array)$this->rawheaders; - while(list($headerKey,$headerVal) = each($this->rawheaders)) - $headers[] = $headerKey.": ".$headerVal; - } - if(!empty($content_type)) { - if ($content_type == "multipart/form-data") - $headers[] = "Content-type: $content_type; boundary=".$this->_mime_boundary; - else - $headers[] = "Content-type: $content_type"; - } - if(!empty($body)) - $headers[] = "Content-length: ".strlen($body); - if(!empty($this->user) || !empty($this->pass)) - $headers[] = "Authorization: BASIC ".base64_encode($this->user.":".$this->pass); - - for($curr_header = 0; $curr_header < count($headers); $curr_header++) - $cmdline_params .= " -H \"".$headers[$curr_header]."\""; - - if(!empty($body)) - $cmdline_params .= " -d \"$body\""; - - if($this->read_timeout > 0) - $cmdline_params .= " -m ".$this->read_timeout; - - $headerfile = uniqid(time()); - - # accept self-signed certs - $cmdline_params .= " -k"; - exec($this->curl_path." -D \"/tmp/$headerfile\"".$cmdline_params." ".$URI,$results,$return); - - if($return) - { - $this->error = "Error: cURL could not retrieve the document, error $return."; - return false; - } - - - $results = implode("\r\n",$results); - - $result_headers = file("/tmp/$headerfile"); - - $this->_redirectaddr = false; - unset($this->headers); - - for($currentHeader = 0; $currentHeader < count($result_headers); $currentHeader++) - { - - // if a header begins with Location: or URI:, set the redirect - if(preg_match("/^(Location: |URI: )/i",$result_headers[$currentHeader])) - { - // get URL portion of the redirect - preg_match("/^(Location: |URI:)(.*)/",chop($result_headers[$currentHeader]),$matches); - // look for :// in the Location header to see if hostname is included - if(!preg_match("|\:\/\/|",$matches[2])) - { - // no host in the path, so prepend - $this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port; - // eliminate double slash - if(!preg_match("|^/|",$matches[2])) - $this->_redirectaddr .= "/".$matches[2]; - else - $this->_redirectaddr .= $matches[2]; - } - else - $this->_redirectaddr = $matches[2]; - } - - if(preg_match("|^HTTP/|",$result_headers[$currentHeader])) - { - $this->response_code = $result_headers[$currentHeader]; - if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$this->response_code, $match)) - { - $this->status= $match[1]; - } - } - $this->headers[] = $result_headers[$currentHeader]; - } - - // check if there is a a redirect meta tag - - if(preg_match("']*?content[\s]*=[\s]*[\"\']?\d+;[\s]+URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match)) - { - $this->_redirectaddr = $this->_expandlinks($match[1],$URI); - } - - // have we hit our frame depth and is there frame src to fetch? - if(($this->_framedepth < $this->maxframes) && preg_match_all("']+)'i",$results,$match)) - { - $this->results[] = $results; - for($x=0; $x_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host); - } - // have we already fetched framed content? - elseif(is_array($this->results)) - $this->results[] = $results; - // no framed content - else - $this->results = $results; - - unlink("/tmp/$headerfile"); - - return true; - } - -/*======================================================================*\ - Function: setcookies() - Purpose: set cookies for a redirection -\*======================================================================*/ - - function setcookies() - { - for($x=0; $xheaders); $x++) - { - if(preg_match("/^set-cookie:[\s]+([^=]+)=([^;]+)/i", $this->headers[$x],$match)) - $this->cookies[$match[1]] = $match[2]; - } - } - - -/*======================================================================*\ - Function: _check_timeout - Purpose: checks whether timeout has occurred - Input: $fp file pointer -\*======================================================================*/ - - function _check_timeout($fp) - { - if ($this->read_timeout > 0) { - $fp_status = socket_get_status($fp); - if ($fp_status["timed_out"]) { - $this->timed_out = true; - return true; - } - } - return false; - } - -/*======================================================================*\ - Function: _connect - Purpose: make a socket connection - Input: $fp file pointer -\*======================================================================*/ - - function _connect(&$fp) - { - if(!empty($this->proxy_host) && !empty($this->proxy_port)) - { - $this->_isproxy = true; - $host = $this->proxy_host; - $port = $this->proxy_port; - } - else - { - $host = $this->host; - $port = $this->port; - } - - $this->status = 0; - - if($fp = fsockopen( - $host, - $port, - $errno, - $errstr, - $this->_fp_timeout - )) - { - // socket connection succeeded - - return true; - } - else - { - // socket connection failed - $this->status = $errno; - switch($errno) - { - case -3: - $this->error="socket creation failed (-3)"; - case -4: - $this->error="dns lookup failure (-4)"; - case -5: - $this->error="connection refused or timed out (-5)"; - default: - $this->error="connection failed (".$errno.")"; - } - return false; - } - } -/*======================================================================*\ - Function: _disconnect - Purpose: disconnect a socket connection - Input: $fp file pointer -\*======================================================================*/ - - function _disconnect($fp) - { - return(fclose($fp)); - } - - -/*======================================================================*\ - Function: _prepare_post_body - Purpose: Prepare post body according to encoding type - Input: $formvars - form variables - $formfiles - form upload files - Output: post body -\*======================================================================*/ - - function _prepare_post_body($formvars, $formfiles) - { - settype($formvars, "array"); - settype($formfiles, "array"); - - if (count($formvars) == 0 && count($formfiles) == 0) - return; - - switch ($this->_submit_type) { - case "application/x-www-form-urlencoded": - reset($formvars); - while(list($key,$val) = each($formvars)) { - if (is_array($val) || is_object($val)) { - while (list($cur_key, $cur_val) = each($val)) { - $postdata .= urlencode($key)."[]=".urlencode($cur_val)."&"; - } - } else - $postdata .= urlencode($key)."=".urlencode($val)."&"; - } - break; - - case "multipart/form-data": - $this->_mime_boundary = "Snoopy".md5(uniqid(microtime())); - - reset($formvars); - while(list($key,$val) = each($formvars)) { - if (is_array($val) || is_object($val)) { - while (list($cur_key, $cur_val) = each($val)) { - $postdata .= "--".$this->_mime_boundary."\r\n"; - $postdata .= "Content-Disposition: form-data; name=\"$key\[\]\"\r\n\r\n"; - $postdata .= "$cur_val\r\n"; - } - } else { - $postdata .= "--".$this->_mime_boundary."\r\n"; - $postdata .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n"; - $postdata .= "$val\r\n"; - } - } - - reset($formfiles); - while (list($field_name, $file_names) = each($formfiles)) { - settype($file_names, "array"); - while (list(, $file_name) = each($file_names)) { - if (!is_readable($file_name)) continue; - - $fp = fopen($file_name, "r"); - $file_content = fread($fp, filesize($file_name)); - fclose($fp); - $base_name = basename($file_name); - - $postdata .= "--".$this->_mime_boundary."\r\n"; - $postdata .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$base_name\"\r\n\r\n"; - $postdata .= "$file_content\r\n"; - } - } - $postdata .= "--".$this->_mime_boundary."--\r\n"; - break; - } - - return $postdata; - } -} - -?> diff --git a/tools/IRC_Bot/magpierss/rss_cache.inc b/tools/IRC_Bot/magpierss/rss_cache.inc deleted file mode 100644 index fdfa5dd25..000000000 --- a/tools/IRC_Bot/magpierss/rss_cache.inc +++ /dev/null @@ -1,184 +0,0 @@ - - * Version: 0.51 - * License: GPL - * - * The lastest version of MagpieRSS can be obtained from: - * http://magpierss.sourceforge.net - * - * For questions, help, comments, discussion, etc., please join the - * Magpie mailing list: - * http://lists.sourceforge.net/lists/listinfo/magpierss-general - * - */ - -class RSSCache { - var $BASE_CACHE = './cache'; // where the cache files are stored - var $MAX_AGE = 3600; // when are files stale, default one hour - var $ERROR = ""; // accumulate error messages - - function RSSCache ($base='', $age='') { - if ( $base ) { - $this->BASE_CACHE = $base; - } - if ( $age ) { - $this->MAX_AGE = $age; - } - - // attempt to make the cache directory - if ( ! file_exists( $this->BASE_CACHE ) ) { - $status = @mkdir( $this->BASE_CACHE, 0755 ); - - // if make failed - if ( ! $status ) { - $this->error( - "Cache couldn't make dir '" . $this->BASE_CACHE . "'." - ); - } - } - } - -/*=======================================================================*\ - Function: set - Purpose: add an item to the cache, keyed on url - Input: url from wich the rss file was fetched - Output: true on sucess -\*=======================================================================*/ - function set ($url, $rss) { - $this->ERROR = ""; - $cache_file = $this->file_name( $url ); - $fp = @fopen( $cache_file, 'w' ); - - if ( ! $fp ) { - $this->error( - "Cache unable to open file for writing: $cache_file" - ); - return 0; - } - - - $data = $this->serialize( $rss ); - fwrite( $fp, $data ); - fclose( $fp ); - - return $cache_file; - } - -/*=======================================================================*\ - Function: get - Purpose: fetch an item from the cache - Input: url from wich the rss file was fetched - Output: cached object on HIT, false on MISS -\*=======================================================================*/ - function get ($url) { - $this->ERROR = ""; - $cache_file = $this->file_name( $url ); - - if ( ! file_exists( $cache_file ) ) { - $this->debug( - "Cache doesn't contain: $url (cache file: $cache_file)" - ); - return 0; - } - - $fp = @fopen($cache_file, 'r'); - if ( ! $fp ) { - $this->error( - "Failed to open cache file for reading: $cache_file" - ); - return 0; - } - - $data = fread( $fp, filesize($cache_file) ); - $rss = $this->unserialize( $data ); - - return $rss; - } - -/*=======================================================================*\ - Function: check_cache - Purpose: check a url for membership in the cache - and whether the object is older then MAX_AGE (ie. STALE) - Input: url from wich the rss file was fetched - Output: cached object on HIT, false on MISS -\*=======================================================================*/ - function check_cache ( $url ) { - $this->ERROR = ""; - $filename = $this->file_name( $url ); - - if ( file_exists( $filename ) ) { - // find how long ago the file was added to the cache - // and whether that is longer then MAX_AGE - $mtime = filemtime( $filename ); - $age = time() - $mtime; - if ( $this->MAX_AGE > $age ) { - // object exists and is current - return 'HIT'; - } - else { - // object exists but is old - return 'STALE'; - } - } - else { - // object does not exist - return 'MISS'; - } - } - -/*=======================================================================*\ - Function: serialize -\*=======================================================================*/ - function serialize ( $rss ) { - return serialize( $rss ); - } - -/*=======================================================================*\ - Function: unserialize -\*=======================================================================*/ - function unserialize ( $data ) { - return unserialize( $data ); - } - -/*=======================================================================*\ - Function: file_name - Purpose: map url to location in cache - Input: url from wich the rss file was fetched - Output: a file name -\*=======================================================================*/ - function file_name ($url) { - $filename = md5( $url ); - return join( DIRECTORY_SEPARATOR, array( $this->BASE_CACHE, $filename ) ); - } - -/*=======================================================================*\ - Function: error - Purpose: register error -\*=======================================================================*/ - function error ($errormsg, $lvl=E_USER_WARNING) { - // append PHP's error message if track_errors enabled - if ( isset($php_errormsg) ) { - $errormsg .= " ($php_errormsg)"; - } - $this->ERROR = $errormsg; - if ( MAGPIE_DEBUG ) { - trigger_error( $errormsg, $lvl); - } - else { - error_log( $errormsg, 0); - } - } - - function debug ($debugmsg, $lvl=E_USER_NOTICE) { - if ( MAGPIE_DEBUG ) { - $this->error("MagpieRSS [debug] $debugmsg", $lvl); - } - } - -} - -?> diff --git a/tools/IRC_Bot/magpierss/rss_fetch.inc b/tools/IRC_Bot/magpierss/rss_fetch.inc deleted file mode 100644 index c1098d681..000000000 --- a/tools/IRC_Bot/magpierss/rss_fetch.inc +++ /dev/null @@ -1,458 +0,0 @@ - - * License: GPL - * - * The lastest version of MagpieRSS can be obtained from: - * http://magpierss.sourceforge.net - * - * For questions, help, comments, discussion, etc., please join the - * Magpie mailing list: - * magpierss-general@lists.sourceforge.net - * - */ - -// Setup MAGPIE_DIR for use on hosts that don't include -// the current path in include_path. -// with thanks to rajiv and smarty -if (!defined('DIR_SEP')) { - define('DIR_SEP', DIRECTORY_SEPARATOR); -} - -if (!defined('MAGPIE_DIR')) { - define('MAGPIE_DIR', dirname(__FILE__) . DIR_SEP); -} - -require_once( MAGPIE_DIR . 'rss_parse.inc' ); -require_once( MAGPIE_DIR . 'rss_cache.inc' ); - -// for including 3rd party libraries -define('MAGPIE_EXTLIB', MAGPIE_DIR . 'extlib' . DIR_SEP); -require_once( MAGPIE_EXTLIB . 'Snoopy.class.inc'); - - -/* - * CONSTANTS - redefine these in your script to change the - * behaviour of fetch_rss() currently, most options effect the cache - * - * MAGPIE_CACHE_ON - Should Magpie cache parsed RSS objects? - * For me a built in cache was essential to creating a "PHP-like" - * feel to Magpie, see rss_cache.inc for rationale - * - * - * MAGPIE_CACHE_DIR - Where should Magpie cache parsed RSS objects? - * This should be a location that the webserver can write to. If this - * directory does not already exist Mapie will try to be smart and create - * it. This will often fail for permissions reasons. - * - * - * MAGPIE_CACHE_AGE - How long to store cached RSS objects? In seconds. - * - * - * MAGPIE_CACHE_FRESH_ONLY - If remote fetch fails, throw error - * instead of returning stale object? - * - * MAGPIE_DEBUG - Display debugging notices? - * -*/ - - -/*=======================================================================*\ - Function: fetch_rss: - Purpose: return RSS object for the give url - maintain the cache - Input: url of RSS file - Output: parsed RSS object (see rss_parse.inc) - - NOTES ON CACHEING: - If caching is on (MAGPIE_CACHE_ON) fetch_rss will first check the cache. - - NOTES ON RETRIEVING REMOTE FILES: - If conditional gets are on (MAGPIE_CONDITIONAL_GET_ON) fetch_rss will - return a cached object, and touch the cache object upon recieving a - 304. - - NOTES ON FAILED REQUESTS: - If there is an HTTP error while fetching an RSS object, the cached - version will be return, if it exists (and if MAGPIE_CACHE_FRESH_ONLY is off) -\*=======================================================================*/ - -define('MAGPIE_VERSION', '0.7'); - -$MAGPIE_ERROR = ""; - -function fetch_rss ($url) { - // initialize constants - init(); - - if ( !isset($url) ) { - error("fetch_rss called without a url"); - return false; - } - - // if cache is disabled - if ( !MAGPIE_CACHE_ON ) { - // fetch file, and parse it - $resp = _fetch_remote_file( $url ); - if ( is_success( $resp->status ) ) { - return _response_to_rss( $resp ); - } - else { - error("Failed to fetch $url and cache is off"); - return false; - } - } - // else cache is ON - else { - // Flow - // 1. check cache - // 2. if there is a hit, make sure its fresh - // 3. if cached obj fails freshness check, fetch remote - // 4. if remote fails, return stale object, or error - - $cache = new RSSCache( MAGPIE_CACHE_DIR, MAGPIE_CACHE_AGE ); - - if (MAGPIE_DEBUG and $cache->ERROR) { - debug($cache->ERROR, E_USER_WARNING); - } - - - $cache_status = 0; // response of check_cache - $request_headers = array(); // HTTP headers to send with fetch - $rss = 0; // parsed RSS object - $errormsg = 0; // errors, if any - - // store parsed XML by desired output encoding - // as character munging happens at parse time - $cache_key = $url . MAGPIE_OUTPUT_ENCODING; - - if (!$cache->ERROR) { - // return cache HIT, MISS, or STALE - $cache_status = $cache->check_cache( $cache_key); - } - - // if object cached, and cache is fresh, return cached obj - if ( $cache_status == 'HIT' ) { - $rss = $cache->get( $cache_key ); - if ( isset($rss) and $rss ) { - // should be cache age - $rss->from_cache = 1; - if ( MAGPIE_DEBUG > 1) { - debug("MagpieRSS: Cache HIT", E_USER_NOTICE); - } - return $rss; - } - } - - // else attempt a conditional get - - // setup headers - if ( $cache_status == 'STALE' ) { - $rss = $cache->get( $cache_key ); - if ( $rss and $rss->etag and $rss->last_modified ) { - $request_headers['If-None-Match'] = $rss->etag; - $request_headers['If-Last-Modified'] = $rss->last_modified; - } - } - - $resp = _fetch_remote_file( $url, $request_headers ); - - if (isset($resp) and $resp) { - if ($resp->status == '304' ) { - // we have the most current copy - if ( MAGPIE_DEBUG > 1) { - debug("Got 304 for $url"); - } - // reset cache on 304 (at minutillo insistent prodding) - $cache->set($cache_key, $rss); - return $rss; - } - elseif ( is_success( $resp->status ) ) { - $rss = _response_to_rss( $resp ); - if ( $rss ) { - if (MAGPIE_DEBUG > 1) { - debug("Fetch successful"); - } - // add object to cache - $cache->set( $cache_key, $rss ); - return $rss; - } - } - else { - $errormsg = "Failed to fetch $url "; - if ( $resp->status == '-100' ) { - $errormsg .= "(Request timed out after " . MAGPIE_FETCH_TIME_OUT . " seconds)"; - } - elseif ( $resp->error ) { - # compensate for Snoopy's annoying habbit to tacking - # on '\n' - $http_error = substr($resp->error, 0, -2); - $errormsg .= "(HTTP Error: $http_error)"; - } - else { - $errormsg .= "(HTTP Response: " . $resp->response_code .')'; - } - } - } - else { - $errormsg = "Unable to retrieve RSS file for unknown reasons."; - } - - // else fetch failed - - // attempt to return cached object - if ($rss) { - if ( MAGPIE_DEBUG ) { - debug("Returning STALE object for $url"); - } - return $rss; - } - - // else we totally failed - error( $errormsg ); - - return false; - - } // end if ( !MAGPIE_CACHE_ON ) { -} // end fetch_rss() - -/*=======================================================================*\ - Function: error - Purpose: set MAGPIE_ERROR, and trigger error -\*=======================================================================*/ - -function error ($errormsg, $lvl=E_USER_WARNING) { - global $MAGPIE_ERROR; - - // append PHP's error message if track_errors enabled - if ( isset($php_errormsg) ) { - $errormsg .= " ($php_errormsg)"; - } - if ( $errormsg ) { - $errormsg = "MagpieRSS: $errormsg"; - $MAGPIE_ERROR = $errormsg; - trigger_error( $errormsg, $lvl); - } -} - -function debug ($debugmsg, $lvl=E_USER_NOTICE) { - trigger_error("MagpieRSS [debug] $debugmsg", $lvl); -} - -/*=======================================================================*\ - Function: magpie_error - Purpose: accessor for the magpie error variable -\*=======================================================================*/ -function magpie_error ($errormsg="") { - global $MAGPIE_ERROR; - - if ( isset($errormsg) and $errormsg ) { - $MAGPIE_ERROR = $errormsg; - } - - return $MAGPIE_ERROR; -} - -/*=======================================================================*\ - Function: _fetch_remote_file - Purpose: retrieve an arbitrary remote file - Input: url of the remote file - headers to send along with the request (optional) - Output: an HTTP response object (see Snoopy.class.inc) -\*=======================================================================*/ -function _fetch_remote_file ($url, $headers = "" ) { - // Snoopy is an HTTP client in PHP - $client = new Snoopy(); - $client->agent = MAGPIE_USER_AGENT; - $client->read_timeout = MAGPIE_FETCH_TIME_OUT; - $client->use_gzip = MAGPIE_USE_GZIP; - if (is_array($headers) ) { - $client->rawheaders = $headers; - } - - @$client->fetch($url); - return $client; - -} - -/*=======================================================================*\ - Function: _response_to_rss - Purpose: parse an HTTP response object into an RSS object - Input: an HTTP response object (see Snoopy) - Output: parsed RSS object (see rss_parse) -\*=======================================================================*/ -function _response_to_rss ($resp) { - $rss = new MagpieRSS( $resp->results, MAGPIE_OUTPUT_ENCODING, MAGPIE_INPUT_ENCODING, MAGPIE_DETECT_ENCODING ); - - // if RSS parsed successfully - if ( $rss and !$rss->ERROR) { - - // find Etag, and Last-Modified - foreach($resp->headers as $h) { - // 2003-03-02 - Nicola Asuni (www.tecnick.com) - fixed bug "Undefined offset: 1" - if (strpos($h, ": ")) { - list($field, $val) = explode(": ", $h, 2); - } - else { - $field = $h; - $val = ""; - } - - if ( $field == 'ETag' ) { - $rss->etag = $val; - } - - if ( $field == 'Last-Modified' ) { - $rss->last_modified = $val; - } - } - - return $rss; - } // else construct error message - else { - $errormsg = "Failed to parse RSS file."; - - if ($rss) { - $errormsg .= " (" . $rss->ERROR . ")"; - } - error($errormsg); - - return false; - } // end if ($rss and !$rss->error) -} - -/*=======================================================================*\ - Function: init - Purpose: setup constants with default values - check for user overrides -\*=======================================================================*/ -function init () { - if ( defined('MAGPIE_INITALIZED') ) { - return; - } - else { - define('MAGPIE_INITALIZED', true); - } - - if ( !defined('MAGPIE_CACHE_ON') ) { - define('MAGPIE_CACHE_ON', true); - } - - if ( !defined('MAGPIE_CACHE_DIR') ) { - define('MAGPIE_CACHE_DIR', './cache'); - } - - if ( !defined('MAGPIE_CACHE_AGE') ) { - define('MAGPIE_CACHE_AGE', 60*60); // one hour - } - - if ( !defined('MAGPIE_CACHE_FRESH_ONLY') ) { - define('MAGPIE_CACHE_FRESH_ONLY', false); - } - - if ( !defined('MAGPIE_OUTPUT_ENCODING') ) { - define('MAGPIE_OUTPUT_ENCODING', 'ISO-8859-1'); - } - - if ( !defined('MAGPIE_INPUT_ENCODING') ) { - define('MAGPIE_INPUT_ENCODING', null); - } - - if ( !defined('MAGPIE_DETECT_ENCODING') ) { - define('MAGPIE_DETECT_ENCODING', true); - } - - if ( !defined('MAGPIE_DEBUG') ) { - define('MAGPIE_DEBUG', 0); - } - - if ( !defined('MAGPIE_USER_AGENT') ) { - $ua = 'MagpieRSS/'. MAGPIE_VERSION . ' (+http://magpierss.sf.net'; - - if ( MAGPIE_CACHE_ON ) { - $ua = $ua . ')'; - } - else { - $ua = $ua . '; No cache)'; - } - - define('MAGPIE_USER_AGENT', $ua); - } - - if ( !defined('MAGPIE_FETCH_TIME_OUT') ) { - define('MAGPIE_FETCH_TIME_OUT', 5); // 5 second timeout - } - - // use gzip encoding to fetch rss files if supported? - if ( !defined('MAGPIE_USE_GZIP') ) { - define('MAGPIE_USE_GZIP', true); - } -} - -// NOTE: the following code should really be in Snoopy, or at least -// somewhere other then rss_fetch! - -/*=======================================================================*\ - HTTP STATUS CODE PREDICATES - These functions attempt to classify an HTTP status code - based on RFC 2616 and RFC 2518. - - All of them take an HTTP status code as input, and return true or false - - All this code is adapted from LWP's HTTP::Status. -\*=======================================================================*/ - - -/*=======================================================================*\ - Function: is_info - Purpose: return true if Informational status code -\*=======================================================================*/ -function is_info ($sc) { - return $sc >= 100 && $sc < 200; -} - -/*=======================================================================*\ - Function: is_success - Purpose: return true if Successful status code -\*=======================================================================*/ -function is_success ($sc) { - return $sc >= 200 && $sc < 300; -} - -/*=======================================================================*\ - Function: is_redirect - Purpose: return true if Redirection status code -\*=======================================================================*/ -function is_redirect ($sc) { - return $sc >= 300 && $sc < 400; -} - -/*=======================================================================*\ - Function: is_error - Purpose: return true if Error status code -\*=======================================================================*/ -function is_error ($sc) { - return $sc >= 400 && $sc < 600; -} - -/*=======================================================================*\ - Function: is_client_error - Purpose: return true if Error status code, and its a client error -\*=======================================================================*/ -function is_client_error ($sc) { - return $sc >= 400 && $sc < 500; -} - -/*=======================================================================*\ - Function: is_client_error - Purpose: return true if Error status code, and its a server error -\*=======================================================================*/ -function is_server_error ($sc) { - return $sc >= 500 && $sc < 600; -} - -?> diff --git a/tools/IRC_Bot/magpierss/rss_parse.inc b/tools/IRC_Bot/magpierss/rss_parse.inc deleted file mode 100644 index af4020ebf..000000000 --- a/tools/IRC_Bot/magpierss/rss_parse.inc +++ /dev/null @@ -1,589 +0,0 @@ - -* @version 0.7a -* @license GPL -* -*/ - -define('RSS', 'RSS'); -define('ATOM', 'Atom'); - -require_once (MAGPIE_DIR . 'rss_utils.inc'); - -/** -* Hybrid parser, and object, takes RSS as a string and returns a simple object. -* -* see: rss_fetch.inc for a simpler interface with integrated caching support -* -*/ -class MagpieRSS { - var $parser; - - var $current_item = array(); // item currently being parsed - var $items = array(); // collection of parsed items - var $channel = array(); // hash of channel fields - var $textinput = array(); - var $image = array(); - var $feed_type; - var $feed_version; - var $encoding = ''; // output encoding of parsed rss - - var $_source_encoding = ''; // only set if we have to parse xml prolog - - var $ERROR = ""; - var $WARNING = ""; - - // define some constants - - var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright'); - var $_KNOWN_ENCODINGS = array('UTF-8', 'US-ASCII', 'ISO-8859-1'); - - // parser variables, useless if you're not a parser, treat as private - var $stack = array(); // parser stack - var $inchannel = false; - var $initem = false; - var $incontent = false; // if in Atom field - var $intextinput = false; - var $inimage = false; - var $current_field = ''; - var $current_namespace = false; - - - /** - * Set up XML parser, parse source, and return populated RSS object.. - * - * @param string $source string containing the RSS to be parsed - * - * NOTE: Probably a good idea to leave the encoding options alone unless - * you know what you're doing as PHP's character set support is - * a little weird. - * - * NOTE: A lot of this is unnecessary but harmless with PHP5 - * - * - * @param string $output_encoding output the parsed RSS in this character - * set defaults to ISO-8859-1 as this is PHP's - * default. - * - * NOTE: might be changed to UTF-8 in future - * versions. - * - * @param string $input_encoding the character set of the incoming RSS source. - * Leave blank and Magpie will try to figure it - * out. - * - * - * @param bool $detect_encoding if false Magpie won't attempt to detect - * source encoding. (caveat emptor) - * - */ - function MagpieRSS ($source, $output_encoding='ISO-8859-1', - $input_encoding=null, $detect_encoding=true) - { - # if PHP xml isn't compiled in, die - # - if (!function_exists('xml_parser_create')) { - $this->error( "Failed to load PHP's XML Extension. " . - "http://www.php.net/manual/en/ref.xml.php", - E_USER_ERROR ); - } - - list($parser, $source) = $this->create_parser($source, - $output_encoding, $input_encoding, $detect_encoding); - - - if (!is_resource($parser)) { - $this->error( "Failed to create an instance of PHP's XML parser. " . - "http://www.php.net/manual/en/ref.xml.php", - E_USER_ERROR ); - } - - - $this->parser = $parser; - - # pass in parser, and a reference to this object - # setup handlers - # - xml_set_object( $this->parser, $this ); - xml_set_element_handler($this->parser, - 'feed_start_element', 'feed_end_element' ); - - xml_set_character_data_handler( $this->parser, 'feed_cdata' ); - - $status = xml_parse( $this->parser, $source ); - - if (! $status ) { - $errorcode = xml_get_error_code( $this->parser ); - if ( $errorcode != XML_ERROR_NONE ) { - $xml_error = xml_error_string( $errorcode ); - $error_line = xml_get_current_line_number($this->parser); - $error_col = xml_get_current_column_number($this->parser); - $errormsg = "$xml_error at line $error_line, column $error_col"; - - $this->error( $errormsg ); - } - } - - xml_parser_free( $this->parser ); - - $this->normalize(); - } - - function feed_start_element($p, $element, &$attrs) { - $el = $element = strtolower($element); - $attrs = array_change_key_case($attrs, CASE_LOWER); - - // check for a namespace, and split if found - $ns = false; - if ( strpos( $element, ':' ) ) { - list($ns, $el) = split( ':', $element, 2); - } - if ( $ns and $ns != 'rdf' ) { - $this->current_namespace = $ns; - } - - # if feed type isn't set, then this is first element of feed - # identify feed from root element - # - if (!isset($this->feed_type) ) { - if ( $el == 'rdf' ) { - $this->feed_type = RSS; - $this->feed_version = '1.0'; - } - elseif ( $el == 'rss' ) { - $this->feed_type = RSS; - $this->feed_version = $attrs['version']; - } - elseif ( $el == 'feed' ) { - $this->feed_type = ATOM; - $this->feed_version = $attrs['version']; - $this->inchannel = true; - } - return; - } - - if ( $el == 'channel' ) - { - $this->inchannel = true; - } - elseif ($el == 'item' or $el == 'entry' ) - { - $this->initem = true; - if ( isset($attrs['rdf:about']) ) { - $this->current_item['about'] = $attrs['rdf:about']; - } - } - - // if we're in the default namespace of an RSS feed, - // record textinput or image fields - elseif ( - $this->feed_type == RSS and - $this->current_namespace == '' and - $el == 'textinput' ) - { - $this->intextinput = true; - } - - elseif ( - $this->feed_type == RSS and - $this->current_namespace == '' and - $el == 'image' ) - { - $this->inimage = true; - } - - # handle atom content constructs - elseif ( $this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) ) - { - // avoid clashing w/ RSS mod_content - if ($el == 'content' ) { - $el = 'atom_content'; - } - - $this->incontent = $el; - - - } - - // if inside an Atom content construct (e.g. content or summary) field treat tags as text - elseif ($this->feed_type == ATOM and $this->incontent ) - { - // if tags are inlined, then flatten - $attrs_str = join(' ', - array_map('map_attrs', - array_keys($attrs), - array_values($attrs) ) ); - - $this->append_content( "<$element $attrs_str>" ); - - array_unshift( $this->stack, $el ); - } - - // Atom support many links per containging element. - // Magpie treats link elements of type rel='alternate' - // as being equivalent to RSS's simple link element. - // - elseif ($this->feed_type == ATOM and $el == 'link' ) - { - if ( isset($attrs['rel']) and $attrs['rel'] == 'alternate' ) - { - $link_el = 'link'; - } - else { - $link_el = 'link_' . $attrs['rel']; - } - - $this->append($link_el, $attrs['href']); - } - // set stack[0] to current element - else { - array_unshift($this->stack, $el); - } - } - - - - function feed_cdata ($p, $text) { - - if ($this->feed_type == ATOM and $this->incontent) - { - $this->append_content( $text ); - } - else { - $current_el = join('_', array_reverse($this->stack)); - $this->append($current_el, $text); - } - } - - function feed_end_element ($p, $el) { - $el = strtolower($el); - - if ( $el == 'item' or $el == 'entry' ) - { - $this->items[] = $this->current_item; - $this->current_item = array(); - $this->initem = false; - } - elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' ) - { - $this->intextinput = false; - } - elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' ) - { - $this->inimage = false; - } - elseif ($this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) ) - { - $this->incontent = false; - } - elseif ($el == 'channel' or $el == 'feed' ) - { - $this->inchannel = false; - } - elseif ($this->feed_type == ATOM and $this->incontent ) { - // balance tags properly - // note: i don't think this is actually neccessary - if ( $this->stack[0] == $el ) - { - $this->append_content(""); - } - else { - $this->append_content("<$el />"); - } - - array_shift( $this->stack ); - } - else { - array_shift( $this->stack ); - } - - $this->current_namespace = false; - } - - function concat (&$str1, $str2="") { - if (!isset($str1) ) { - $str1=""; - } - $str1 .= $str2; - } - - - - function append_content($text) { - if ( $this->initem ) { - $this->concat( $this->current_item[ $this->incontent ], $text ); - } - elseif ( $this->inchannel ) { - $this->concat( $this->channel[ $this->incontent ], $text ); - } - } - - // smart append - field and namespace aware - function append($el, $text) { - if (!$el) { - return; - } - if ( $this->current_namespace ) - { - if ( $this->initem ) { - $this->concat( - $this->current_item[ $this->current_namespace ][ $el ], $text); - } - elseif ($this->inchannel) { - $this->concat( - $this->channel[ $this->current_namespace][ $el ], $text ); - } - elseif ($this->intextinput) { - $this->concat( - $this->textinput[ $this->current_namespace][ $el ], $text ); - } - elseif ($this->inimage) { - $this->concat( - $this->image[ $this->current_namespace ][ $el ], $text ); - } - } - else { - if ( $this->initem ) { - $this->concat( - $this->current_item[ $el ], $text); - } - elseif ($this->intextinput) { - $this->concat( - $this->textinput[ $el ], $text ); - } - elseif ($this->inimage) { - $this->concat( - $this->image[ $el ], $text ); - } - elseif ($this->inchannel) { - $this->concat( - $this->channel[ $el ], $text ); - } - - } - } - - function normalize () { - // if atom populate rss fields - if ( $this->is_atom() ) { - $this->channel['description'] = $this->channel['tagline']; - for ( $i = 0; $i < count($this->items); $i++) { - $item = $this->items[$i]; - if ( isset($item['summary']) ) - $item['description'] = $item['summary']; - if ( isset($item['atom_content'])) - $item['content']['encoded'] = $item['atom_content']; - - $atom_date = (isset($item['issued']) ) ? $item['issued'] : $item['modified']; - if ( $atom_date ) { - $epoch = @parse_w3cdtf($item['modified']); - if ($epoch and $epoch > 0) { - $item['date_timestamp'] = $epoch; - } - } - - $this->items[$i] = $item; - } - } - elseif ( $this->is_rss() ) { - $this->channel['tagline'] = $this->channel['description']; - for ( $i = 0; $i < count($this->items); $i++) { - $item = $this->items[$i]; - if ( isset($item['description'])) - $item['summary'] = $item['description']; - if ( isset($item['content']['encoded'] ) ) - $item['atom_content'] = $item['content']['encoded']; - - if ( $this->is_rss() == '1.0' and isset($item['dc']['date']) ) { - $epoch = @parse_w3cdtf($item['dc']['date']); - if ($epoch and $epoch > 0) { - $item['date_timestamp'] = $epoch; - } - } - elseif ( isset($item['pubdate']) ) { - $epoch = @strtotime($item['pubdate']); - if ($epoch > 0) { - $item['date_timestamp'] = $epoch; - } - } - - $this->items[$i] = $item; - } - } - } - - - function is_rss () { - if ( $this->feed_type == RSS ) { - return $this->feed_version; - } - else { - return false; - } - } - - function is_atom() { - if ( $this->feed_type == ATOM ) { - return $this->feed_version; - } - else { - return false; - } - } - - /** - * return XML parser, and possibly re-encoded source - * - */ - function create_parser($source, $out_enc, $in_enc, $detect) { - if ( substr(phpversion(),0,1) == 5) { - $parser = $this->php5_create_parser($in_enc, $detect); - } - else { - list($parser, $source) = $this->php4_create_parser($source, $in_enc, $detect); - } - if ($out_enc) { - $this->encoding = $out_enc; - xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $out_enc); - } - - return array($parser, $source); - } - - /** - * Instantiate an XML parser under PHP5 - * - * PHP5 will do a fine job of detecting input encoding - * if passed an empty string as the encoding. - * - * All hail libxml2! - * - */ - function php5_create_parser($in_enc, $detect) { - // by default php5 does a fine job of detecting input encodings - if(!$detect && $in_enc) { - return xml_parser_create($in_enc); - } - else { - return xml_parser_create(''); - } - } - - /** - * Instaniate an XML parser under PHP4 - * - * Unfortunately PHP4's support for character encodings - * and especially XML and character encodings sucks. As - * long as the documents you parse only contain characters - * from the ISO-8859-1 character set (a superset of ASCII, - * and a subset of UTF-8) you're fine. However once you - * step out of that comfy little world things get mad, bad, - * and dangerous to know. - * - * The following code is based on SJM's work with FoF - * @see http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss - * - */ - function php4_create_parser($source, $in_enc, $detect) { - if ( !$detect ) { - return array(xml_parser_create($in_enc), $source); - } - - if (!$in_enc) { - if (preg_match('//m', $source, $m)) { - $in_enc = strtoupper($m[1]); - $this->source_encoding = $in_enc; - } - else { - $in_enc = 'UTF-8'; - } - } - - if ($this->known_encoding($in_enc)) { - return array(xml_parser_create($in_enc), $source); - } - - // the dectected encoding is not one of the simple encodings PHP knows - - // attempt to use the iconv extension to - // cast the XML to a known encoding - // @see http://php.net/iconv - - if (function_exists('iconv')) { - $encoded_source = iconv($in_enc,'UTF-8', $source); - if ($encoded_source) { - return array(xml_parser_create('UTF-8'), $encoded_source); - } - } - - // iconv didn't work, try mb_convert_encoding - // @see http://php.net/mbstring - if(function_exists('mb_convert_encoding')) { - $encoded_source = mb_convert_encoding($source, 'UTF-8', $in_enc ); - if ($encoded_source) { - return array(xml_parser_create('UTF-8'), $encoded_source); - } - } - - // else - $this->error("Feed is in an unsupported character encoding. ($in_enc) " . - "You may see strange artifacts, and mangled characters.", - E_USER_NOTICE); - - return array(xml_parser_create(), $source); - } - - function known_encoding($enc) { - $enc = strtoupper($enc); - if ( in_array($enc, $this->_KNOWN_ENCODINGS) ) { - return $enc; - } - else { - return false; - } - } - - function error ($errormsg, $lvl=E_USER_WARNING) { - // append PHP's error message if track_errors enabled - if ( $php_errormsg ) { - $errormsg .= " ($php_errormsg)"; - } - if ( MAGPIE_DEBUG ) { - trigger_error( $errormsg, $lvl); - } - else { - error_log( $errormsg, 0); - } - - $notices = E_USER_NOTICE|E_NOTICE; - if ( $lvl&$notices ) { - $this->WARNING = $errormsg; - } else { - $this->ERROR = $errormsg; - } - } - - -} // end class RSS - -function map_attrs($k, $v) { - return "$k=\"$v\""; -} - - -?> diff --git a/tools/IRC_Bot/magpierss/rss_utils.inc b/tools/IRC_Bot/magpierss/rss_utils.inc deleted file mode 100644 index 2a29e72a9..000000000 --- a/tools/IRC_Bot/magpierss/rss_utils.inc +++ /dev/null @@ -1,67 +0,0 @@ - - * Version: 0.51 - * License: GPL - * - * The lastest version of MagpieRSS can be obtained from: - * http://magpierss.sourceforge.net - * - * For questions, help, comments, discussion, etc., please join the - * Magpie mailing list: - * magpierss-general@lists.sourceforge.net - */ - - -/*======================================================================*\ - Function: parse_w3cdtf - Purpose: parse a W3CDTF date into unix epoch - - NOTE: http://www.w3.org/TR/NOTE-datetime -\*======================================================================*/ - -function parse_w3cdtf ( $date_str ) { - - # regex to match wc3dtf - $pat = "/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/"; - - if ( preg_match( $pat, $date_str, $match ) ) { - list( $year, $month, $day, $hours, $minutes, $seconds) = - array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[6]); - - # calc epoch for current date assuming GMT - $epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year); - - $offset = 0; - if ( $match[10] == 'Z' ) { - # zulu time, aka GMT - } - else { - list( $tz_mod, $tz_hour, $tz_min ) = - array( $match[8], $match[9], $match[10]); - - # zero out the variables - if ( ! $tz_hour ) { $tz_hour = 0; } - if ( ! $tz_min ) { $tz_min = 0; } - - $offset_secs = (($tz_hour*60)+$tz_min)*60; - - # is timezone ahead of GMT? then subtract offset - # - if ( $tz_mod == '+' ) { - $offset_secs = $offset_secs * -1; - } - - $offset = $offset_secs; - } - $epoch = $epoch + $offset; - return $epoch; - } - else { - return -1; - } -} - -?> diff --git a/tools/LevelConverter/Makefile b/tools/LevelConverter/Makefile deleted file mode 100644 index 23b8a1106..000000000 --- a/tools/LevelConverter/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -# Makfile for SRB2 Level Converter -# by Alam Arias et al. - -SRC=levelconverter.c -OBJ=$(SRC:.c=.o)# replaces the .c from SRC with .o -EXE=LevelConverter - -.PHONY : all # .PHONY ignores files named all -all: $(EXE) # all is dependent on $(BIN) to be complete - -$(EXE): $(OBJ) # $(EXE) is dependent on all of the files in $(OBJ) to exist - $(CC) $(OBJ) $(LDFLAGS) -o $@ - -.PHONY : clean # .PHONY ignores files named clean -clean: - -$(RM) $(OBJ) $(EXE) diff --git a/tools/LevelConverter/levelconverter.c b/tools/LevelConverter/levelconverter.c deleted file mode 100644 index 7c84ac510..000000000 --- a/tools/LevelConverter/levelconverter.c +++ /dev/null @@ -1,1061 +0,0 @@ -// -// Level Converter -// -// Converts thing types from 1.09.4 to 1.1 -// -// By A.J. Freda -// -// Modified from Graue's "Heightedit" -// and uses Graue's "LumpMod" utility. -// - -#include -#include -#include - -//#define STARPOSTS_ONLY - -#define TABLE_SIZE 16384 -int conversion[TABLE_SIZE]; // Conversion table. -FILE *lvlconvfile; - -static inline void InitializeThingConversionTable(void) -{ - memset(conversion, 0, sizeof(conversion)); - - // Player starts - conversion[1] = 1; - conversion[2] = 2; - conversion[3] = 3; - conversion[4] = 4; - conversion[4001] = 5; - conversion[4002] = 6; - conversion[4003] = 7; - conversion[4004] = 8; - conversion[4005] = 9; - conversion[4006] = 10; - conversion[4007] = 11; - conversion[4008] = 12; - conversion[4009] = 13; - conversion[4010] = 14; - conversion[4011] = 15; - conversion[4012] = 16; - conversion[4013] = 17; - conversion[4014] = 18; - conversion[4015] = 19; - conversion[4016] = 20; - conversion[4017] = 21; - conversion[4018] = 22; - conversion[4019] = 23; - conversion[4020] = 24; - conversion[4021] = 25; - conversion[4022] = 26; - conversion[4023] = 27; - conversion[4024] = 28; - conversion[4025] = 29; - conversion[4026] = 30; - conversion[4027] = 31; - conversion[4028] = 32; - conversion[11] = 33; - conversion[87] = 34; - conversion[89] = 35; - - // Enemies - conversion[3004] = 100; - conversion[9] = 101; - conversion[58] = 102; - conversion[5005] = 103; - conversion[5006] = 104; - conversion[3005] = 105; - conversion[22] = 106; - conversion[21] = 107; - conversion[71] = 108; - conversion[56] = 109; - conversion[2004] = 110; - conversion[42] = 111; - - // Bosses - conversion[16] = 200; - conversion[2008] = 201; - conversion[17] = 290; - conversion[2049] = 291; - - // Collectibles - conversion[2014] = 300; - conversion[69] = 301; - conversion[3003] = 302; - conversion[80] = 303; - conversion[26] = 304; - conversion[54] = 305; - conversion[31] = 310; - conversion[34] = 311; - conversion[2013] = 312; - conversion[420] = 313; - conversion[421] = 314; - conversion[422] = 315; - conversion[423] = 316; - conversion[424] = 317; - conversion[425] = 318; - conversion[426] = 319; - conversion[64] = 320; - conversion[3002] = 320; - conversion[3001] = 320; - - // Boxes - conversion[2011] = 400; - conversion[2012] = 400; - conversion[48] = 402; - conversion[2002] = 403; - conversion[2018] = 404; - conversion[35] = 405; - conversion[2028] = 406; - conversion[25] = 407; - conversion[2022] = 408; - conversion[41] = 409; - conversion[2005] = 410; - conversion[78] = 411; - conversion[3000] = 412; - - // Interactive Objects - conversion[33] = 500; - conversion[86] = 501; - conversion[3006] = 502; -// conversion[?] = 520; - conversion[23] = 521; - conversion[67] = 522; - conversion[68] = 523; - conversion[32] = 540; - conversion[30] = 541; - conversion[28] = 550; - conversion[79] = 551; - conversion[5004] = 552; - conversion[65] = 553; - conversion[66] = 554; - conversion[2015] = 555; - conversion[38] = 556; - conversion[20] = 557; - conversion[39] = 558; - - // Special Placement Patterns - conversion[84] = 600; - conversion[44] = 601; - conversion[76] = 602; - conversion[77] = 603; - conversion[47] = 604; - conversion[2007] = 605; - conversion[2048] = 606; - conversion[2010] = 607; - conversion[2046] = 608; - conversion[2047] = 609; - - // Powerup Indicators/Environmental Effects/Miscellany - conversion[2026] = 700; - conversion[2024] = 701; - conversion[2023] = 702; - conversion[2045] = 703; - conversion[83] = 704; - conversion[2019] = 705; - conversion[2025] = 706; - conversion[27] = 707; - conversion[14] = 708; - conversion[43] = 709; - conversion[8] = 750; - conversion[5003] = 751; - conversion[5007] = 752; - conversion[18] = 753; - conversion[5001] = 754; - conversion[5002] = 755; - conversion[2003] = 756; - - // Greenflower Scenery - conversion[36] = 800; - conversion[70] = 801; - conversion[73] = 802; - conversion[74] = 804; - conversion[75] = 805; - - // Techno Hill Scenery - conversion[2035] = 900; - conversion[2006] = 901; - - // Deep Sea Scenery - conversion[81] = 1000; - - // Castle Eggman Scenery - conversion[49] = 1100; - conversion[24] = 1101; - conversion[52] = 1102; - conversion[2001] = 1103; - - // NiGHTS Items - conversion[72] = 1700; - conversion[61] = 1701; - conversion[46] = 1702; - conversion[60] = 1703; - conversion[82] = 1704; - conversion[57] = 1705; - conversion[37] = 1706; - conversion[3007] = 1707; - conversion[3008] = 1708; - conversion[3009] = 1709; - conversion[40] = 1710; - - // Mario Items - conversion[10005] = 1800; - conversion[10000] = 1801; - conversion[10001] = 1802; - conversion[50] = 1803; - conversion[10] = 1804; - conversion[29] = 1805; - conversion[19] = 1806; - conversion[12] = 1807; - conversion[10002] = 1808; - conversion[10003] = 1809; - conversion[10004] = 1810; - - // Christmas Items - conversion[5] = 1850; - conversion[13] = 1851; - conversion[6] = 1852; -} - -static inline void InitializeSectorConversionTable(void) -{ - memset(conversion, 0, sizeof(conversion)); - - // Player starts - conversion[690] = -1; - conversion[691] = -1; - conversion[692] = -1; - conversion[693] = -1; - conversion[694] = -1; - conversion[695] = -1; - conversion[696] = -1; - conversion[697] = -1; - conversion[698] = -1; - conversion[699] = -1; - conversion[700] = -1; - conversion[701] = -1; - conversion[702] = -1; - conversion[703] = -1; - conversion[704] = -1; - conversion[705] = -1; - conversion[706] = -1; - conversion[707] = -1; - conversion[708] = -1; - conversion[709] = -1; - conversion[710] = -1; - conversion[711] = -1; - conversion[981] = -1; - conversion[986] = -1; - conversion[8] = -1; - conversion[17] = -1; - conversion[519] = 3 + (512 << 8); - conversion[984] = 2 + (512 << 8); - - // Section 1 - conversion[11] = 1; - conversion[983] = 2; - conversion[7] = 3; - conversion[18] = 4; - conversion[4] = 5; - conversion[16] = 6; - conversion[5] = 7; - conversion[10] = 8; - conversion[978] = 9; - conversion[980] = 10; - conversion[9] = 11; - conversion[6] = 12; - conversion[992] = 13; - conversion[996] = 14; - conversion[14] = 15; - - // Section 2 - conversion[971] = 1 << 4; - conversion[972] = 2 << 4; - conversion[973] = 3 << 4; - conversion[974] = 4 << 4; - conversion[975] = 5 << 4; - conversion[967] = 6 << 4; - conversion[968] = 7 << 4; - conversion[970] = 8 << 4; - conversion[666] = 9 << 4; - conversion[990] = 10 << 4; - conversion[991] = 11 << 4; - - // Section 3 - conversion[256] = 1 << 8; - conversion[512] = 2 << 8; - conversion[768] = 3 << 8; - conversion[985] = 4 << 8; - conversion[976] = 5 << 8; - conversion[977] = 6 << 8; - conversion[1500] = 7 << 8; - conversion[1501] = 8 << 8; - conversion[1502] = 9 << 8; - conversion[1503] = 10 << 8; - conversion[1504] = 11 << 8; - conversion[1505] = 12 << 8; - conversion[1506] = 13 << 8; - conversion[1507] = 14 << 8; - conversion[1508] = 15 << 8; - - // Section 4 - conversion[993] = 1 << 12; - conversion[33] = 2 << 12; - conversion[982] = 2 << 12; - conversion[987] = 2 << 12; - conversion[995] = 2 << 12; - conversion[988] = 3 << 12; - conversion[989] = 4 << 12; - conversion[997] = 5 << 12; - conversion[969] = 6 << 12; - conversion[979] = 7 << 12; - conversion[998] = 8 << 12; - conversion[999] = 9 << 12; - conversion[994] = 10 << 12; -} - -static inline void InitializeLinedefConversionTable(void) -{ - memset(conversion, 0, sizeof(conversion)); - - // Old Water Removed - conversion[14] = -1; - - // Level Parameters/Misc: - conversion[64] = 1; - conversion[71] = 2; - conversion[18] = 3; - conversion[65] = 4; - conversion[63] = 5; - conversion[73] = 6; - conversion[66] = 7; - - // Level-Load Effects: - conversion[26] = 50; - conversion[24] = 51; - conversion[88] = 52; - conversion[2] = 53; - conversion[3] = 54; - conversion[4] = 55; - conversion[6] = 56; - conversion[7] = 57; - conversion[8] = 58; - conversion[232] = 59; - conversion[233] = 60; - conversion[43] = 61; - conversion[50] = 62; - conversion[242] = 63; - - // Floor-Over-Floors: - conversion[25] = 100; - conversion[33] = 101; - conversion[44] = 102; - conversion[69] = 103; - conversion[51] = 104; - conversion[57] = 105; - conversion[48] = 120; - conversion[45] = 121; - conversion[75] = 122; - conversion[74] = 123; - conversion[59] = 140; - conversion[81] = 141; - conversion[77] = 142; - conversion[38] = 150; - conversion[68] = 151; - conversion[72] = 152; - conversion[34] = 160; - conversion[36] = 170; - conversion[35] = 171; - conversion[79] = 172; - conversion[80] = 173; - conversion[82] = 174; - conversion[83] = 175; - conversion[39] = 176; - conversion[1] = 177; - conversion[37] = 178; - conversion[42] = 179; - conversion[40] = 180; - conversion[89] = 190; - conversion[90] = 191; - conversion[91] = 192; - conversion[94] = 193; - conversion[92] = 194; - conversion[93] = 195; - conversion[49] = 200; - conversion[47] = 201; - conversion[46] = 202; - conversion[62] = 220; - conversion[52] = 221; - conversion[67] = 222; - conversion[58] = 223; - conversion[41] = 250; - conversion[54] = 251; - conversion[76] = 252; - conversion[86] = 253; - conversion[55] = 254; - conversion[78] = 255; - conversion[84] = 256; - conversion[56] = 257; - conversion[53] = 258; - conversion[87] = 259; - - // Linedef Executor Triggers: - conversion[96] = 300; - conversion[97] = 301; - conversion[98] = 302; - conversion[95] = 303; - conversion[99] = 304; - conversion[19] = 305; - conversion[20] = 306; - conversion[21] = 307; - conversion[9] = 308; - conversion[10] = 309; - conversion[11] = 310; - conversion[12] = 311; - conversion[13] = 312; - conversion[15] = 313; - - // Linedef Executor Options: - conversion[101] = 400; - conversion[102] = 401; - conversion[103] = 402; - conversion[106] = 403; - conversion[107] = 404; - conversion[108] = 405; - conversion[109] = 406; - conversion[110] = 407; - conversion[111] = 408; - conversion[112] = 409; - conversion[114] = 410; - conversion[116] = 411; - conversion[104] = 412; - conversion[105] = 413; - conversion[115] = 414; - conversion[113] = 415; - conversion[119] = 416; - conversion[120] = 417; - conversion[117] = 420; - conversion[118] = 421; - conversion[121] = 422; - conversion[123] = 423; - conversion[124] = 424; - conversion[125] = 425; - conversion[122] = 426; - conversion[126] = 427; - conversion[127] = 428; - - // Scrollers/Pushers - conversion[100] = 500; - conversion[85] = 501; - conversion[254] = 502; - conversion[218] = 503; - conversion[249] = 504; - conversion[255] = 505; - conversion[251] = 510; - conversion[215] = 511; - conversion[246] = 512; - conversion[250] = 513; - conversion[214] = 514; - conversion[245] = 515; - conversion[252] = 520; - conversion[216] = 521; - conversion[247] = 522; - conversion[203] = 523; - conversion[205] = 524; - conversion[201] = 525; - conversion[253] = 530; - conversion[217] = 531; - conversion[248] = 532; - conversion[202] = 533; - conversion[204] = 534; - conversion[200] = 535; - conversion[223] = 540; - conversion[224] = 541; - conversion[229] = 542; - conversion[230] = 543; - conversion[225] = 544; - conversion[227] = 545; - conversion[228] = 546; - conversion[226] = 547; - - // Lighting - conversion[213] = 600; - - conversion[5] = 601; - conversion[60] = 602; - conversion[61] = 603; - conversion[16] = 606; - - // Translucency - conversion[284] = 900; - conversion[285] = 901; - conversion[286] = 902; - conversion[287] = 903; - conversion[288] = 904; - conversion[283] = 905; - - // Extended numbers - conversion[281] = conversion[25]; - conversion[289] = conversion[33]; - conversion[282] = conversion[26]; -} - -#ifndef _WIN32 -#include -static inline const char* _strupr(char *n) -{ - const char *m = n; - while (*n != '\0') - { - *n = toupper(*n); - n++; - } - return m; -} -#define strupr _strupr -#endif - -static inline int ConvertStarposts(char *argv[]) -{ - char syscmd[100]; - InitializeThingConversionTable(); - - sprintf(syscmd, "lumpmod %s extract -s MAP%s THINGS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - - lvlconvfile = fopen("lvlconv.tmp", "r+b"); - if(lvlconvfile == NULL) { - puts("Failed to open lvlconv.tmp."); - return EXIT_FAILURE; - } - for(;;) { - int c; - short x, y, angle, type, options; - - fseek(lvlconvfile, 1, SEEK_CUR); - fseek(lvlconvfile, -1, SEEK_CUR); - - c = fgetc(lvlconvfile); - if(c == EOF) break; - - fseek(lvlconvfile, -1, SEEK_CUR); - if(fread(&x, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT READ THE X"); - return EXIT_FAILURE; - } - if(fread(&y, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE Y"); - return EXIT_FAILURE; - } - if(fread(&angle, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE ANGLE"); - return EXIT_FAILURE; - } - if(fread(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE TYPE"); - return EXIT_FAILURE; - } - if(fread(&options, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE FLAGS"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, -6, SEEK_CUR); - - /* CHECK FOR MATCH */ - if(type == 502) - { - int numpost = options & 31; - angle %= 360; - angle += numpost * 360; - options = 0; - } - - if(fwrite(&angle, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE ANGLE"); - return EXIT_FAILURE; - } - - if(fwrite(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE TYPE"); - return EXIT_FAILURE; - } - - if (fwrite(&options, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE FLAGS"); - return EXIT_FAILURE; - } - } - fclose(lvlconvfile); - puts("DONE, Man!.. Inserting into WAD.\n"); - sprintf(syscmd, "lumpmod %s update -s MAP%s THINGS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - remove("lvlconv.tmp"); - return 1; -} - -static inline int ConvertThings(char *argv[]) -{ - char syscmd[100]; - InitializeThingConversionTable(); - - printf("NOTE: Skill settings not supported in 1.1. All of your objects\nhave been converted to appear regardless of skill level.\n"); - - sprintf(syscmd, "lumpmod %s extract -s MAP%s THINGS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - - lvlconvfile = fopen("lvlconv.tmp", "r+b"); - if(lvlconvfile == NULL) { - puts("Failed to open lvlconv.tmp."); - return EXIT_FAILURE; - } - for(;;) { - int c; - short x, y, angle, type, options; - - fseek(lvlconvfile, 1, SEEK_CUR); - fseek(lvlconvfile, -1, SEEK_CUR); - - c = fgetc(lvlconvfile); - if(c == EOF) break; - - fseek(lvlconvfile, -1, SEEK_CUR); - if(fread(&x, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT READ THE X"); - return EXIT_FAILURE; - } - if(fread(&y, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE Y"); - return EXIT_FAILURE; - } - if(fread(&angle, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE ANGLE"); - return EXIT_FAILURE; - } - if(fread(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE TYPE"); - return EXIT_FAILURE; - } - if(fread(&options, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE FLAGS"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, -6, SEEK_CUR); - - /* CHECK FOR MATCH */ - if(type != 32000 && type != 32001) // !@#$%^ Doom Builder... - { - if(type < TABLE_SIZE && conversion[type] < 0) - printf("\nThing type %d no longer supported. You will have to manually change this.", type); - else if(type < TABLE_SIZE && conversion[type] != 0) - type = conversion[type]; - else - printf("\nUnknown thing type %d!", type); - - if (type != 502 && type != 1700 && type != 1701 && type != 1702 && type != 1703 && type != 1704 && type != 1705) - { - if (options == 1 || options == 4) - { - printf("\nThing type %d on Easy or Hard only, renamed to thing type 4242.", type); - type = 4242; - } - - options &= ~7; // Strip skill settings - } - } - - if (type == 502) - { - int numpost = options & 31; - angle %= 360; - angle += numpost * 360; - options = 0; - } - - if(fwrite(&angle, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE ANGLE"); - return EXIT_FAILURE; - } - - if(fwrite(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE TYPE"); - return EXIT_FAILURE; - } - - if (fwrite(&options, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE FLAGS"); - return EXIT_FAILURE; - } - } - fclose(lvlconvfile); - puts("DONE, Man!.. Inserting into WAD.\n"); - sprintf(syscmd, "lumpmod %s update -s MAP%s THINGS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - remove("lvlconv.tmp"); - return 1; -} - -static void ConvertFlat(char *garbage) -{ - /* CHECK FOR MATCH */ - if(!memcmp(garbage, "FLOOR0_3\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR01\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR0_6\0\0\0", 8)) - strncpy(garbage, "GFZFLR02\0\0\0", 8); - else if(!memcmp(garbage, "CEIL3_3\0\0\0\0\0", 8) || !memcmp(garbage, "GATE1\0\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR03\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "CEIL3_4\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR04\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR1_1\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR05\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR1_7\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR06\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR5_3\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR07\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "OLDROCK\0\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR08\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SFLR5_0\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR09\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SFLR6_1\0\0\0\0\0", 8) - || !memcmp(garbage, "SFLR6_4\0\0\0\0\0", 8) - || !memcmp(garbage, "SFLR7_1\0\0\0\0\0", 8) - || !memcmp(garbage, "SFLR7_4\0\0\0\0\0", 8)) - { - printf("Flat pic %s no longer supported. Use GFZFLR09 with\r\nlinedef special #7 to achieve same effect.\r\nFlat converted to GFZFLR09 for your convenience.\r\n", garbage); - strncpy(garbage, "GFZFLR09\0\0\0\0\0\0", 8); - } - else if(!memcmp(garbage, "DEM1_4\0\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR10\0\0\0\0", 8); - - else if(!memcmp(garbage, "FLOOR3_3\0\0\0\0\0", 8)) - strncpy(garbage, "THZFLR30\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR4_5\0\0\0\0\0", 8)) - strncpy(garbage, "THZFLR31\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "OTHZW1\0\0\0\0\0", 8)) - strncpy(garbage, "THZFLR32\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "OTHZW2\0\0\0\0\0", 8)) - strncpy(garbage, "THZFLR33\0\0\0\0\0\0\0", 8); - - else if(!memcmp(garbage, "BLOOD1\0\0", 8)) - strncpy(garbage, "LITER1\0\0", 8); - else if(!memcmp(garbage, "BLOOD2\0\0", 8)) - strncpy(garbage, "LITER2\0\0", 8); - else if(!memcmp(garbage, "BLOOD3\0\0", 8)) - strncpy(garbage, "LITER3\0\0", 8); - - else if(!memcmp(garbage, "BLUE1\0\0\0", 8)) - strncpy(garbage, "LITEB1\0\0", 8); - else if(!memcmp(garbage, "BLUE2\0\0\0", 8)) - strncpy(garbage, "LITEB2\0\0", 8); - else if(!memcmp(garbage, "BLUE3\0\0\0", 8)) - strncpy(garbage, "LITEB3\0\0", 8); - - else if(!memcmp(garbage, "GREY1\0\0\0", 8)) - strncpy(garbage, "LITEN1\0\0", 8); - else if(!memcmp(garbage, "GREY2\0\0\0", 8)) - strncpy(garbage, "LITEN2\0\0", 8); - else if(!memcmp(garbage, "GREY3\0\0\0", 8)) - strncpy(garbage, "LITEN3\0\0", 8); - - else if(!memcmp(garbage, "NUKAGE1\0\0\0", 8)) - strncpy(garbage, "LITEY1\0\0", 8); - else if(!memcmp(garbage, "NUKAGE2\0\0\0", 8)) - strncpy(garbage, "LITEY2\0\0", 8); - else if(!memcmp(garbage, "NUKAGE3\0\0\0", 8)) - strncpy(garbage, "LITEY3\0\0", 8); - - else if(!memcmp(garbage, "CEIL1_3\0\0\0\0\0", 8)) - strncpy(garbage, "CEZFLR09\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "CEIL1_1\0\0\0\0\0", 8)) - strncpy(garbage, "CEZFLR10\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "CEIL1_2\0\0\0\0\0", 8)) - strncpy(garbage, "CEZFLR11\0\0\0\0\0\0\0", 8); - - else if(!memcmp(garbage, "CONS1_1\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR07\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "CONS1_5\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR08\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "CONS1_7\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR09\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR0_5\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR10\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR0_7\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR11\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR1_6\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR12\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME01\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR13\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME02\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR14\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME03\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR15\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME04\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR12\0\0\0\0\0\0\0", 8); - - else if(!memcmp(garbage, "DCFLR1\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR01\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCCEIL1\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR02\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCPAVE\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR03\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCMANHO\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR04\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCTEX1\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR05\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCTEX2\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR06\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCTEX3\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR07\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCTEX4\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR08\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCWHITE\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR09\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCYELLOW\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR10\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DENTFLR\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR11\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DENTMETL\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR12\0\0\0\0\0\0\0", 8); // Intentionally - else if(!memcmp(garbage, "FLAT14\0\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR12\0\0\0\0\0", 8); // The same! - else if(!memcmp(garbage, "MFLR8_1\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR13\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "STEP2\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR14\0\0\0\0\0", 8); - - - else if(!memcmp(garbage, "DEEPSEA2\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR04\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DEEPSEA3\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR05\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DEEPSEA4\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR06\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR4_6\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR07\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME14\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR08\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME15\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR09\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME16\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR10\0\0\0\0\0\0\0", 8); - - else if(!memcmp(garbage, "ERROCK\0\0\0\0\0\0", 8)) - strncpy(garbage, "ERZFLR01\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLAT18\0\0\0\0\0\0", 8)) - strncpy(garbage, "ERZFLR02\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLAT20\0\0\0\0\0\0", 8)) - strncpy(garbage, "ERZFLR03\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLAT22\0\0\0\0\0\0", 8)) - strncpy(garbage, "ERZFLR04\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLAT23\0\0\0\0\0\0", 8)) - strncpy(garbage, "ERZFLR05\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLAT5_4\0\0\0\0", 8)) - strncpy(garbage, "ERZFLR06\0\0\0\0\0", 8); - - else if(!memcmp(garbage, "FLAT10\0\0\0\0\0\0", 8)) - strncpy(garbage, "REDFLR\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLAT5\0\0\0\0\0\0", 8)) - strncpy(garbage, "ORGFLR\0\0\0\0\0", 8); - - else if(!memcmp(garbage, "MFLR8_2\0\0\0\0\0\0", 8)) - strncpy(garbage, "GREYFLR\0\0\0\0\0", 8); - else if(!memcmp(garbage, "MFLR8_4\0\0\0\0\0\0", 8)) - strncpy(garbage, "GREYFLR\0\0\0\0\0", 8); -} - -static inline int ConvertSectors(char *argv[]) -{ - char syscmd[100]; - InitializeSectorConversionTable(); - - sprintf(syscmd, "lumpmod %s extract -s MAP%s SECTORS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - - lvlconvfile = fopen("lvlconv.tmp", "r+b"); - if(lvlconvfile == NULL) { - puts("Failed to open lvlconv.tmp."); - return EXIT_FAILURE; - } - for(;;) { - int c; - char garbage[11]; - short type; - - c = fgetc(lvlconvfile); - if(c == EOF) break; - - fseek(lvlconvfile, -1, SEEK_CUR); - if(fread(&garbage, sizeof(short)*2, 1, lvlconvfile) < 1) { - puts("I CANNOT READ THE DATA BEFORE SECTOR FLATS"); - return EXIT_FAILURE; - } - - // Read floor flat first. - if(fread(&garbage, 8, 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE SECTOR FLOOR FLAT"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, -8, SEEK_CUR); - - garbage[8] = 0; - - ConvertFlat(garbage); - - if(fwrite(&garbage, 8, 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE FLOOR FLAT"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, 0, SEEK_CUR); - - memset(garbage, 0, sizeof(garbage)); - - // Now do ceiling flat. - if(fread(&garbage, 8, 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE SECTOR CEILING FLAT"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, -8, SEEK_CUR); - - garbage[8] = 0; - ConvertFlat(garbage); - - if(fwrite(&garbage, 8, 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE CEILING FLAT"); - return EXIT_FAILURE; - } - - // Skip lightlevel - fseek(lvlconvfile, 1 * sizeof(short), SEEK_CUR); - - // Now do sector special. - if(fread(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE SECTOR SPECIAL"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, -1 * (int)sizeof(short), SEEK_CUR); - - /* CHECK FOR MATCH */ - if(conversion[type] < 0) - printf("\nSector type %d no longer supported. You will have to manually change this.", type); - else if(conversion[type] != 0) - type = conversion[type]; - else if (type != 0) - printf("\nUnknown sector type %d!", type); - - if(fwrite(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE TYPE"); - return EXIT_FAILURE; - } - - /* skip 1 short of TOTAL CRAP */ - fseek(lvlconvfile, 1 * sizeof(short), SEEK_CUR); - } - fclose(lvlconvfile); - puts("DONE, Man!.. Inserting back into WAD.\n"); - sprintf(syscmd, "lumpmod %s update -s MAP%s SECTORS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - remove("lvlconv.tmp"); - return 1; -} - -static inline int ConvertLinedefs(char *argv[]) -{ - char syscmd[100]; - InitializeLinedefConversionTable(); - - sprintf(syscmd, "lumpmod %s extract -s MAP%s LINEDEFS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - - lvlconvfile = fopen("lvlconv.tmp", "r+b"); - if(lvlconvfile == NULL) { - puts("Failed to open lvlconv.tmp."); - return EXIT_FAILURE; - } - for(;;) { - int c; - short garbage[3], type; - - c = fgetc(lvlconvfile); - if(c == EOF) break; - - fseek(lvlconvfile, -1, SEEK_CUR); - if(fread(&garbage, sizeof(short)*3, 1, lvlconvfile) < 1) { - puts("I CANNOT READ THE DATA BEFORE THE LINEDEF SPECIAL"); - return EXIT_FAILURE; - } - if(fread(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE LINEDEF TYPE"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, -1 * (int)sizeof(short), SEEK_CUR); - - /* CHECK FOR MATCH */ - if(conversion[type] < 0) - printf("\nLinedef type %d no longer supported. You will have to manually change this.", type); - else if(conversion[type] != 0) - { - if(type == 65) - printf("\nThis level contains a speed pad linedef. You will have to flip the direction of the line for it to work properly."); - - type = conversion[type]; - } - else if (type != 0) - printf("\nUnknown linedef type %d!", type); - - if(fwrite(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE TYPE"); - return EXIT_FAILURE; - } - - /* skip 3 shorts of TOTAL CRAP */ - fseek(lvlconvfile, 3 * sizeof(short), SEEK_CUR); - } - fclose(lvlconvfile); - puts("DONE, Man!.. Inserting back into WAD.\n"); - sprintf(syscmd, "lumpmod %s update -s MAP%s LINEDEFS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - remove("lvlconv.tmp"); - return 1; -} - -int main(int argc, char *argv[]) { - if(argc != 3) { - puts("Usage: lvlconv [filename] [mapnumber]"); - puts("Example: lvlconv wadfile.wad 01"); - return EXIT_FAILURE; /* YOU FAIL IT! */ - } - - if(strlen(argv[2]) != 2 || strlen(argv[1]) > 32) { - puts("nonono you screwed it up"); - return EXIT_FAILURE; /* YOU LIKEWISE FAIL IT! */ - } -#ifdef STARPOSTS_ONLY - ConvertStarposts(argv); -#else - puts("\nConverting Things..."); - ConvertThings(argv); - puts("\nConverting Sectors..."); - ConvertSectors(argv); - puts("\nConverting Linedefs..."); - ConvertLinedefs(argv); -#endif - - puts("\nOkay, DONE!! Enjoy the NEWLY MODIFIED WAD FILE!!! HAVE A GOOD DAY!"); - return EXIT_SUCCESS; /* YOU SUCCEED AT IT! :) */ -} diff --git a/tools/LevelConverter/levelconverter.dsp b/tools/LevelConverter/levelconverter.dsp deleted file mode 100644 index 655cc3799..000000000 --- a/tools/LevelConverter/levelconverter.dsp +++ /dev/null @@ -1,88 +0,0 @@ -# Microsoft Developer Studio Project File - Name="levelconverter" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=levelconverter - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "levelconverter.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "levelconverter.mak" CFG="levelconverter - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "levelconverter - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "levelconverter - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "levelconverter - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 - -!ELSEIF "$(CFG)" == "levelconverter - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept - -!ENDIF - -# Begin Target - -# Name "levelconverter - Win32 Release" -# Name "levelconverter - Win32 Debug" -# Begin Source File - -SOURCE=.\levelconverter.c -# End Source File -# End Target -# End Project diff --git a/tools/LevelConverter/levelconverter.dsw b/tools/LevelConverter/levelconverter.dsw deleted file mode 100644 index 51a840c28..000000000 --- a/tools/LevelConverter/levelconverter.dsw +++ /dev/null @@ -1,29 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "levelconverter"=.\levelconverter.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - diff --git a/tools/MSDfile b/tools/MSDfile deleted file mode 100644 index 287c31354..000000000 --- a/tools/MSDfile +++ /dev/null @@ -1,235 +0,0 @@ -# Doxyfile 1.4.3 - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- -PROJECT_NAME = "SRB2 MasterServer" -PROJECT_NUMBER = -OUTPUT_DIRECTORY = ../doc/MasterServer -CREATE_SUBDIRS = YES -OUTPUT_LANGUAGE = English -USE_WINDOWS_ENCODING = YES -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ABBREVIATE_BRIEF = "The $name class" \ - "The $name widget" \ - "The $name file" \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the -ALWAYS_DETAILED_SEC = NO -INLINE_INHERITED_MEMB = NO -FULL_PATH_NAMES = YES -STRIP_FROM_PATH = -STRIP_FROM_INC_PATH = -SHORT_NAMES = NO -JAVADOC_AUTOBRIEF = NO -MULTILINE_CPP_IS_BRIEF = NO -DETAILS_AT_TOP = NO -INHERIT_DOCS = YES -DISTRIBUTE_GROUP_DOC = NO -SEPARATE_MEMBER_PAGES = NO -TAB_SIZE = 8 -ALIASES = -OPTIMIZE_OUTPUT_FOR_C = NO -OPTIMIZE_OUTPUT_JAVA = NO -SUBGROUPING = YES -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- -EXTRACT_ALL = YES -EXTRACT_PRIVATE = YES -EXTRACT_STATIC = YES -EXTRACT_LOCAL_CLASSES = YES -EXTRACT_LOCAL_METHODS = NO -HIDE_UNDOC_MEMBERS = NO -HIDE_UNDOC_CLASSES = NO -HIDE_FRIEND_COMPOUNDS = NO -HIDE_IN_BODY_DOCS = NO -INTERNAL_DOCS = NO -CASE_SENSE_NAMES = NO -HIDE_SCOPE_NAMES = NO -SHOW_INCLUDE_FILES = YES -INLINE_INFO = YES -SORT_MEMBER_DOCS = YES -SORT_BRIEF_DOCS = NO -SORT_BY_SCOPE_NAME = NO -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -GENERATE_DEPRECATEDLIST= YES -ENABLED_SECTIONS = -MAX_INITIALIZER_LINES = 30 -SHOW_USED_FILES = YES -SHOW_DIRECTORIES = YES -FILE_VERSION_FILTER = -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = NO -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_IF_DOC_ERROR = YES -WARN_NO_PARAMDOC = NO -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = ./masterserver -FILE_PATTERNS = *.cpp \ - *.h -RECURSIVE = NO -EXCLUDE = -EXCLUDE_SYMLINKS = NO -EXCLUDE_PATTERNS = -EXAMPLE_PATH = -EXAMPLE_PATTERNS = * -EXAMPLE_RECURSIVE = NO -IMAGE_PATH = -INPUT_FILTER = -FILTER_PATTERNS = -FILTER_SOURCE_FILES = YES -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- -SOURCE_BROWSER = YES -INLINE_SOURCES = YES -STRIP_CODE_COMMENTS = YES -REFERENCED_BY_RELATION = NO -REFERENCES_RELATION = NO -USE_HTAGS = NO -VERBATIM_HEADERS = YES -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = NO -COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = html -HTML_FILE_EXTENSION = .html -HTML_HEADER = -HTML_FOOTER = -HTML_STYLESHEET = -HTML_ALIGN_MEMBERS = YES -GENERATE_HTMLHELP = NO -CHM_FILE = -HHC_LOCATION = -GENERATE_CHI = NO -BINARY_TOC = NO -TOC_EXPAND = NO -DISABLE_INDEX = NO -ENUM_VALUES_PER_LINE = 4 -GENERATE_TREEVIEW = YES -TREEVIEW_WIDTH = 250 -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = NO -LATEX_OUTPUT = latex -LATEX_CMD_NAME = latex -MAKEINDEX_CMD_NAME = makeindex -COMPACT_LATEX = NO -PAPER_TYPE = a4wide -EXTRA_PACKAGES = -LATEX_HEADER = -PDF_HYPERLINKS = NO -USE_PDFLATEX = NO -LATEX_BATCHMODE = NO -LATEX_HIDE_INDICES = NO -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = man -MAN_EXTENSION = .3 -MAN_LINKS = YES -#--------------------------------------------------------------------------- -# configuration options related to the XML output -#--------------------------------------------------------------------------- -GENERATE_XML = NO -XML_OUTPUT = xml -XML_SCHEMA = -XML_DTD = -XML_PROGRAMLISTING = YES -#--------------------------------------------------------------------------- -# configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- -GENERATE_AUTOGEN_DEF = NO -#--------------------------------------------------------------------------- -# configuration options related to the Perl module output -#--------------------------------------------------------------------------- -GENERATE_PERLMOD = NO -PERLMOD_LATEX = NO -PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = NO -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = C:/Dev/include -INCLUDE_FILE_PATTERNS = -PREDEFINED = HWRENDER \ - DIRECTFULLSCREEN \ - HW3SOUND -EXPAND_AS_DEFINED = -SKIP_FUNCTION_MACROS = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -EXTERNAL_GROUPS = YES -PERL_PATH = /usr/bin/perl -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -CLASS_DIAGRAMS = YES -HIDE_UNDOC_RELATIONS = YES -HAVE_DOT = NO -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -GROUP_GRAPHS = YES -UML_LOOK = NO -TEMPLATE_RELATIONS = NO -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -CALL_GRAPH = NO -GRAPHICAL_HIERARCHY = YES -DIRECTORY_GRAPH = YES -DOT_IMAGE_FORMAT = png -DOT_PATH = -DOTFILE_DIRS = -MAX_DOT_GRAPH_WIDTH = 1024 -MAX_DOT_GRAPH_HEIGHT = 1024 -MAX_DOT_GRAPH_DEPTH = 1000 -DOT_TRANSPARENT = NO -DOT_MULTI_TARGETS = NO -GENERATE_LEGEND = YES -DOT_CLEANUP = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to the search engine -#--------------------------------------------------------------------------- -SEARCHENGINE = NO diff --git a/tools/PHPD b/tools/PHPD deleted file mode 100644 index d2877f4e3..000000000 --- a/tools/PHPD +++ /dev/null @@ -1,239 +0,0 @@ -# Doxyfile 1.4.3 - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- -PROJECT_NAME = "SRB2 MasterServer IRC Bot and PHP stuff" -PROJECT_NUMBER = -OUTPUT_DIRECTORY = ../doc/IRC_Bot -CREATE_SUBDIRS = YES -OUTPUT_LANGUAGE = English -USE_WINDOWS_ENCODING = YES -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ABBREVIATE_BRIEF = "The $name class" \ - "The $name widget" \ - "The $name file" \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the -ALWAYS_DETAILED_SEC = NO -INLINE_INHERITED_MEMB = NO -FULL_PATH_NAMES = YES -STRIP_FROM_PATH = -STRIP_FROM_INC_PATH = -SHORT_NAMES = NO -JAVADOC_AUTOBRIEF = NO -MULTILINE_CPP_IS_BRIEF = NO -DETAILS_AT_TOP = NO -INHERIT_DOCS = YES -DISTRIBUTE_GROUP_DOC = NO -SEPARATE_MEMBER_PAGES = NO -TAB_SIZE = 8 -ALIASES = -OPTIMIZE_OUTPUT_FOR_C = NO -OPTIMIZE_OUTPUT_JAVA = NO -SUBGROUPING = YES -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- -EXTRACT_ALL = YES -EXTRACT_PRIVATE = YES -EXTRACT_STATIC = YES -EXTRACT_LOCAL_CLASSES = YES -EXTRACT_LOCAL_METHODS = NO -HIDE_UNDOC_MEMBERS = NO -HIDE_UNDOC_CLASSES = NO -HIDE_FRIEND_COMPOUNDS = NO -HIDE_IN_BODY_DOCS = NO -INTERNAL_DOCS = NO -CASE_SENSE_NAMES = NO -HIDE_SCOPE_NAMES = NO -SHOW_INCLUDE_FILES = YES -INLINE_INFO = YES -SORT_MEMBER_DOCS = YES -SORT_BRIEF_DOCS = NO -SORT_BY_SCOPE_NAME = NO -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -GENERATE_DEPRECATEDLIST= YES -ENABLED_SECTIONS = -MAX_INITIALIZER_LINES = 30 -SHOW_USED_FILES = YES -SHOW_DIRECTORIES = YES -FILE_VERSION_FILTER = -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = NO -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_IF_DOC_ERROR = YES -WARN_NO_PARAMDOC = NO -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = ./ -FILE_PATTERNS = *.php \ - *.php3 \ - *.inc \ - *.dox -RECURSIVE = YES -EXCLUDE = ./IRC_Bot/SmartIRC.php -EXCLUDE_SYMLINKS = NO -EXCLUDE_PATTERNS = */IRC_Bot/magpierss/* \ - */IRC_Bot/SmartIRC/* \ - */IRC_Bot/*SRB2MS_Pass.php -EXAMPLE_PATH = -EXAMPLE_PATTERNS = * -EXAMPLE_RECURSIVE = NO -IMAGE_PATH = -INPUT_FILTER = -FILTER_PATTERNS = -FILTER_SOURCE_FILES = YES -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- -SOURCE_BROWSER = YES -INLINE_SOURCES = YES -STRIP_CODE_COMMENTS = YES -REFERENCED_BY_RELATION = NO -REFERENCES_RELATION = NO -USE_HTAGS = NO -VERBATIM_HEADERS = YES -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = NO -COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = html -HTML_FILE_EXTENSION = .html -HTML_HEADER = -HTML_FOOTER = -HTML_STYLESHEET = -HTML_ALIGN_MEMBERS = YES -GENERATE_HTMLHELP = NO -CHM_FILE = -HHC_LOCATION = -GENERATE_CHI = NO -BINARY_TOC = NO -TOC_EXPAND = NO -DISABLE_INDEX = NO -ENUM_VALUES_PER_LINE = 4 -GENERATE_TREEVIEW = YES -TREEVIEW_WIDTH = 250 -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = NO -LATEX_OUTPUT = latex -LATEX_CMD_NAME = latex -MAKEINDEX_CMD_NAME = makeindex -COMPACT_LATEX = NO -PAPER_TYPE = a4wide -EXTRA_PACKAGES = -LATEX_HEADER = -PDF_HYPERLINKS = NO -USE_PDFLATEX = NO -LATEX_BATCHMODE = NO -LATEX_HIDE_INDICES = NO -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = man -MAN_EXTENSION = .3 -MAN_LINKS = YES -#--------------------------------------------------------------------------- -# configuration options related to the XML output -#--------------------------------------------------------------------------- -GENERATE_XML = NO -XML_OUTPUT = xml -XML_SCHEMA = -XML_DTD = -XML_PROGRAMLISTING = YES -#--------------------------------------------------------------------------- -# configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- -GENERATE_AUTOGEN_DEF = NO -#--------------------------------------------------------------------------- -# configuration options related to the Perl module output -#--------------------------------------------------------------------------- -GENERATE_PERLMOD = NO -PERLMOD_LATEX = NO -PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = NO -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = C:/Dev/include -INCLUDE_FILE_PATTERNS = -PREDEFINED = HWRENDER \ - DIRECTFULLSCREEN \ - HW3SOUND -EXPAND_AS_DEFINED = -SKIP_FUNCTION_MACROS = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -EXTERNAL_GROUPS = YES -PERL_PATH = /usr/bin/perl -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -CLASS_DIAGRAMS = YES -HIDE_UNDOC_RELATIONS = YES -HAVE_DOT = NO -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -GROUP_GRAPHS = YES -UML_LOOK = NO -TEMPLATE_RELATIONS = NO -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -CALL_GRAPH = NO -GRAPHICAL_HIERARCHY = YES -DIRECTORY_GRAPH = YES -DOT_IMAGE_FORMAT = png -DOT_PATH = -DOTFILE_DIRS = -MAX_DOT_GRAPH_WIDTH = 1024 -MAX_DOT_GRAPH_HEIGHT = 1024 -MAX_DOT_GRAPH_DEPTH = 1000 -DOT_TRANSPARENT = NO -DOT_MULTI_TARGETS = NO -GENERATE_LEGEND = YES -DOT_CLEANUP = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to the search engine -#--------------------------------------------------------------------------- -SEARCHENGINE = NO diff --git a/tools/anglechk.c b/tools/anglechk.c deleted file mode 100644 index 7f56abff7..000000000 --- a/tools/anglechk.c +++ /dev/null @@ -1,364 +0,0 @@ -/* - * anglechk.c - * - * Copyright 2007 Alam Arias - * - * 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 2 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, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include -#ifdef _MSC_VER -#include -#endif -#include "../src/tables.h" -#define NO_M -#include "../src/m_fixed.c" -#define FIXEDPOINTCONV - -// With angle_t, -// 360 deg = 2^32 -// 45 deg = 2^29 -// 1 deg = 2^29 / 45 -// To convert an angle to a fixed-point number of degrees, then, use -// fixed = angle * FRACUNIT / ((1<<29) / 45) -// But, done literally like that, this will overflow. -// It's mathematically equivalent to -// fixed = angle * (1<>(29-FRACBITS)) -// fixed = (angle>>(29-FRACBITS)) * 45 - -#define ANGLE_TO_FIXED(a) (fixed_t)(((a)>>(29-FRACBITS))*45) -#define FIXED_TO_ANGLE(x) (angle_t)(((x)/45)<<(29-FRACBITS)) - -/* -Old code that failed if FRACBITS was not 16. -In particular, the use of FRACUNIT in the definition of ANGLE_F is completely -wrong. The value wanted actually happens to be 65536 due to the definition -of angle_t (it's specified so that 360 degrees = 2^32, to take advantage of -modular arithmetic). That 65536 has nothing whatsoever to do with the setting -of FRACUNIT. - -#define ANGF_D 8192 -#define ANGF_N 45 -#define ANGLE_F (ANGF_N*FRACUNIT/ANGF_D) -#define FIXED_TO_ANGLE(x) (angle_t)FixedDiv(x, ANGLE_F) // angle_t = FixedDiv(fixed_t, ANGLE_F) -#define ANGLE_TO_FIXED(x) FixedMul((fixed_t)(x), ANGLE_F) // fixed_t = FixedMul(angle_t, ANGLE_F) -*/ - -static fixed_t AngleFixed204(angle_t af) -{ - const fixed_t cfn = 180*FRACUNIT; - if (af == 0) - return 0; - else if (af > ANGLE_180) - return cfn + ANGLE_TO_FIXED(af - ANGLE_180); - else if (af < ANGLE_180) - return ANGLE_TO_FIXED(af); - else return cfn; -} - -static inline angle_t FixedAngleC204(fixed_t fa, fixed_t factor) -{ -#if 0 //FixedMod off? - const boolean neqda = da < 0, neqfa = fa < 0; - const fixed_t afactor = abs(factor); - angle_t ra = ANGLE_180; - - if (factor == 0) - return FixedAngle204(fa); - else if (fa == 0) - return 0; - - if (neqfactor) - { - const fixed_t maf = FixedDiv(afactor, ANGLE_F); - const fixed_t cfn = FixedMul(360*FRACUNIT, afactor), hcfn = (cfn/2); - const fixed_t fam = FixedMod(fa, cfn); - - if (fam > hcfn) - ra = ANGLE_180 + (angle_t)FixedMul(fam - hcfn, maf); - else if (fam < hcfn) - ra = (angle_t)FixedMul(fam, maf); - } - else - { - const fixed_t maf = FixedMul(afactor, ANGLE_F); - const fixed_t cfn = FixedDiv(360*FRACUNIT, afactor), hcfn = (cfn/2); - const fixed_t fam = FixedMod(fa, cfn); - - if (fam > hcfn) - ra = ANGLE_180 + (angle_t)FixedDiv(fam - hcfn, maf); - else if (fam < hcfn) - ra = (angle_t)FixedDiv(fam, maf); - } - - if (neqfa) - ra = ANGLE_MAX-ra; - - return ra; -#else - if (factor == 0) - return FixedAngle(fa); - else if (factor > 0) - return (angle_t)((FIXED_TO_FLOAT(fa)/FIXED_TO_FLOAT(factor))*(ANGLE_45/45)); - else - return (angle_t)((FIXED_TO_FLOAT(fa)*FIXED_TO_FLOAT(-factor))*(ANGLE_45/45)); -#endif -} - -angle_t FixedAngle(fixed_t fa) -{ -#if 0 //FixedMod off? - const boolean neqfa = fa < 0; - const fixed_t cfn = 180*FRACUNIT; - const fixed_t fam = FixedMod(fa, 360*FRACUNIT); - angle_t ra = ANGLE_180; - - if (fa == 0) - return 0; - - if (fam > cfn) - ra = ANGLE_180+FIXED_TO_ANGLE(fam-cfn); - else if (fam < cfn) - ra = FIXED_TO_ANGLE(fam); - - if (neqfa) - ra = ANGLE_MAX-ra; - - return ra; -#else - return (angle_t)(FIXED_TO_FLOAT(fa)*(ANGLE_45/45)); -#endif -} - -fixed_t AngleFixed205(angle_t af) -{ -#ifdef FIXEDPOINTCONV - angle_t wa = ANGLE_180; - fixed_t wf = 180*FRACUNIT; - fixed_t rf = 0*FRACUNIT; - //const angle_t adj = 0x2000; - - //if (af < adj) // too small to notice - //return rf; - - while (af) - { - while (af < wa) - { - wa /= 2; - wf /= 2; - } - rf += wf; - af -= wa; - } - - return rf; -#else - const fixed_t cfn = 180*FRACUNIT; - if (af == 0) - return 0; - else if (af > ANGLE_180) - return cfn + ANGLE_TO_FIXED(af - ANGLE_180); - else if (af < ANGLE_180) - return ANGLE_TO_FIXED(af); - else return cfn; -#endif -} - -#ifdef FIXEDPOINTCONV -static FUNCMATH angle_t AngleAdj(const fixed_t fa, const fixed_t wf, - angle_t ra) -{ - const angle_t adj = 0x77; - const boolean fan = fa < 0; - const fixed_t sl = FixedDiv(fa, wf*2); - const fixed_t lb = FixedRem(fa, wf*2); - const fixed_t lo = (wf*2)-lb; - - if (ra == 0) - { - if (lb == 0) - { - ra = FixedMul(FRACUNIT/512, sl); - if (ra > FRACUNIT/64) - return ANGLE_MAX-ra+1; - return ra; - } - else if (lb > 0) - return ANGLE_MAX-FixedMul(lo*FRACUNIT, adj)+1; - else - return ANGLE_MAX-FixedMul(lo*FRACUNIT, adj)+1; - } - - if (fan) - return ANGLE_MAX-ra+1; - else - return ra; -} -#endif - -angle_t FixedAngleC205(fixed_t fa, fixed_t factor) -{ -#ifdef FIXEDPOINTCONV - angle_t wa = ANGLE_180; - fixed_t wf = 180*FRACUNIT; - angle_t ra = 0; - const fixed_t cfa = fa; - fixed_t cwf = wf; - - if (fa == 0) - return 0; - - if (factor == 0) - return FixedAngle(fa); - else if (factor > 0) - cwf = wf = FixedMul(wf, factor); - else if (factor < 0) - cwf = wf = FixedDiv(wf, -factor); - - fa = abs(fa); - - while (fa) - { - while (fa < wf) - { - wa /= 2; - wf /= 2; - } - ra = ra + wa; - fa = fa - wf; - } - - return AngleAdj(cfa, cwf, ra); -#else - if (factor == 0) - return FixedAngle(fa); - - //fa = FixedMod(fa, 360*FRACUNIT); - - if (factor > 0) - return (angle_t)((FIXED_TO_FLOAT(fa)/FIXED_TO_FLOAT(factor))*(ANGLE_45/45)); - else - return (angle_t)((FIXED_TO_FLOAT(fa)*FIXED_TO_FLOAT(-factor))*(ANGLE_45/45)); -#endif -} - -angle_t FixedAngle205(fixed_t fa) -{ -#ifdef FIXEDPOINTCONV - angle_t wa = ANGLE_180; - fixed_t wf = 180*FRACUNIT; - angle_t ra = 0; - const fixed_t cfa = fa; - const fixed_t cwf = wf; - - if (fa == 0) - return 0; - - fa = abs(fa); - - while (fa) - { - while (fa < wf) - { - wa /= 2; - wf /= 2; - } - ra = ra + wa; - fa = fa - wf; - } - - return AngleAdj(cfa, cwf, ra); -#else - //fa = FixedMod(fa, 360*FRACUNIT); - - if (fa == 0) - return 0; - - return (angle_t)(FIXED_TO_FLOAT(fa)*(ANGLE_45/45)); -#endif -} - -int main(int argc, char** argv) -{ - fixed_t f, f204, f205; - INT64 a; - angle_t a204, a205; - fixed_t CF = 40*FRACUNIT; - int err = 0; - (void)argc; - (void)argv; - - err = 0x29; //41 - - if (1) - for (a = 0; a < ANGLE_MAX; a += 0x1) - { - f204 = AngleFixed204((angle_t)a); - f205 = AngleFixed205((angle_t)a); - if (f204 != f205 && (abs(f204-f205) > err || f204 == 0 || f205 == 0)) - { - printf("Angle: %u, %d, %d, %d\n", (angle_t)a, f204, f205, f204-f205); - //err = abs(f204-f205); - } - } - - //err = FixedDiv(FRACUNIT, 120*FRACUNIT); // 547 - err = FixedDiv(FRACUNIT, 62*FRACUNIT); //1059 - - if (1) - for (f = FRACUNIT*-720; f < FRACUNIT*720; f += 1) - { - a204 = FixedAngle(f); - a205 = FixedAngle205(f); - if (a204 != a205 && (abs(a204-a205) > err || a204 == 0 || a205 == 0)) - { - printf("Fixed: %f, %u, %u, %d\n", FIXED_TO_FLOAT(f), a204, a205, a204-a205); - err = abs(a204-a205); - } - } - - //err = FixedDiv(FRACUNIT, 316*FRACUNIT); //207 - err = FixedDiv(FRACUNIT, 125*FRACUNIT); //526 - - if (1) - for (f = FixedMul(FRACUNIT*-720, CF); f < FixedMul(FRACUNIT*720, CF); f += FRACUNIT/16) - { - a204 = FixedAngleC204(f, CF); - a205 = FixedAngleC205(f, CF); - if (a204 != a205 && (abs(a204-a205) > err || a204 == 0 || a205 == 0)) - { - printf("FixedC: %f, %u, %u, %d\n", FIXED_TO_FLOAT(f), a204, a205, a204-a205); - //err = abs(a204-a205); - } - } - - return 0; -} - -static void *cpu_cpy(void *dest, const void *src, size_t n) -{ - return memcpy(dest, src, n); -} - -void *(*M_Memcpy)(void* dest, const void* src, size_t n) = cpu_cpy; - -void I_Error(const char *error, ...) -{ - (void)error; - exit(-1); -} diff --git a/tools/convert.c b/tools/convert.c deleted file mode 100644 index 0ab0cb132..000000000 --- a/tools/convert.c +++ /dev/null @@ -1,35 +0,0 @@ -// convert corona.raw in a pic_t as corona2.raw - -#include - -typedef struct -{ - short width; - char reserved0; // set to 0 - char mode; // see pic_mode_t above - short height; - short reserved1; // set to 0 -} pic_t; - -void main(int argc, char *argv[]) -{ - int i, j, k; - char buf1[256][256], buf2[256][256][2]; - pic_t pic = {256, 0, 2, 256, 0}; - FILE *g; - - FILE *f = fopen("corona.raw", "rb"); - fread(buf1, 256*256, 1, f); - fclose(f); - - g = fopen("corona2.raw", "wb"); - for (i = 0; i < 256; i++) - for (j = 0; j < 256; j++) - { - buf2[i][j][0] = buf1[i][j]; - buf2[i][j][1] = buf1[i][j]; - } - fwrite(&pic, sizeof (pic_t), 1, g); - fwrite(buf2, sizeof (buf2), 1, g); - fclose(g); -} diff --git a/tools/dircomp2.c b/tools/dircomp2.c deleted file mode 100644 index 96a55f36f..000000000 --- a/tools/dircomp2.c +++ /dev/null @@ -1,1028 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (C) 1998-2000 by Boris Pereira. -// -// 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 2 -// 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. -//----------------------------------------------------------------------------- - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include"keys.h" - - -#define true 1 -#define false 0 - -#define MAXLINE 32768 -#define MAXLENLINE 4096 -#define SCREENWIDTH 80 - -typedef struct { - int lines; - char *line[MAXLINE]; -} textfile_t; - -char tempfilename[255],editor[128]="c:\\program files\\ultraedit\\uedit32.exe"; -int sameline=3,tab1=8,tab2=8; -int screenline=25; -textfile_t f1,f2; -int nonewfile = false; -int compspace = false; - -unsigned short colornormal = ( BLACK<<4) + LIGHTGRAY; -unsigned short colortitle = ( BLACK<<4) + WHITE; -unsigned short colortext = ( BLACK<<4) + DARKGRAY; -unsigned short colordiff = ( BLACK<<4) + LIGHTRED; -unsigned short colorkeys = ( BLACK<<4) + LIGHTCYAN; - - -// compare directorys -void CompareDir(char *dir1,char *dir2); - -// compare directorys this one check only for missing file -void CompareDir2(char *dir1,char *dir2); - -// compare files -void CompareFile(char *filename1,char *filename2); - -// copy a file -void fcopy(char *filename1,char *filename2); - -// recursive delete a dir -void dirunlink(char *dirname); - -// recursive copy a dir -void copydir(char *dirname1,char *dirname2); - -void Quit(char *f,...) -{ - va_list argptr; - - // put message to stderr - va_start (argptr,f); - fprintf (stderr, "Error: "); - vfprintf (stderr,f,argptr); - va_end (argptr); - - fflush( stderr ); - exit(-1); -} - -int CheckParm(int argc, char *argv[], char *param ) -{ - int i; - for(i=1;i []\n\n" - " Options\n" - " -------\n" - " -t1 n : change tab size for directory 1 (default 8)\n" - " -t2 n : change tab size for directory 2 (default 8)\n" - " -l n : use n same line to resynchronize (default 3)\n" - " -e : use spesified editor\n" - " -nonew: don't prompt to copy/delete file\n" - " -w compress space and tab"); - - if(findfirst(argv[1],&dir,FA_DIREC)) - Quit("Error can't find %s\n",argv[1]); - - if(findfirst(argv[2],&dir,FA_DIREC)) - Quit("Error can't find %s\n",argv[2]); - - if(argc>2) - { - i=CheckParm(argc,argv,"-t1"); - if(i) tab1=atoi(argv[i+1]); - i=CheckParm(argc,argv,"-t2"); - if(i) tab2=atoi(argv[i+1]); - i=CheckParm(argc,argv,"-l"); - if(i) sameline=atoi(argv[i+1]); - i=CheckParm(argc,argv,"-e"); - if(i) strcpy(editor,argv[i+1]); - nonewfile=CheckParm(argc,argv,"-nonew"); - compspace=CheckParm(argc,argv,"-w"); - } - - _set_screen_lines(50); - screenline=50; - // desable blink color so we can use darkcolor for background - //outportb(0x3b8,5); - intensevideo(); - - tmp=getenv("temp"); - if(!tmp) - tmp=getenv("TEMP"); - if(!tmp) - tmp=getenv("tmp"); - if(!tmp) - tmp=getenv("TMP"); - if(tmp) - { - strcpy(tempfilename,tmp); - if(tempfilename[strlen(tempfilename)]!='\\') - strcat(tempfilename,"\\"); - } - else - tempfilename[0]='\0'; - strcat(tempfilename,"dircmp$$.tmp"); - - CompareDir(argv[1],argv[2]); - - if(!nonewfile) - // just for file in the directory 2 and not in the 1 - CompareDir2(argv[1],argv[2]); - - return 0; -} - -char *fileextension(char *filename) -{ - static char nullextension=0; - int i; - i = strlen(filename)-1; - while(i>0 && filename[i]!='.') i--; - if( filename[i]=='.' ) - return filename+i+1; - // else - return &nullextension; -} - -void CompareDir(char *dirname1,char *dirname2) -{ - struct ffblk dir; - char filter[20]="\\*.*"; - char tempstr[255]; - int finish; - - strcpy(tempstr,dirname1); - strcat(tempstr,filter); - - printf("Comparing %s and %s\n",dirname2,dirname1); - - // enter in directorys first - finish=findfirst(tempstr,&dir,FA_DIREC); - while(!finish) - { - char tempstr2[255],tempstr3[255]; - - strcpy(tempstr2,dirname1); - strcat(tempstr2,"\\"); - strcat(tempstr2,dir.ff_name); - - strcpy(tempstr3,dirname2); - strcat(tempstr3,"\\"); - strcat(tempstr3,dir.ff_name); - - - if(dir.ff_attrib & FA_DIREC) - { - if(dir.ff_name[0]!='.' && strcmp(dir.ff_name,"CVS")!=0) - { - int check,choice; - check=access(tempstr3,F_OK); - if( check ) - { - printf("\nDirectory missing : %s\n" - "Delete %s ? (Y/N)\n",tempstr3,tempstr2); - do { - choice=getch(); - } while(choice!='y' && choice!='n' - && choice!='Y' && choice!='N'); - - if( choice=='y' || choice=='Y' ) - dirunlink(tempstr2); - } - else - CompareDir(tempstr2,tempstr3); - } - } - finish=findnext(&dir); - } - - finish=findfirst(tempstr,&dir,0); - while(!finish) - { - char tempstr2[255],tempstr3[255]; - - strcpy(tempstr2,dirname1); - strcat(tempstr2,"\\"); - strcat(tempstr2,dir.ff_name); - - strcpy(tempstr3,dirname2); - strcat(tempstr3,"\\"); - strcat(tempstr3,dir.ff_name); - - if((dir.ff_attrib & FA_DIREC)==0) - { - int check; - char *ext; - - ext = fileextension(dir.ff_name); - if( !(stricmp(ext,"dsp")==0 || - stricmp(ext,"dep")==0 || - stricmp(ext,"dsw")==0 || - stricmp(ext,"ncb")==0 || - stricmp(ext,"bmp")==0 || - stricmp(ext,"opt")==0 || - stricmp(ext,"plg")==0 || - stricmp(ext,"ico")==0 || - stricmp(ext,"rc" )==0 || - stricmp(ext,"o" )==0 || - stricmp(ext,"bat")==0 || - stricmp(ext,"obj")==0 )) - { - printf("Comparing %s and %s\n",tempstr2,tempstr3); - check=access(tempstr3,F_OK); - - if(check) - { - // seconde file not found - int choice; - if(!nonewfile) - { - printf("\nFile missing : %s\n" - "Delete %s ? (Y/N)\n",tempstr3,tempstr2); - do { - choice=getch(); - } while(choice!='y' && choice!='n' - && choice!='Y' && choice!='N'); - - if(choice=='y' || choice=='Y') - unlink(tempstr2); - } - } - else - { - struct stat fs1,fs2; - stat(tempstr2,&fs1); - stat(tempstr3,&fs2); - - if(fs1.st_atime!=fs2.st_atime || fs1.st_size!=fs2.st_size) - CompareFile(tempstr2,tempstr3); - } - printf("\n"); - } - } - finish=findnext(&dir); - } -} - -// find file in dir2 but not in dir1 -void CompareDir2(char *dirname1,char *dirname2) -{ - struct ffblk dir; - char filter[20]="\\*.*"; - char tempstr[255]; - int finish; - - strcpy(tempstr,dirname2); - strcat(tempstr,filter); - - printf("Comparing %s and %s\n",dirname1,dirname2); - - finish=findfirst(tempstr,&dir,FA_DIREC); - while(!finish) - { - char tempstr2[255],tempstr3[255]; - - strcpy(tempstr2,dirname1); - strcat(tempstr2,"\\"); - strcat(tempstr2,dir.ff_name); - - strcpy(tempstr3,dirname2); - strcat(tempstr3,"\\"); - strcat(tempstr3,dir.ff_name); - - - if(dir.ff_attrib & FA_DIREC) - { - if(dir.ff_name[0]!='.' && strcmp(dir.ff_name,"CVS")!=0) - { - int check,choice; - check=access(tempstr3,F_OK); - if( check ) - { - printf("\nDirectory missing : %s\n" - "Copy %s ? (Y/N)\n",tempstr3,tempstr2); - do { - choice=getch(); - } while(choice!='y' && choice!='n' - && choice!='Y' && choice!='N'); - - if( choice=='y' || choice=='Y' ) - copydir(tempstr2,tempstr3); - } - else - CompareDir2(tempstr2,tempstr3); - } - } - finish=findnext(&dir); - } - - finish=findfirst(tempstr,&dir,FA_DIREC); - while(!finish) - { - char tempstr2[255],tempstr3[255]; - - strcpy(tempstr2,dirname1); - strcat(tempstr2,"\\"); - strcat(tempstr2,dir.ff_name); - - strcpy(tempstr3,dirname2); - strcat(tempstr3,"\\"); - strcat(tempstr3,dir.ff_name); - - if((dir.ff_attrib & FA_DIREC)==0) - { - char *ext = fileextension(dir.ff_name); - if( !(stricmp(ext,"dsp")==0 || - stricmp(ext,"dep")==0 || - stricmp(ext,"dsw")==0 || - stricmp(ext,"ncb")==0 || - stricmp(ext,"bmp")==0 || - stricmp(ext,"opt")==0 || - stricmp(ext,"plg")==0 || - stricmp(ext,"ico")==0 || - stricmp(ext,"rc" )==0 || - stricmp(ext,"o" )==0 || - stricmp(ext,"bat")==0 || - stricmp(ext,"obj")==0 ) && - // check if file exist in dir1 - access(tempstr2,F_OK)) - { - int choice; - - printf("File %s found in %s but not in %s\n" - "Copy it ? (y/n)\n",tempstr3,dirname2,dirname1); - do { - choice=getch(); - } while(choice!='y' && choice!='n'); - - if(choice=='y') - fcopy(tempstr2,tempstr3); - - return; - - - } - } - finish=findnext(&dir); - } -} - -// convert tab to space -char *tabconv(char *c,int tabsize) -{ - static char buf[MAXLENLINE]; - int i=0,j=0; - - while(c[i]) - { - if(c[i]=='\t') - { - do { - buf[j++]=' '; - } while(j % tabsize); - } - else - buf[j++]=c[i]; - i++; - } - -/* - if(j>maxline) - { - buf[maxline-1]='\n'; // trunc - j=maxline; - } -*/ - buf[j]=0; - - return buf; -} - -void tabconv2(textfile_t *f,int start,int stop) -{ - static char buf[MAXLENLINE]; - char *c; - int i,j,k; - - for(k=start;k<=stop;k++) - { - c=f->line[k]; - i=j=0; - while(c[i]) - { - if(c[i]=='\t' && c[i+1]=='\t') - { - buf[j++]='\t'; - } - else - if(c[i]=='\t') - do { buf[j++]=' '; } while(j & 3); - else - buf[j++]=c[i]; - i++; - } - buf[j]=0; - free(f->line[k]); - f->line[k]=(char *)malloc(j); - strcpy(f->line[k],buf); - } -} - -int c; - -void initmyfgets( FILE *stream ) -{ - c = fgetc(stream); -} - -// convert any f*** format to the good one -char *myfgets( char *string, int n, FILE *stream ) -{ - int i=0; - char *s=string; - if( c==EOF ) - return NULL; - while( i=MAXLINE) - Quit("File %s too big, more than %d lines\n",filename,MAXLINE); - if(!myfgets(buf,MAXLENLINE,f)) - break; - if( convtab ) - strcpy(buf,tabconv(buf,tabsize)); - file->line[i]=(char *)malloc(strlen(buf)+1); - strcpy(file->line[i],buf); - i++; - } - fclose(f); - - file->lines=i; - - for(;iline[i]=eofline; -} - -void FreeTextFile(textfile_t *file) -{ - int i; - - for(i=0;ilines;i++) - free(file->line[i]); - - file->lines = 0; -} - -// afficher une partie de fichier en partant de startline jusqu'a stop line -// affiche les ligne redbeg jusqua redstop en rouge -// decale le text vers la droite de offset caractere -void PrintfBlock(textfile_t *f,int start,int redbeg,int redstop,int stop, int offset) -{ - int i,l; - char save80,save81,*p; - - if(start<0) - start=0; - - for(i=start;i<=stop;i++) - { - if(i>=redbeg && i<=redstop) - textattr(colordiff); - else - textattr(colortext); - if( f->line[i] ) - l=strlen(f->line[i]); - else - l=0; - if(l<=offset) - { - cprintf("\n\r"); - continue; - } - p=&(f->line[i][offset]); - l-=offset; - if( l>SCREENWIDTH-1) - { - save80=p[SCREENWIDTH-2]; - save81=p[SCREENWIDTH-1]; - if( p[SCREENWIDTH-2]!='\0') - p[SCREENWIDTH-2]='\n'; - p[SCREENWIDTH-1]='\0'; - cprintf("%s\r",p); - p[SCREENWIDTH-2]=save80; - p[SCREENWIDTH-1]=save81; - } - else - cprintf("%s\r",p); - } -} - -// copy only the syntax, compress all spacing in 1 space -char *delspace(char *s) -{ -static char buf[MAXLENLINE]; - int i=0,j=0; - - if( !compspace ) - { - // remove just trailing space - strcpy(buf, s); - for(i = strlen(buf)-1;(buf[i]==' ' || buf[i]=='\n' || buf[i]=='\r') && i>=0;i--) - buf[i]='\0'; - buf[i+1]='\n'; - buf[i+2]='\0'; - return buf; - } - - while(s[i]!='\n' && s[i]) - { - if(s[i]==' ') - { - while(s[i]==' ' && s[i]!='\n' && s[i]) { i++; } - if(s[i]!='\n' && s[i]) - buf[j++]=' '; - } - else - buf[j++]=s[i++]; - } - buf[j++]='\n'; - buf[j]='\0'; - - return buf; -} - -int LineCmp(char **a1,char **a2,int linetocmp) -{ - char buf[MAXLENLINE]; - char buf2[MAXLENLINE]; - int i; - - for(i=0;iline[line1+i-j] - ,&f2->line[line2+j],sameline)) - { - *ri=i-j; - *rj=j; - - return; - } - animcount++; - animcount&=0xF; - // not to mush printf this slowdown a lot - if( (animcount&3)==0 ) - cprintf("\b%c",anim[animcount>>2]); - } - Quit("Too mush difference between the files\n"); -} - -void cnprintf(char *s,int n) -{ - int i; - for(i=0;i%c%c] [-]%d lines[+] [u]ndo [e]dit [c]ompress space",27,26,sameline); - fflush(stdout); - textattr(colornormal); -} - -// copy file date of source to dest -void CopyFileDate(char *dest,char *source) -{ - struct stat fs1; - struct utimbuf fs2; - - stat(source,&fs1); - fs2.actime = fs1.st_mtime; - fs2.modtime = fs1.st_mtime; - - utime(dest,&fs2); -} - -void CompareFile(char *filename1,char *filename2) -{ - int i,j,choice,k,l; - int line1,line2; - FILE *outfile; - int maxlines,always,enterline=0,column=0; - int oneselected=false,twoselected=false; - - LoadTextFile(filename1,&f1,tab1); - LoadTextFile(filename2,&f2,tab2); - outfile=fopen(tempfilename,"wt"); - if( !outfile ) - Quit("Error: No way to open %s\n",tempfilename); - line1=0; - line2=0; - always=0; - maxlines=f1.lines+f2.lines+1; - -// if(maxlines1 ) { - sameline--; - Resynchronize(&f1,line1,&f2,line2,&i,&j,maxlines,sameline); - } - break; - case 'c' : - compspace = !compspace; - Resynchronize(&f1,line1,&f2,line2,&i,&j,maxlines,sameline); - break; -/* - case 't' : - tabconv2(&f1,line1,line1+i-1); - Resynchronize(&f1,line1,&f2,line2,&i,&j,maxlines,sameline); - break; -*/ - case 'p' : always=1;break; - case 'd' : always=2;break; - case 'u' : - fclose(outfile); - FreeTextFile(&f1); - FreeTextFile(&f2); - - // remove the temp file - unlink(tempfilename); - - CompareFile(filename1,filename2); - - return; - case 'e' : - { - char params[256]; - fclose(outfile); - FreeTextFile(&f1); - FreeTextFile(&f2); - - // remove the temp file - unlink(tempfilename); - - sprintf(params,"\"%s/%d\" \"%s/%d\"",filename1,line1,filename2,line2); - - spawnlp(P_WAIT,editor,params,params,NULL); - printf("\n\nHit Enter to continue\n"); - getchar(); - - CompareFile(filename1,filename2); - return; - } - } - - } while(choice!='3' && choice!='9' && always==0); - } - printf("\n"); - - if(choice=='9'|| always==1) - { - int blankline; - for(blankline=0;blankline /dev/null 2>&1 - -$(RM) $@ - $(FOR) f in $(SRC); do \ - $(SHCC) $(CPPFLAGS) $(CFLAGS) -MM $$f >> $@; \ - done --include $@ - -%.o: %.c -ifndef V - $(ECHO) " $(PRCC)$@" -endif - $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ - -$(BIN): $(OBJ) -ifndef V - $(ECHO) " $(PRCC)$@" -endif - $(CC) $(LDFLAGS) -o $@ $(OBJ) $(LIB) - -$(STABIN): $(OBJ) -ifndef V - $(ECHO) " $(PRAR)$@" -endif - $(AR) rcs $@ $(OBJ) - -install: all install-libs install-headers - -install-libs: - $(MKDIR) $(LIBDIR) -ifndef V - $(FOR) f in $(LIBS); do \ - $(SHECHO) " $(PRINSTALL)$$f"; \ - $(SHINSTALL) $$f $(LIBDIR); \ - done -else - $(FOR) f in $(LIBS); do \ - $(SHINSTALL) $$f $(LIBDIR); \ - done -endif - $(LDCONFIG) - -install-headers: - $(MKDIR) $(INCLUDE) -ifndef V - $(FOR) f in $(HEADERS); do \ - $(SHECHO) " $(PRINSTALL)$$f"; \ - $(SHINSTALL) $$f $(INCLUDE); \ - done -else - $(FOR) f in $(HEADERS); do \ - $(SHINSTALL) $$f $(INCLUDE); \ - done -endif - -clean: -ifndef V - $(ECHO) " $(PRCLEAN)$(OBJ) $(LIBS)" -endif - -$(RM) $(OBJ) $(LIBS) - -distclean: -ifndef V - $(ECHO) " $(PRCLEAN)$(BINDIR)" -endif - -$(RM) $(BINDIR) - - -.PHONY : all install install-libs install-headers clean diff --git a/tools/libwad/examples/wadexample/Makefile b/tools/libwad/examples/wadexample/Makefile deleted file mode 100644 index 773733b06..000000000 --- a/tools/libwad/examples/wadexample/Makefile +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env make -f - -## wadexample: libwad example program. -## Copyright (C) 2011 by Callum Dickinson. -# -## 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 2 -## 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. - -# Program name. -PRONAME = wadexample -# Program version. -PROVER = 1.0.0 - -# Program default options. -CPPFLAGS += -DPRONAME="$(PRONAME)" -DPROVER="$(PROVER)" - -# Source files and directory. -SRC = wadexample.c - -# Required libraries. -LIB = -lwad - -# -## Variables that shouldn't be edited unless -## you know what you are doing start here. -# - -# Makefile pretty text output variables. -PRCC = CC -PRINSTALL=INSTALL -PRCLEAN = CLEAN - -# Library name prefix. -LIBPFX = lib - -# Library installation directory. -PREFIX ?= /usr/local -LIBDIR := $(PREFIX)/lib -INCLUDE := $(PREFIX)/include - -# Variables created during compilation. -OBJ = $(SRC:.c=.o) -DEP = $(PRONAME).d -ifdef MINGW -BIN = $(PRONAME).exe -else -BIN = $(PRONAME) -endif - -# Compilation programs. -ECHO := echo -RM := $(RM) -r -FIND := find -GREP := grep -INSTALLX:= install -m 755 -MKDIR := mkdir -p -FOR := for -SED := sed -CC := $(CROSS_COMPILE)$(CC) - -# Shell programs. -SHECHO := $(ECHO) -SHFIND := $(FIND) -SHGREP := $(GREP) -SHINSTALL:= $(INSTALL) -SHSED := $(SED) -SHCC := $(CC) - -# Quiet compiling programs during pretty text output. -NULL := /dev/null 2>&1 -ECHO := @$(ECHO) -ifndef V -RM := @$(RM) -LDCONFIG:= @$(LDCONFIG) -FIND := @$(FIND) -GREP := @$(GREP) -INSTALL := @$(INSTALL) -MKDIR := @$(MKDIR) -FOR := @$(FOR) -SED := @$(SED) -CC := @$(CC) -endif - -# Compiler default flags. -ifdef DEBUG -CFLAGS += -g -O0 -Wall -W -endif - -# Linker flags. -#LDFLAGS += - -# -## Makefile targets. -# - -all: $(DEP) $(BIN) - -$(DEP): $(SRC) -ifndef V - $(ECHO) " $(PRCC)$@" -endif - -$(RM) $@ - $(FOR) f in $(SRC); do \ - $(SHCC) $(CPPFLAGS) $(CFLAGS) -MM $$f >> $@; \ - done --include $@ - -%.o: %.c -ifndef V - $(ECHO) " $(PRCC)$@" -endif - $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ - -$(BIN): $(OBJ) -ifndef V - $(ECHO) " $(PRCC)$@" -endif - $(CC) $(LDFLAGS) -o $@ $(OBJ) $(LIB) - -install: all -ifndef V - $(SHECHO) " $(PRINSTALL)$(BIN)" -endif - $(INSTALLX) $(BIN) $(INSTALLDIR) - -clean: -ifndef V - $(ECHO) " $(PRCLEAN)$(OBJ) $(DEP)" -endif - -$(RM) $(OBJ) $(DEP) - -.PHONY : all install clean diff --git a/tools/libwad/examples/wadexample/wadexample.c b/tools/libwad/examples/wadexample/wadexample.c deleted file mode 100644 index 5e35a1e4d..000000000 --- a/tools/libwad/examples/wadexample/wadexample.c +++ /dev/null @@ -1,64 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// wadexample: libwad example program. -// Copyright (C) 2011 by Callum Dickinson. -// -// 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 2 -// 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. -//----------------------------------------------------------------------------- -/// \file wadconv.c -/// \brief Converts wads made for version 2.0 to 2.1. - -#include -#include -#include -#include -#include "wad.h" - -int main(int argc, char **argv) -{ - wad_uint32_t i; - - wad_t *w; - lump_t *l; - - if (argc < 2) - { - puts("Usage: wadexample [filename] [..]"); - puts("Example: example wadfile.wad wadfile2.wad"); - return EXIT_FAILURE; - } - - // Open the WAD files. - puts("Opening WADs..."); - for (i = 1; i < (unsigned)argc; i++) - { - if (!WAD_OpenWAD(argv[i])) - { - printf("Error opening WAD %s: %s\n", argv[i], WAD_Error()); - return 1; - } - } - - for (i = 0; i < wad_numwads; i = WAD_WADLoopAdvance(i)) - { - w = WAD_WADByNum(i); - printf("List of lumps inside wad %s:\n", WAD_BaseName(w->filename)); - for (l = w->lumps; l; l = l->next) - printf("Lump #%i: %s\n", l->num, l->name); - } - - puts("Closing WADs..."); - for (i = 0; i < wad_numwads; i++) - WAD_CloseWADByNum(i); - - return EXIT_SUCCESS; -} diff --git a/tools/libwad/include/wad.h b/tools/libwad/include/wad.h deleted file mode 100644 index 298a478b7..000000000 --- a/tools/libwad/include/wad.h +++ /dev/null @@ -1,227 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// libwad: Doom WAD format interface library. -// Copyright (C) 2011 by Callum Dickinson. -// -// 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 2 -// 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. -//----------------------------------------------------------------------------- -/// \file wad.h -/// \brief WAD file manipulation library. - -#ifndef __WAD_H__ -#define __WAD_H__ - -#ifdef __cplusplus -extern "C" -{ -#endif - -// -// Exact-width integer types. -// -#ifdef _MSC_VER -typedef signed __int8 wad_int8_t; -typedef unsigned __int8 wad_uint8_t; - -typedef __int16 wad_int16_t; -typedef unsigned __int16 wad_uint16_t; - -typedef __int32 wad_int32_t; -typedef unsigned __int32 wad_uint32_t; - -typedef __int64 wad_int64_t; -typedef unsigned __int64 wad_uint64_t; - -// Older Visual C++ headers don't have the Win64-compatible typedefs... -#if ((_MSC_VER <= 1200) && (!defined(DWORD_PTR))) -#define DWORD_PTR DWORD -#endif - -#if ((_MSC_VER <= 1200) && (!defined(PDWORD_PTR))) -#define PDWORD_PTR PDWORD -#endif - -#elif defined (_arch_dreamcast) -#include - -typedef signed char wad_int8_t; -typedef unsigned char wad_uint8_t; - -typedef int16 wad_int16_t; -typedef uint16 wad_uint16_t; - -typedef int wad_int32_t; -typedef unsigned int wad_uint32_t; - -typedef int64 wad_int64_t; -typedef uint64 wad_uint64_t; -#elif defined (__DJGPP__) -typedef signed char wad_int8_t; -typedef unsigned char wad_uint8_t; - -typedef signed short int wad_int16_t; -typedef unsigned short int wad_uint16_t; - -typedef signed long wad_int32_t; -typedef unsigned long wad_uint32_t; - -typedef signed long long wad_int64_t; -typedef unsigned long long wad_uint64_t; -#else -#define __STDC_LIMIT_MACROS -#include - -typedef int8_t wad_int8_t; -typedef uint8_t wad_uint8_t; - -typedef int16_t wad_int16_t; -typedef uint16_t wad_uint16_t; - -typedef int32_t wad_int32_t; -typedef uint32_t wad_uint32_t; - -typedef int64_t wad_int64_t; -typedef uint64_t wad_uint64_t; -#endif - -typedef enum -{ - false, - true -} wad_boolean_t; - -typedef struct -{ - char id[4]; // The WAD header's 4-character ID. - wad_uint32_t numlumps; // The number of lumps the WAD has. - wad_uint32_t lumpdir; // The pointer to the lump directory. -} wadheader_t; - -typedef struct wad_s -{ - char *filename; // The filename of the open WAD. - - wadheader_t *header; // The WAD's header. - wad_boolean_t compressed; - - struct lump_s *lumps; // The WAD's lumps buffer. -} wad_t; - -typedef struct lump_s -{ - wad_t *wad; // The WAD the lump belongs to. - - char name[9]; // The name of the lump. - - wad_uint64_t disksize; // The size of the lump on disk. - size_t size; // The real (uncompressed) size of the lump. - - wad_boolean_t compressed; - - void *data; // The actual lump data. - - wad_uint32_t num; // The lump number in the WAD. - struct lump_s *prev; // The previous node in the tree. - struct lump_s *next; // The next node in the tree. -} lump_t; - -// a raw entry of the wad directory -typedef struct -{ - wad_uint32_t position; // The position of the lump in the WAD file. - wad_uint32_t size; // Size of the lump. - char name[8]; // The lump's name. -} lumpdir_t; - -// -// wad_static.c -// Static file for internal libwad operations. -// -extern char *WAD_Error(void); -extern char *WAD_BaseName(char *path); -extern char *WAD_VA(const char *format, ...); - -extern inline wad_int16_t WAD_INT16_Endianness(wad_int16_t x); -extern inline wad_int32_t WAD_INT32_Endianness(wad_int32_t x); - -// -// wad.c -// WAD interface functionality. -// -extern wad_uint32_t wad_numwads; - -extern wad_uint32_t WAD_WADLoopAdvance(wad_uint32_t i); - -extern wad_t *WAD_WADByNum(wad_uint16_t num); -extern wad_t *WAD_WADByFileName(const char *filename); - -extern wad_t *WAD_OpenWAD(const char *filename); - -extern wad_int32_t WAD_SaveWAD(wad_t *wad); -extern inline wad_int32_t WAD_SaveWADByNum(wad_uint16_t num); -extern inline wad_int32_t WAD_SaveWADByFileName(const char *filename); - -extern inline wad_int32_t WAD_SaveCloseWAD(wad_t *wad); -extern inline wad_int32_t WAD_SaveCloseWADByNum(wad_uint16_t num); -extern inline wad_int32_t WAD_SaveCloseWADByFileName(const char *filename); - -extern void WAD_CloseWAD(wad_t *wad); -extern inline void WAD_CloseWADByNum(wad_uint16_t num); -extern inline void WAD_CloseWADByFileName(const char *filename); - -// -// lump.c -// Lump interface functionality. -// -extern char *WAD_LumpNameFromFileName(char *path); -extern lump_t *WAD_LumpInWADByNum(wad_t *wad, wad_uint32_t num); -extern lump_t *WAD_LumpInWADByName(wad_t *wad, const char *name); -extern lump_t *WAD_LumpByName(const char *name); - -extern inline wad_uint32_t WAD_LumpNum(lump_t *lump); -extern inline wad_uint32_t WAD_LumpNumInWADByName(wad_t *wad, const char *name); -extern inline wad_uint32_t WAD_LumpNumByName(const char *name); - -extern inline size_t WAD_LumpSize(lump_t *lump); -extern inline size_t WAD_LumpSizeInWADByName(wad_t *wad, const char *name); -extern inline size_t WAD_LumpSizeByName(const char *name); - -extern lump_t *WAD_AddLump(wad_t *wad, lump_t *destlump, const char *name, const char *filename); -extern inline lump_t *WAD_AddLumpInWADByNum(wad_t *wad, wad_uint32_t num, const char *name, const char *filename); -extern inline lump_t *WAD_AddLumpInWADByName(wad_t *wad, const char *destname, const char *name, const char *filename); -extern inline lump_t *WAD_AddLumpByName(const char *destname, const char *name, const char *filename); - -extern lump_t *WAD_CacheLump(lump_t *lump); -extern inline lump_t *WAD_CacheLumpInWADByNum(wad_t *wad, wad_uint32_t num); -extern inline lump_t *WAD_CacheLumpInWADByName(wad_t *wad, const char *name); -extern inline lump_t *WAD_CacheLumpByName(const char *name); - -extern lump_t *WAD_MoveLump(lump_t *lump, lump_t *destlump); -extern inline lump_t *WAD_MoveLumpInWADByNum(wad_t *wad, wad_uint32_t num, wad_t *destwad, wad_uint32_t destnum); -extern inline lump_t *WAD_MoveLumpInWADByName(wad_t *wad, const char *name, wad_t *destwad, const char *destname); -extern inline lump_t *WAD_MoveLumpByName(const char *name, const char *destname); - -extern void WAD_UncacheLump(lump_t *lump); -extern inline void WAD_UncacheLumpInWADByNum(wad_t *wad, wad_uint32_t num); -extern inline void WAD_UncacheLumpInWADByName(wad_t *wad, const char *name); -extern inline void WAD_UncacheLumpByName(const char *name); - -extern void WAD_RemoveLump(lump_t *lump); -extern inline void WAD_RemoveLumpInWADByNum(wad_t *wad, wad_uint32_t num); -extern inline void WAD_RemoveLumpInWADByName(wad_t *wad, const char *name); -extern inline void WAD_RemoveLumpByName(const char *name); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // __WAD_H__ diff --git a/tools/libwad/src/lump.c b/tools/libwad/src/lump.c deleted file mode 100644 index a1f4c97fc..000000000 --- a/tools/libwad/src/lump.c +++ /dev/null @@ -1,392 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// libwad: Doom WAD format interface library. -// Copyright (C) 2011 by Callum Dickinson. -// -// 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 2 -// 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. -//----------------------------------------------------------------------------- -/// \file lump.c -/// \brief Lump interface functionality. - -#include "wad_static.h" - -// -// Create a lump name from the file name -// of a lump. Used for when no name for -// a lump was given. -// -char *WAD_LumpNameFromFileName(char *path) -{ - wad_int32_t i; - char *name, *tempname, *file = WAD_BaseName(path); - - if (!file) - return NULL; - - // - // Process the filename for a suitable lump name. - // - // Get rid of any hidden file period. - if (file[0] == '.') - { - if (!(tempname = malloc(sizeof(*file) * strlen(&file[1])))) - { - free(file); - return NULL; - } - strcpy(tempname, &file[1]); - free(file); - } - else - tempname = file; - - // Get rid of any extensions. - for (i = 0; tempname[i] != '.' && tempname[i] != '\0'; i++); - - // Then, take the first eight characters of - // the resulting filename to get the lump name. - if (i > 8) - i = 8; - - if (!(name = malloc(sizeof(*name) * (i+1)))) - { - free(tempname); - return NULL; - } - - strncpy(name, tempname, i); - name[i+1] = '\0'; - - // - // Done processing lump name. - // - free(tempname); - return name; -} - -lump_t *WAD_LumpInWADByNum(wad_t *wad, wad_uint32_t num) -{ - lump_t *lump; - - if (!wad || !num) - return NULL; - - for (lump = wad->lumps; lump; lump = lump->next) - if (num == lump->num) - return lump; - - return NULL; -} - -lump_t *WAD_LumpInWADByName(wad_t *wad, const char *name) -{ - lump_t *lump; - - if (!wad || !name) - return NULL; - - for (lump = wad->lumps; lump; lump = lump->next) - if (!strcmp(name, lump->name)) - return lump; - - return NULL; -} - -lump_t *WAD_LumpByName(const char *name) -{ - wad_uint32_t i; - lump_t *lump; - - for (i = 0; i < wad_numwads; i = WAD_WADLoopAdvance(i)) - if ((lump = WAD_LumpInWADByName(WAD_WADByNum(i), name))) - return lump; - - return NULL; -} - -inline wad_uint32_t WAD_LumpNum(lump_t *lump) -{ - return lump->num; -} - -inline wad_uint32_t WAD_LumpNumInWADByName(wad_t *wad, const char *name) -{ - return WAD_LumpNum(WAD_LumpInWADByName(wad, name)); -} - -inline wad_uint32_t WAD_LumpNumByName(const char *name) -{ - return WAD_LumpNum(WAD_LumpByName(name)); -} - -inline size_t WAD_LumpSize(lump_t *lump) -{ - return lump->size; -} - -inline size_t WAD_LumpSizeInWADByName(wad_t *wad, const char *name) -{ - return WAD_LumpSize(WAD_LumpInWADByName(wad, name)); -} - -inline size_t WAD_LumpSizeByName(const char *name) -{ - return WAD_LumpSize(WAD_LumpByName(name)); -} - -static void WAD_AddLumpToTree(lump_t *lump, lump_t *destlump) -{ - lump_t *l; - - if (destlump) - { - lump->wad = destlump->wad; - lump->num = destlump->num; - for (l = destlump; l; l = l->next) - l->num++; - if (destlump->prev) - destlump->prev->next = lump; - lump->prev = destlump->prev; - destlump->prev = lump; - lump->next = destlump; - } - else - { - for (l = lump->wad->lumps; l; l = l->next) - if (!l->next) - break; - lump->num = lump->wad->header->numlumps; - l->next = lump; - lump->prev = l; - lump->next = NULL; - } - lump->wad->header->numlumps++; -} - -lump_t *WAD_AddLump(wad_t *wad, lump_t *destlump, const char *name, const char *filename) -{ - // The open lump file. - FILE *file = NULL; - // Pointer to the lump. - lump_t *lump; - // Lump structure. - wad_uint64_t disksize; // lump->disksize - size_t size; // lump->size - wad_boolean_t compressed;// lump->compressed - void *data; // lump->data - - if (!wad) - return NULL; - - if (!name && !filename) - return NULL; - - if (filename) - { - if (!(file = fopen(filename, "rb"))) - return NULL; - - fseek(file, 0, SEEK_END); - disksize = size = (unsigned)ftell(file); - compressed = false; - - - if (!(data = malloc(size))) - { - fclose(file); - return NULL; - } - - fseek(file, 0, SEEK_SET); - if (fread(data, disksize, 1, file) < 1) - return NULL; - fclose(file); - } - else - { - disksize = size = 0; - compressed = false; - data = NULL; - } - - - if (!(lump = malloc(sizeof(*lump)))) - { - WAD_FreeMemory(NULL, NULL, NULL, lump, NULL); - return NULL; - } - - lump->wad = wad; - if (!strcpy(lump->name, (name) ? name : WAD_LumpNameFromFileName((char *)filename))) - { - WAD_FreeMemory(NULL, NULL, NULL, lump, NULL); - return NULL; - } - lump->disksize = disksize; - lump->size = size; - lump->compressed = compressed; - - lump->data = data; - - WAD_AddLumpToTree(lump, destlump); - - return lump; -} - -inline lump_t *WAD_AddLumpInWADByNum(wad_t *wad, wad_uint32_t num, const char *name, const char *filename) -{ - return WAD_AddLump(wad, WAD_LumpInWADByNum(wad, num), name, filename); -} - -inline lump_t *WAD_AddLumpInWADByName(wad_t *wad, const char *destname, const char *name, const char *filename) -{ - return WAD_AddLump(wad, WAD_LumpInWADByName(wad, destname), name, filename); -} - -inline lump_t *WAD_AddLumpByName(const char *destname, const char *name, const char *filename) -{ - lump_t *l = WAD_LumpByName(destname); - return WAD_AddLump(l->wad, l, name, filename); -} - -lump_t *WAD_CacheLump(lump_t *lump) -{ - return lump; // TODO: WAD_CacheLump, dynamic lump loading. -} - -inline lump_t *WAD_CacheLumpInWADByNum(wad_t *wad, wad_uint32_t num) -{ - return WAD_CacheLump(WAD_LumpInWADByNum(wad, num)); -} - -inline lump_t *WAD_CacheLumpInWADByName(wad_t *wad, const char *name) -{ - return WAD_CacheLump(WAD_LumpInWADByName(wad, name)); -} - -inline lump_t *WAD_CacheLumpByName(const char *name) -{ - return WAD_CacheLump(WAD_LumpByName(name)); -} - -lump_t *WAD_MoveLump(lump_t *lump, lump_t *destlump) -{ - lump_t *l; - - if (!destlump) - return NULL; - - // - // Link the previous and next nodes in the WAD tree with each other. - // - if (lump->next) - { - lump->next->prev = lump->prev; - for (l = lump->next; l; l = l->next) - l->num--; - } - if (lump->prev) - lump->prev->next = lump->next; - lump->wad->header->numlumps--; - - // - WAD_AddLumpToTree(lump, destlump); - - return lump; -} - -inline lump_t *WAD_MoveLumpInWADByNum(wad_t *wad, wad_uint32_t num, wad_t *destwad, wad_uint32_t destnum) -{ - return WAD_MoveLump(WAD_LumpInWADByNum(wad, num), WAD_LumpInWADByNum(destwad, destnum)); -} - -inline lump_t *WAD_MoveLumpInWADByName(wad_t *wad, const char *name, wad_t *destwad, const char *destname) -{ - return WAD_MoveLump(WAD_LumpInWADByName(wad, name), WAD_LumpInWADByName(destwad, destname)); -} - -inline lump_t *WAD_MoveLumpByName(const char *name, const char *destname) -{ - return WAD_MoveLump(WAD_LumpByName(name), WAD_LumpByName(destname)); -} - -void WAD_UncacheLump(lump_t *lump) -{ - (void)lump; // TODO: WAD_UncacheLump, dynamic lump loading. -} - -inline void WAD_UncacheLumpInWADByNum(wad_t *wad, wad_uint32_t num) -{ - WAD_UncacheLump(WAD_LumpInWADByNum(wad, num)); -} - -inline void WAD_UncacheLumpInWADByName(wad_t *wad, const char *name) -{ - WAD_UncacheLump(WAD_LumpInWADByName(wad, name)); -} - -inline void WAD_UncacheLumpByName(const char *name) -{ - WAD_UncacheLump(WAD_LumpByName(name)); -} - -void WAD_RemoveLump(lump_t *lump) -{ - lump_t *l; - - if (!lump) - return; - - // - // Link the previous and next nodes in the WAD tree with each other. - // - lump->next->prev = lump->prev; - lump->prev->next = lump->next; - - // - // Modify the lump numbers for all the subsequent lumps, - // and the total lumps in the WAD. - // - lump->wad->header->numlumps--; - - if (lump->num == 0) - lump->wad->lumps = lump->next; - - for (l = lump->next; l; l = l->next) - l->num--; - - // - // While, at the same time, blanking the references - // to these nodes so they don't get removed. - // - lump->next = NULL; - - // - // Free this lump's memory. - // - WAD_FreeMemory(NULL, NULL, NULL, lump, NULL); -} - -inline void WAD_RemoveLumpInWADByNum(wad_t *wad, wad_uint32_t num) -{ - WAD_RemoveLump(WAD_LumpInWADByNum(wad, num)); -} - -inline void WAD_RemoveLumpInWADByName(wad_t *wad, const char *name) -{ - WAD_RemoveLump(WAD_LumpInWADByName(wad, name)); -} - -inline void WAD_RemoveLumpByName(const char *name) -{ - WAD_RemoveLump(WAD_LumpByName(name)); -} diff --git a/tools/libwad/src/wad.c b/tools/libwad/src/wad.c deleted file mode 100644 index ab8099b47..000000000 --- a/tools/libwad/src/wad.c +++ /dev/null @@ -1,412 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// libwad: Doom WAD format interface library. -// Copyright (C) 2011 by Callum Dickinson. -// -// 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 2 -// 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. -//----------------------------------------------------------------------------- -/// \file wad.c -/// \brief WAD interface functionality. - -#include "wad_static.h" - -// -// Offset for the first lump's data is always 12 bytes. -// -#define LUMPOFFSET 12 - -// -// Maximum of wad files used at the same time. -// (There is a max of simultaneous open files anyway, and this should be plenty.) -// -#define MAX_WADFILES 48 - -wad_t *wads[MAX_WADFILES]; -wad_uint32_t wad_numwads; - -wad_uint32_t wad_oldnumwads; -wad_uint32_t wad_removednum; - -static inline void WAD_ChangeWADNum(wad_int32_t i, wad_t *wad) -{ - wads[i] = wad; -} - -static inline void WAD_CacheWAD(wad_t *wad) -{ - WAD_ChangeWADNum(wad_numwads, wad); - wad_oldnumwads = wad_numwads; - wad_numwads++; -} - -static void WAD_UncacheWAD(wad_t *wad) -{ - wad_uint32_t i; - - for (i = 0; i < wad_numwads; i++) - if (WAD_WADByNum(i) == wad) - break; - - WAD_ChangeWADNum(i, NULL); - wad_removednum = i; - - for (; i < wad_numwads; i++) - { - if (WAD_WADByNum(i+1)) - { - WAD_ChangeWADNum(i, WAD_WADByNum(i+1)); - WAD_ChangeWADNum(i+1, NULL); - } - } - - wad_oldnumwads = wad_numwads; - wad_numwads--; -} - -wad_uint32_t WAD_WADLoopAdvance(wad_uint32_t i) -{ - wad_uint32_t o; - - o = wad_oldnumwads; - wad_oldnumwads = wad_numwads; - - return (o > wad_numwads && i <= wad_removednum) ? i : i + 1; -} - -wad_t *WAD_WADByNum(wad_uint16_t num) -{ - return (wads[num]) ? (wad_t *)wads[num] : NULL; -} - -wad_t *WAD_WADByFileName(const char *filename) -{ - wad_uint32_t i; - wad_t *w; - - for (i = 0; i < wad_numwads; i = WAD_WADLoopAdvance(i)) - { - w = WAD_WADByNum(i); - if (!strcmp(filename, w->filename)) - return w; - } - - return NULL; -} - -// -// Allocate a wadfile, setup the lumpinfo (directory) and -// lumpcache, add the wadfile to the current active wadfiles -// -// 1: Reached the maximum WAD number. -// 2: Cannot open the file. -// 3: Cannot read the WAD file's header. -// 4: Invalid WAD ID. -// 5: WAD's lump directory is corrupt. -// 6: Corrupt compressed WAD. -// -wad_t *WAD_OpenWAD(const char *filename) -{ - size_t i; - // Pointer to the WAD. - wad_t *wad = NULL; - // WAD file structure information. - // wad->filename is the function's argument. - FILE *file; // wad->file - wadheader_t *header; // wad->header - lump_t *l, *lumps = NULL; // wad->lumps - // Temporary lump information. - wad_uint64_t position; - lumpdir_t *lumpdir; - lump_t *ln = NULL; - - // - // Check if the limit of maximum WAD files has been - // reached or not. - // - if (wad_numwads >= MAX_WADFILES) - return NULL; - - // - // Open the WAD file. - // - if (!(file = fopen(filename, "rb"))) - return NULL; - - // - // Read the WAD file's header. - // - header = malloc(sizeof(*header)); - if (fread(header, 1, sizeof(*header), file) < sizeof(*header)) - return NULL; - - // Check if the ID is valid. - if (memcmp(header->id, "IWAD", 4) && memcmp(header->id, "PWAD", 4) && memcmp(header->id, "SDLL", 4)) - { - WAD_FreeMemory(file, header, NULL, NULL, NULL); - return NULL; - } - - // Check the rest of the header for type. - header->numlumps = WAD_INT32_Endianness(header->numlumps); - header->lumpdir = WAD_INT32_Endianness(header->lumpdir); - - // - // Read the WAD file's lump directory. - // - i = header->numlumps * sizeof(*lumpdir); - lumpdir = malloc(i); - - if (fseek(file, header->lumpdir, SEEK_SET) < 0 || fread(lumpdir, i, 1, file) < 1) - { - WAD_FreeMemory(file, header, lumpdir, NULL, NULL); - return NULL; - } - - // - // Fill lump information structure. - // - for (i = 0; i < header->numlumps; i++, lumpdir++) - { - if (!(l = malloc(sizeof(*l)))) - { - WAD_FreeMemory(file, header, lumpdir, lumps, NULL); - return NULL; - } - - position = WAD_INT32_Endianness(lumpdir->position); - - strncpy(l->name, lumpdir->name, 8); - l->size = l->disksize = WAD_INT32_Endianness(lumpdir->size); - l->compressed = false; // TODO: Compressed WAD support. - - if (l->disksize) - { - fseek(file, position, SEEK_SET); - if (!(l->data = malloc(l->disksize)) || fread(l->data, l->disksize, 1, file) < 1) - { - WAD_FreeMemory(file, header, lumpdir, lumps, NULL); - - if (!l->data) - return NULL; - else - return NULL; - } - } - - l->num = i; - l->next = NULL; - if (!lumps) - { - l->prev = NULL; - ln = lumps = l; - } - else - { - l->prev = ln; - ln = ln->next = l; - } - } - //free(lumpdir); - - // - // Allocate and fill WAD entry. - // - if (!(wad = malloc(sizeof(*wad)))) - { - WAD_FreeMemory(file, header, NULL, lumps, NULL); - return NULL; - } - wad->filename = (char *)filename; - - wad->header = header; - wad->compressed = false; - - wad->lumps = lumps; - - for (l = wad->lumps; l; l = l->next) - l->wad = wad; - - fclose(file); - - // - // Add the WAD to the wadfiles buffer and wad_numwads number. - // - WAD_CacheWAD(wad); - - // - // Done, loaded the WAD file. - // - return wad; -} - -// 1: Invalid wad number. -// 2: Unable to open file for writing. -// 3: Unable to write wad ID to the header. -// 4: Unable to write number of lumps to the header. -// 5: Unable to write temporary data to the header. -// 6: Unable to write lump data. -// 7: Unable to write position of lump data. -// 8: Unable to Write size of lump data. -// 9: Unable to write lump name. -// 9: Unable to write directory position. -wad_int32_t WAD_SaveWAD(wad_t *wad) -{ - lump_t *l; - FILE *file; - char *newfilename; - wad_int64_t diroffset, lumpoffset; - - if (!wad) - return 1; - - newfilename = WAD_VA("%s%s", wad->filename, ".bak"); - - remove(newfilename); - rename(wad->filename, newfilename); - - if (!(file = fopen(wad->filename, "wb"))) - return 2; - - // - // Write four-character WAD ID. - // - if(fwrite(wad->header->id, 4, 1, file) < 1) - return 3; - - // - // Write number of lumps. - // - if (fwrite(&wad->header->numlumps, 4, 1, file) < 1) - return 4; - - // - // Offset of directory is not known yet. For now, write number of lumps - // again, just to fill the space. - // - if (fwrite(&wad->header->numlumps, 4, 1, file) < 1) - return 5; - - // - // Loop through lump list, writing lump data. - // - for (l = wad->lumps; l; l = l->next) - { - // Don't write anything for the head of the lump list or for lumps of - // zero length. - if (!l->data) - continue; - - // Write the data. - if (fwrite(l->data, l->disksize, 1, file) < 1) - return 6; - } - - // - // Current position is where directory will start. - // - diroffset = ftell(file); - - // - // Pointer to the offset for the first lump's data. - // - lumpoffset = LUMPOFFSET; - - // - // Loop through lump list again, this time writing directory entries. - // - for (l = wad->lumps; l; l = l->next) - { - // Write position of lump data. - if (fwrite(&lumpoffset, 4, 1, file) < 1) - return 7; - - // Write size of lump data. - if (fwrite(&(l->disksize), 4, 1, file) < 1) - return 8; - - // Write lump name. - if (fwrite(&(l->name), 8, 1, file) < 1) - return 9; - - // Increment lumpoffset variable as appropriate. - lumpoffset += l->disksize; - } - - // - // Go back to header and write the proper directory position. - // - fseek(file, 8, SEEK_SET); - if (fwrite(&diroffset, 4, 1, file) < 1) - return 10; - - // - // Done, saved the WAD file. - // - return 0; -} - -inline wad_int32_t WAD_SaveWADByNum(wad_uint16_t num) -{ - return WAD_SaveWAD(WAD_WADByNum(num)); -} - -inline wad_int32_t WAD_SaveWADByFileName(const char *filename) -{ - return WAD_SaveWAD(WAD_WADByFileName(filename)); -} - -inline wad_int32_t WAD_SaveCloseWAD(wad_t *wad) -{ - wad_int32_t ret; - - if (!(ret = WAD_SaveWAD(wad))) - return ret; - - WAD_CloseWAD(wad); - return ret; -} - -inline wad_int32_t WAD_SaveCloseWADByNum(wad_uint16_t num) -{ - return WAD_SaveCloseWAD(WAD_WADByNum(num)); -} - -inline wad_int32_t WAD_SaveCloseWADByFileName(const char *filename) -{ - return WAD_SaveCloseWAD(WAD_WADByFileName(filename)); -} - -void WAD_CloseWAD(wad_t *wad) -{ - if (!wad) - return; - - // - // Free memory used by the WAD. - // - WAD_FreeMemory(NULL, wad->header, NULL, wad->lumps, wad); - - // - // Remove references to the WAD. - // - WAD_UncacheWAD(wad); -} - -inline void WAD_CloseWADByNum(wad_uint16_t num) -{ - WAD_CloseWAD(WAD_WADByNum(num)); -} - -inline void WAD_CloseWADByFileName(const char *name) -{ - WAD_CloseWAD(WAD_WADByFileName(name)); -} diff --git a/tools/libwad/src/wad_static.c b/tools/libwad/src/wad_static.c deleted file mode 100644 index dd631a5ba..000000000 --- a/tools/libwad/src/wad_static.c +++ /dev/null @@ -1,116 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// libwad: Doom WAD format interface library. -// Copyright (C) 2011 by Callum Dickinson. -// -// 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 2 -// 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. -//----------------------------------------------------------------------------- -/// \file wad_static.c -/// \brief Static functions for internal libwad operations. - -#include "wad_static.h" - -#define WAD_MAXERROR 1024 -static char wad_error[WAD_MAXERROR]; - -void WAD_ErrorSet(const char *text) -{ - strncpy(wad_error, text, WAD_MAXERROR); - wad_error[WAD_MAXERROR] = '\0'; -} - -inline void WAD_FreeMemory(FILE *file, wadheader_t *header, void *lumpdir, lump_t *lumps, wad_t *wad) -{ - lump_t *l, *ln = NULL; - - if (file) - fclose(file); - if (header) - free(header); - if (lumpdir) - free(lumpdir); - - if (lumps) - { - for (l = lumps; l; l = ln) - { - ln = l->next; - free(l->data); - free(l); - } - } - - if (wad) - { - if (wad->filename) - free(wad->filename); - - free(wad); - } -} - -char *WAD_Error(void) -{ - return wad_error; -} - -char *WAD_BaseName(char *path) -{ - wad_int32_t i; - - // - // Check if there is no text to check. - // - if (!path || path[0] == '\0') - return NULL; - - // - // Find the buffer entry where the actual filename begins. - // - for (i = strlen(path) - 1; i >= 0 && path[i] != '/'; i--); - - return (i >= 0) ? &path[i+1] : path; -} - -char *WAD_VA(const char *format, ...) -{ - va_list argptr; - static char string[1024]; - - va_start(argptr, format); - vsprintf(string, format, argptr); - va_end(argptr); - - return string; -} - -inline wad_int16_t WAD_INT16_Endianness(wad_int16_t x) -{ -#ifdef _BIG_ENDIAN - return ((wad_int16_t)((((wad_uint16_t)(x) & (wad_uint16_t)0x00ffU) << 8) | (((wad_uint16_t)(x) & (wad_uint16_t)0xff00U) >> 8))); -#else - return (wad_int16_t)x; -#endif -} - -inline wad_int32_t WAD_INT32_Endianness(wad_int32_t x) -{ -#ifdef _BIG_ENDIAN - return ((wad_int32_t)(\ - (((wad_uint32_t)(x) & (wad_uint32_t)0x000000ffUL) << 24) |\ - (((wad_uint32_t)(x) & (wad_uint32_t)0x0000ff00UL) << 8) |\ - (((wad_uint32_t)(x) & (wad_uint32_t)0x00ff0000UL) >> 8) |\ - (((wad_uint32_t)(x) & (wad_uint32_t)0xff000000UL) >> 24))); -#else - return (wad_int32_t)x; -#endif -} diff --git a/tools/libwad/src/wad_static.h b/tools/libwad/src/wad_static.h deleted file mode 100644 index 04d367bbd..000000000 --- a/tools/libwad/src/wad_static.h +++ /dev/null @@ -1,34 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// libwad: Doom WAD format interface library. -// Copyright (C) 2011 by Callum Dickinson. -// -// 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 2 -// 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. -//----------------------------------------------------------------------------- -/// \file wad_static.h -/// \brief Static header for internal libwad operations. - -#ifndef __WAD_STATIC_H__ -#define __WAD_STATIC_H__ - -#include -#include -#include -#include -#include -#include "../include/wad.h" - -void WAD_ErrorSet(const char *text); - -inline void WAD_FreeMemory(FILE *file, wadheader_t *header, void *lumpdir, lump_t *lumps, wad_t *wad); - -#endif // __WAD_STATIC_H__ diff --git a/tools/makefile b/tools/makefile deleted file mode 100644 index f4b377a26..000000000 --- a/tools/makefile +++ /dev/null @@ -1,24 +0,0 @@ - -default: dircomp2.c - gcc -O6 -mpentium -Wall -s dircomp2.c -o dircomp2.exe - -asm: - gcc -O6 -mpentium -Wall -g dircomp2.c -o tmp.exe - objdump -dS tmp.exe --debugging --no-show-raw-insn > dircomp2.s - del tmp.exe - -h2d: h2d.c - gcc -O6 -mpentium -Wall -s h2d.c -o h2d.exe - -dckconv: dckconv.c - gcc -O6 -mpentium -Wall -s dckconv.c -o dckconv.exe - -dckconv2: dckconv2.c - gcc -O6 -mpentium -Wall -s dckconv2.c -o dckconv2.exe - -dckcomp: dckcomp.c - gcc -O6 -mpentium -Wall -s dckcomp.c -o dckcomp.exe - -convert: convert.c - gcc -O6 -mpentium -Wall -s convert.c -o convert.exe - diff --git a/tools/masterserver/.gitignore b/tools/masterserver/.gitignore deleted file mode 100644 index 9f45745a3..000000000 --- a/tools/masterserver/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/client -/server -/server.log -/*.o diff --git a/tools/masterserver/Makefile b/tools/masterserver/Makefile deleted file mode 100644 index 7e66ab210..000000000 --- a/tools/masterserver/Makefile +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright (C) 2000 by DooM Legacy Team. -# -# 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 2 -# 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. -# -# DESCRIPTION: -# Makefile for DooM Legacy Master Server -# Created on 06/23/2000 by Thierry Van Elsuwe -# e-mail: hurdler@newdoom.com -# -#----------------------------------------------------------------------------- - -PORT=28900 -#PORT=7896 - -#*******************************************************************# - -CCFILES=common.cpp ipcs.cpp crypt.cpp md5.cpp -Main_CCFILES=server.cpp #client.cpp - -#******************************************************************# - -MYSQL_CONFIG?= mysql_config -MYSQL_CFLAGS?=$(shell $(MYSQL_CONFIG) --cflags) -MYSQL_LIBS?=$(shell $(MYSQL_CONFIG) --libs) - -CXXFLAGS+=-Wall -O3 -Wextra -ifdef MINGW -LIBS+=-lws2_32 -else -LIBS+=-lm -endif - -CXXFLAGS+=$(MYSQL_CFLAGS) -LIBS+=$(MYSQL_LIBS) - -ifdef DEBUG -CXXFLAGS+=-g -D__DEBUG__ -endif - -SRCS=$(CCFILES) $(Main_CCFILES) -OFILES=$(CCFILES:.cpp=.o) -Main_OFILES=$(Main_CCFILES:.cpp=.o) -EXEFILE=$(Main_CCFILES:.cpp=) - -##################################################################### - -.SUFFIXES: .cpp .h - -default: init $(EXEFILE) end - -init: - @echo - @echo "Compiling options:" - @echo " CXX : $(CXX)" - @echo " LDFLAGS : $(LDFLAGS)" - @echo " LIBS : $(LIBS)" - @echo " CXXFLAGS: $(CXXFLAGS)" - @echo - @echo "Files:" - @echo " SRCS : $(SRCS)" - @echo " OFILES : $(OFILES) $(Main_OFILES)" - @echo " EXEFILE : $(EXEFILE)" - @echo - -end: - @echo - @echo "*** Makefile ended successfully ***" - @echo - -##################################################################### - -$(EXEFILE): $(OFILES) $(Main_OFILES) - @echo Linking ... - @$(CXX) $(LDFLAGS) $(OFILES) $@.o -o $@ $(LIBS) -ifndef CYGWIN -ifndef MINGW - @chmod 755 $@ -endif -endif - @echo File $@ has been created - -##################################################################### - -.cpp.o: - @echo Compiling $< -\> $@ - @$(CXX) $(CXXFLAGS) $(INCS) -c $< -o $@ - -##################################################################### - -debug: debug_ -debug_: - @make "CXXFLAGS = $(CXXFLAGS) -D__DEBUG__" - @echo - -clean: clean_ -clean_: - @echo - @echo Removing obejcts files, executable files and eventually core file... - @rm -f $(OFILES) $(Main_OFILES) $(EXEFILE) core - @echo - -realclean: clean - @echo Removing backup files... - @rm -f *~ *.bak - @echo - -depend: dep -dep: - @echo - @echo Make dependencies... - @makedepend -- $(CXXFLAGS) -- $(Main_CCFILES) $(CCFILES) 2> /dev/null - @rm -f Makefile.bak - @echo - -BAKFILE = ../SRB2MasterServer -backup: bak -bak: clean - @echo Copy files to $(BAKFILE).tgz... - @tar cvf $(BAKFILE).tar * > /dev/null - @gzip $(BAKFILE).tar - @mv $(BAKFILE).tar.gz $(BAKFILE).tgz - @echo Removing backup files... - @rm -f *~ *.bak - @echo - -#mrproper: dep clean default -mrproper: clean default - -install: mrproper - @echo "Launching the server, port $(PORT)..." - @./server $(PORT) - @echo diff --git a/tools/masterserver/Master.dsp b/tools/masterserver/Master.dsp deleted file mode 100644 index 6bb0c13ed..000000000 --- a/tools/masterserver/Master.dsp +++ /dev/null @@ -1,230 +0,0 @@ -# Microsoft Developer Studio Project File - Name="MasterServer" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=MasterServer - Win32 Client Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "Master.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "Master.mak" CFG="MasterServer - Win32 Client Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "MasterServer - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "MasterServer - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE "MasterServer - Win32 Client Debug" (based on "Win32 (x86) Console Application") -!MESSAGE "MasterServer - Win32 Client Release" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "MasterServer - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "../../bin/VC/Release/MasterServer" -# PROP Intermediate_Dir "../../objs/VC/Release/MasterServer" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W4 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__STDC__" /D "_POSIX_" /FR /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 -# ADD LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /machine:I386 /out:"../../bin/VC/Release/MasterServer.exe" - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "../../bin/VC/Debug/MasterServer" -# PROP Intermediate_Dir "../../objs/VC/Debug/MasterServer" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /W4 /Gm /GX /ZI /Od /D "_DEBUG" /D "_WIN32" /D "__DEBUG__" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__STDC__" /D "_POSIX_" /FR /YX /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /debug /machine:I386 /out:"../../bin/VC/Debug/MasterServer.exe" /pdbtype:sept - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "MasterServer___Win32_Client_Debug" -# PROP BASE Intermediate_Dir "MasterServer___Win32_Client_Debug" -# PROP BASE Ignore_Export_Lib 0 -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "../../bin/VC/Debug/MasterClient" -# PROP Intermediate_Dir "../../objs/VC/Debug/MasterClient" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W4 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /D "__STDC__" /YX /FD /GZ /c -# ADD CPP /nologo /W4 /Gm /GX /ZI /Od /D "_DEBUG" /D "_WIN32" /D "__DEBUG__" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__STDC__" /D "_POSIX_" /FR /YX /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /debug /machine:I386 /out:"../../bin/VC/Debug/MasterServer.exe" /pdbtype:sept -# ADD LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /debug /machine:I386 /out:"../../bin/VC/Debug/MasterClient.exe" /pdbtype:sept - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "MasterServer___Win32_Client_Release" -# PROP BASE Intermediate_Dir "MasterServer___Win32_Client_Release" -# PROP BASE Ignore_Export_Lib 0 -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "../../bin/VC/Release/MasterClient" -# PROP Intermediate_Dir "../../objs/VC/Release/MasterClient" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W4 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W4 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__STDC__" /D "_POSIX_" /FR /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /machine:I386 /out:"../../bin/VC/Release/MasterServer.exe" -# ADD LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /machine:I386 /out:"../../bin/VC/Release/MasterClient.exe" - -!ENDIF - -# Begin Target - -# Name "MasterServer - Win32 Release" -# Name "MasterServer - Win32 Debug" -# Name "MasterServer - Win32 Client Debug" -# Name "MasterServer - Win32 Client Release" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\client.cpp - -!IF "$(CFG)" == "MasterServer - Win32 Release" - -# PROP Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Debug" - -# PROP Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Debug" - -# PROP BASE Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Release" - -# PROP BASE Exclude_From_Build 1 - -!ENDIF - -# End Source File -# Begin Source File - -SOURCE=.\common.cpp -# End Source File -# Begin Source File - -SOURCE=.\crypt.cpp -# End Source File -# Begin Source File - -SOURCE=.\ipcs.cpp -# End Source File -# Begin Source File - -SOURCE=.\server.cpp - -!IF "$(CFG)" == "MasterServer - Win32 Release" - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Debug" - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Debug" - -# PROP Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Release" - -# PROP Exclude_From_Build 1 - -!ENDIF - -# End Source File -# Begin Source File - -SOURCE=.\srvlist.cpp -# End Source File -# Begin Source File - -SOURCE=.\stats.cpp -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=.\common.h -# End Source File -# Begin Source File - -SOURCE=.\ipcs.h -# End Source File -# Begin Source File - -SOURCE=.\srvlist.h -# End Source File -# Begin Source File - -SOURCE=.\stats.h -# End Source File -# End Group -# Begin Group "Resource Files" - -# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" -# End Group -# End Target -# End Project diff --git a/tools/masterserver/Master.sln b/tools/masterserver/Master.sln deleted file mode 100644 index 129814c76..000000000 --- a/tools/masterserver/Master.sln +++ /dev/null @@ -1,38 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual C++ Express 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MasterServer", "Master.vcproj", "{6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Client Debug|Win32 = Client Debug|Win32 - Client Debug|x64 = Client Debug|x64 - Client Release|Win32 = Client Release|Win32 - Client Release|x64 = Client Release|x64 - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Debug|Win32.ActiveCfg = Client Debug|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Debug|Win32.Build.0 = Client Debug|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Debug|x64.ActiveCfg = Client Debug|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Debug|x64.Build.0 = Client Debug|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Release|Win32.ActiveCfg = Client Release|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Release|Win32.Build.0 = Client Release|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Release|x64.ActiveCfg = Client Release|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Release|x64.Build.0 = Client Release|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Debug|Win32.ActiveCfg = Debug|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Debug|Win32.Build.0 = Debug|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Debug|x64.ActiveCfg = Debug|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Debug|x64.Build.0 = Debug|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Release|Win32.ActiveCfg = Release|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Release|Win32.Build.0 = Release|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Release|x64.ActiveCfg = Release|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/tools/masterserver/Master.vcproj b/tools/masterserver/Master.vcproj deleted file mode 100644 index 364094dd4..000000000 --- a/tools/masterserver/Master.vcproj +++ /dev/null @@ -1,1063 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/masterserver/MasterClient.dev b/tools/masterserver/MasterClient.dev deleted file mode 100644 index 035bb0bff..000000000 --- a/tools/masterserver/MasterClient.dev +++ /dev/null @@ -1,159 +0,0 @@ -[Project] -FileName=MasterClient.dev -Name=MasterClient -UnitCount=7 -Type=1 -Ver=1 -ObjFiles= -Includes= -Libs= -PrivateResource= -ResourceIncludes= -MakeIncludes= -Compiler=-Wall_@@_ -CppCompiler=-Wall_@@_ -Linker=-lwsock32_@@_ -IsCpp=1 -Icon= -ExeOutput=..\..\bin -ObjectOutput=..\..\objs\MasterClient -OverrideOutput=0 -OverrideOutputName=MasterServer.exe -HostApplication= -Folders=Client,Common -CommandLine= -UseCustomMakefile=0 -CustomMakefile= -IncludeVersionInfo=0 -SupportXPThemes=0 -CompilerSet=0 -CompilerSettings=0000000010001001001010 - -[Unit1] -FileName=common.cpp -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=1 -OverrideBuildCmd=0 -BuildCmd= - -[Unit2] -FileName=ipcs.cpp -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=2 -OverrideBuildCmd=0 -BuildCmd= - -[Unit7] -FileName=Makefile -CompileCpp=1 -Folder= -Compile=0 -Link=0 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit8] -FileName=stats.h -Folder=Server -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= -CompileCpp=1 - -[Unit9] -FileName=common.h -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit11] -FileName=Makefile -CompileCpp=1 -Folder= -Compile=0 -Link=0 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit12] -FileName=srvlist.h -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[VersionInfo] -Major=0 -Minor=1 -Release=1 -Build=1 -LanguageID=1033 -CharsetID=1252 -CompanyName= -FileVersion= -FileDescription=Developed using the Dev-C++ IDE -InternalName= -LegalCopyright= -LegalTrademarks= -OriginalFilename= -ProductName= -ProductVersion= -AutoIncBuildNr=0 - -[Unit3] -FileName=crypt.cpp -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=4 -OverrideBuildCmd=0 -BuildCmd= - -[Unit4] -FileName=client.cpp -CompileCpp=1 -Folder=Client -Compile=1 -Link=1 -Priority=7 -OverrideBuildCmd=0 -BuildCmd=$(CPP) -c client.cpp -o ../../../objs/MasterServer/client.o $(CXXFLAGS) - -[Unit5] -FileName=common.h -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit6] -FileName=ipcs.h -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - diff --git a/tools/masterserver/MasterServer.dev b/tools/masterserver/MasterServer.dev deleted file mode 100644 index bc089ccd5..000000000 --- a/tools/masterserver/MasterServer.dev +++ /dev/null @@ -1,169 +0,0 @@ -[Project] -FileName=MasterServer.dev -Name=MasterServer -UnitCount=11 -Type=1 -Ver=1 -ObjFiles= -Includes= -Libs= -PrivateResource= -ResourceIncludes= -MakeIncludes= -Compiler=-Wall_@@_-DDEBUG_@@_ -CppCompiler=-Wall_@@_-DDEBUG_@@_ -Linker=-lwsock32_@@_-lmysql_@@_ -IsCpp=1 -Icon= -ExeOutput=..\..\bin -ObjectOutput=..\..\objs\MasterServer -OverrideOutput=0 -OverrideOutputName=MasterServer.exe -HostApplication= -Folders=Common,Server -CommandLine=28900 -UseCustomMakefile=0 -CustomMakefile= -IncludeVersionInfo=0 -SupportXPThemes=0 -CompilerSet=0 -CompilerSettings=0000000011001001001010 - -[Unit1] -FileName=common.cpp -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=1 -OverrideBuildCmd=0 -BuildCmd= - -[Unit2] -FileName=ipcs.cpp -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=2 -OverrideBuildCmd=0 -BuildCmd= - -[Unit3] -FileName=srvlist.cpp -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=3 -OverrideBuildCmd=0 -BuildCmd= - -[Unit4] -FileName=crypt.cpp -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=4 -OverrideBuildCmd=0 -BuildCmd= - -[Unit5] -FileName=stats.cpp -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=5 -OverrideBuildCmd=0 -BuildCmd= - -[Unit6] -FileName=server.cpp -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=6 -OverrideBuildCmd=0 -BuildCmd= - -[Unit8] -FileName=common.h -Folder=Common -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= -CompileCpp=1 - -[Unit9] -FileName=ipcs.h -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit10] -FileName=Makefile -CompileCpp=1 -Folder= -Compile=0 -Link=0 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit11] -FileName=srvlist.h -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[VersionInfo] -Major=0 -Minor=1 -Release=1 -Build=1 -LanguageID=1033 -CharsetID=1252 -CompanyName= -FileVersion= -FileDescription=Developed using the Dev-C++ IDE -InternalName= -LegalCopyright= -LegalTrademarks= -OriginalFilename= -ProductName= -ProductVersion= -AutoIncBuildNr=0 - -[Unit7] -FileName=stats.h -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit13] -FileName=LIVE_MySQL.h -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - diff --git a/tools/masterserver/client.cpp b/tools/masterserver/client.cpp deleted file mode 100644 index 8eba3f1a2..000000000 --- a/tools/masterserver/client.cpp +++ /dev/null @@ -1,133 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// 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 2 -// 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. -// -//----------------------------------------------------------------------------- - -#include -#include -#include "ipcs.h" -#include "common.h" - -//============================================================================= - -static CClientSocket client_socket; -//static msg_t msg; -FILE *logfile; - -//============================================================================= - -static msg_t *getData(int argc, char *argv[]) -{ - static msg_t msg; - msg_server_t *info = (msg_server_t *)msg.buffer; - -#if defined (_WIN32) - strcpy(info->header.buffer, ""); -#else - strcpy(info->header.buffer, getpass("Enter password: ")); -#endif - - // default values if one of the param is not entered - strcpy(info->ip, "88.86.106.169"); - strcpy(info->port, "5029"); - strcpy(info->name, "Cueball's Dedicated Server"); - strcpy(info->version, "1.09.4"); - msg.type = ADD_PSERVER_MSG; - msg.length = sizeof (msg_server_t); - - for (int i = 0; i < argc; i++) - { - // first: extra parameters (must be after all -param) - if (!strcasecmp(argv[i], "get")) - { - msg.type = GET_SERVER_MSG; - msg.length = 0; - } - else if (!strcasecmp(argv[i], "log")) - { - msg.type = GET_LOGFILE_MSG; - msg.length = sizeof (msg_server_t); - } - else if (!strcasecmp(argv[i], "erase")) - { - msg.type = ERASE_LOGFILE_MSG; - msg.length = sizeof (msg_server_t); - } - else if (!strcasecmp(argv[i], "remove")) - { - msg.type = REMOVE_PSERVER_MSG; - msg.length = sizeof (msg_server_t); - } - - if (i >= argc-1) - continue; - - // second: parameter requiring extra parameters - if (strcasecmp(argv[i], "-ip") == 0) - strcpy(info->ip, argv[i+1]); - else if (strcasecmp(argv[i], "-port") == 0) - strcpy(info->port, argv[i+1]); - else if (strcasecmp(argv[i], "-hostname") == 0) - strcpy(info->name, argv[i+1]); - else if (strcasecmp(argv[i], "-version") == 0) - strcpy(info->version, argv[i+1]); - else if (strcasecmp(argv[i], "-pass") == 0) - strcpy(info->header.buffer, argv[i+1]); - } - return &msg; -} - -int main(int argc, char *argv[]) -{ - if (argc == 2) - { - printf("encrypt: %s\n", pCrypt(argv[1], "04")); - return 0; - } - else if (argc > 2) - { - if (client_socket.connect(argv[1], argv[2]) < 0) - { - conPrintf(RED, "Connect failed.\n"); - return -1; - } - - msg_t *msg = getData(argc, argv); - - if (client_socket.write(msg) < 0) - { - dbgPrintf(RED, "Write failed.\n"); - return -1; - } - - switch (ntohl(msg->type)) - { - case GET_SERVER_MSG: - case GET_LOGFILE_MSG: - while (client_socket.read(msg) >= 0) - { - if (ntohl(msg->length) == 0) - break; - printf("%s", msg->buffer); - } - break; - - case REMOVE_PSERVER_MSG: - default: - break; - } - } - return 0; -} diff --git a/tools/masterserver/common.cpp b/tools/masterserver/common.cpp deleted file mode 100644 index b9795bd0f..000000000 --- a/tools/masterserver/common.cpp +++ /dev/null @@ -1,207 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// 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 2 -// 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. -// -//----------------------------------------------------------------------------- - -#include -#include -#include -#include "common.h" - -// ================================== GLOBALS ================================= - -static const char *fatal_error_msg[NUM_FATAL_ERROR] = -{ - "Error: signal()", - "Error: select()", - "Error: read()", - "Error: write()", -}; - -// used by xxxPrintf() functions as temporary variable -static char str[1024] =""; -static va_list arglist; -#ifdef _WIN32 -static size_t len = 0; -static HANDLE co = INVALID_HANDLE_VALUE; -static DWORD bytesWritten = 0; -static CONSOLE_SCREEN_BUFFER_INFO ConsoleScreenBufferInfo; -#endif - -// ================================= FUNCTIONS ================================ - -/* - * clearScreen(): - */ -void clearScreen() -{ -#ifdef _WIN32 -#else - printf("\033[0m \033[2J \033[0;0H"); -#endif -} - -/* - * fatalError(): - */ -void fatalError(fatal_error_t num) -{ - clearScreen(); - printf("\n"); - perror(fatal_error_msg[num]); - printf("\n"); - exit(-1); -} - - -/* - * dbgPrintf(): - */ -#ifdef _WIN32 -void dbgPrintf(DWORDLONG col, const char *lpFmt, ...) -#else -void dbgPrintf(const char *col, const char *lpFmt, ...) -#endif -{ -#if defined (__DEBUG__) - va_start(arglist, lpFmt); - vsnprintf(str, sizeof str, lpFmt, arglist); - va_end(arglist); - -#ifdef _WIN32 - len = strlen(str); - co = GetStdHandle(STD_OUTPUT_HANDLE); - - if (co == INVALID_HANDLE_VALUE) - return; - - if (col == DEFCOL) - { - if (!GetConsoleScreenBufferInfo(co, &ConsoleScreenBufferInfo)) - ConsoleScreenBufferInfo.wAttributes = - FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE; - - SetConsoleTextAttribute(co, (WORD)col); - } - - if (GetFileType(co) == FILE_TYPE_CHAR) - WriteConsoleA(co, str, (DWORD)len, &bytesWritten, NULL); - else - WriteFile(co, str, (DWORD)len, &bytesWritten, NULL); - - if (col != DEFCOL) - SetConsoleTextAttribute(co, - ConsoleScreenBufferInfo.wAttributes); -#else - printf("%s%s", col, str); - fflush(stdout); -#endif -#else - (void)col; - (void)lpFmt; -#endif -} - -/* - * conPrintf() - */ -#ifdef _WIN32 -void conPrintf(DWORDLONG col, const char *lpFmt, ...) -#else -void conPrintf(const char *col, const char *lpFmt, ...) -#endif -{ - va_start(arglist, lpFmt); - vsnprintf(str, sizeof str, lpFmt, arglist); - va_end(arglist); - -#ifdef _WIN32 - len = strlen(str); - co = GetStdHandle(STD_OUTPUT_HANDLE); - - if (col == DEFCOL) - { - if (!GetConsoleScreenBufferInfo(co, &ConsoleScreenBufferInfo)) - ConsoleScreenBufferInfo.wAttributes = - FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE; - - SetConsoleTextAttribute(co, (WORD)col); - } - - if (co == INVALID_HANDLE_VALUE) - return; - - if (GetFileType(co) == FILE_TYPE_CHAR) - WriteConsoleA(co, str, (DWORD)len, &bytesWritten, NULL); - else - WriteFile(co, str, (DWORD)len, &bytesWritten, NULL); - - if (col != DEFCOL) - SetConsoleTextAttribute(co, - ConsoleScreenBufferInfo.wAttributes); -#else - printf("%s%s", col, str); - fflush(stdout); -#endif -} - -/* - * logPrintf(): - */ -void logPrintf(FILE *f, const char *lpFmt, ...) -{ - char *ct; - time_t t; - - va_start(arglist, lpFmt); - vsnprintf(str, sizeof str, lpFmt, arglist); - va_end(arglist); - - t = time(NULL); - ct = ctime(&t); - ct[strlen(ct)-1] = '\0'; - fprintf(f, "%s: %s", ct, str); - fflush(f); -#if defined (__DEBUG__) -#ifdef _WIN32 - len = strlen(str); - printf("%s", str); -#else - printf("%s%s", DEFCOL, str); -#endif - fflush(stdout); -#endif -} - -/* - * openFile(): - */ -FILE *openFile(const char *filename) -{ - return fopen(filename, "a+t"); -} - -void strrand(char *s, const int len) { - static const char alphanum[] = - "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; - - for (int i = 0; i < len; ++i) { - s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; - } - - s[len] = 0; -} diff --git a/tools/masterserver/common.h b/tools/masterserver/common.h deleted file mode 100644 index cb935572d..000000000 --- a/tools/masterserver/common.h +++ /dev/null @@ -1,151 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// 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 2 -// 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. -// -//----------------------------------------------------------------------------- - -#ifndef _COMMON_H_ -#define _COMMON_H_ - -#ifdef __GNUC__ -#include -#include - -#define UINT8 uint8_t -#define SINT8 int8_t - -#define UINT16 uint16_t -#define INT16 int16_t - -#define INT32 int32_t -#define UINT32 uint32_t -#define INT64 int64_t -#define UINT64 uint64_t -#define ATTRPACK __attribute__ ((packed)) -#elif defined ( _MSC_VER) -#include -#define UINT8 unsigned __int8 -#define SINT8 signed __int8 - -#define UINT16 unsigned __int16 -#define INT16 __int16 - -#define INT32 __int32 -#define UINT32 unsigned __int32 - -#define INT64 __int64 -#define UINT64 unsigned __int64 - -typedef long ssize_t; -#endif - -#ifndef ATTRPACK -#define ATTRPACK -#endif - -#include -#include -#include -#include - -#if defined (_WIN32) || defined (__OS2__) -#ifdef __GNUC__ -#define strcasecmp stricmp -#elif defined (_MSC_VER) -#define snprintf _snprintf -#define vsnprintf _vsnprintf -#define strcasecmp _stricmp -#pragma warning(disable : 4244) -#endif -#endif - -// ================================ DEFINITIONS =============================== - - -#ifdef _WIN32 -#ifdef __GNUC__ -#include -#include -#include -#include -#endif -#define DEFCOL 0xD0E0F0C0 // codes couleurs ANSI -#define BLACK 0 -#define RED FOREGROUND_RED -#define GREEN FOREGROUND_GREEN -#define BROWN FOREGROUND_GREEN|FOREGROUND_RED -#define BLUE FOREGROUND_BLUE -#define PURPLE FOREGROUND_RED|FOREGROUND_BLUE -#define CYAN FOREGROUND_BLUE|FOREGROUND_GREEN -#define LIGHTGRAY FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_RED -#define DARKGRAY FOREGROUND_INTENSITY -#define LIGHTRED FOREGROUND_RED|FOREGROUND_INTENSITY -#define LIGHTGREEN FOREGROUND_GREEN|FOREGROUND_INTENSITY -#define YELLOW FOREGROUND_GREEN|FOREGROUND_RED|FOREGROUND_INTENSITY -#define LIGHTBLUE FOREGROUND_BLUE|FOREGROUND_INTENSITY -#define MAGENTA FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_INTENSITY -#define LIGHTCYAN FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_INTENSITY -#define WHITE FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_RED|FOREGROUND_INTENSITY - -#else - -#define DEFCOL "\033[0m" // codes couleurs ANSI -#define BLACK "\033[0;30m" -#define RED "\033[0;31m" -#define GREEN "\033[0;32m" -#define BROWN "\033[0;33m" -#define BLUE "\033[0;34m" -#define PURPLE "\033[0;35m" -#define CYAN "\033[0;36m" -#define LIGHTGRAY "\033[0;37m" -#define DARKGRAY "\033[1;30m" -#define LIGHTRED "\033[1;31m" -#define LIGHTGREEN "\033[1;32m" -#define YELLOW "\033[1;33m" -#define LIGHTBLUE "\033[1;34m" -#define MAGENTA "\033[1;35m" -#define LIGHTCYAN "\033[1;36m" -#define WHITE "\033[1;37m" - -#endif - -typedef enum -{ - FE_SIGNAL_ERR, - FE_SELECT_ERR, - FE_READ_ERR, - FE_WRITE_ERR, - NUM_FATAL_ERROR -} fatal_error_t; - -// ================================== PROTOS ================================== - -void clearScreen(); -void fatalError(fatal_error_t); -void logPrintf(FILE *, const char *, ...); -#ifdef _WIN32 -void dbgPrintf(DWORDLONG col, const char *lpFmt, ...); -void conPrintf(DWORDLONG col, const char *lpFmt, ...); -#else -void dbgPrintf(const char *col, const char *lpFmt, ...); -void conPrintf(const char *col, const char *lpFmt, ...); -#endif -FILE *openFile(const char *filename); -const char *pCrypt(const char *pw, const char *salt); - -// ================================== STRINGS ================================= -void strrand(char *s, const int len); - -// ================================== EXTERNS ================================= -#endif diff --git a/tools/masterserver/crypt.cpp b/tools/masterserver/crypt.cpp deleted file mode 100644 index 4f15d3c89..000000000 --- a/tools/masterserver/crypt.cpp +++ /dev/null @@ -1,278 +0,0 @@ -#include "common.h" - -static SINT8 IP[] = -{ - 58,50,42,34,26,18,10, 2, - 60,52,44,36,28,20,12, 4, - 62,54,46,38,30,22,14, 6, - 64,56,48,40,32,24,16, 8, - 57,49,41,33,25,17, 9, 1, - 59,51,43,35,27,19,11, 3, - 61,53,45,37,29,21,13, 5, - 63,55,47,39,31,23,15, 7, -}; -static SINT8 FP[] = -{ - 40, 8,48,16,56,24,64,32, - 39, 7,47,15,55,23,63,31, - 38, 6,46,14,54,22,62,30, - 37, 5,45,13,53,21,61,29, - 36, 4,44,12,52,20,60,28, - 35, 3,43,11,51,19,59,27, - 34, 2,42,10,50,18,58,26, - 33, 1,41, 9,49,17,57,25, -}; -static SINT8 PC1_C[] = -{ - 57,49,41,33,25,17, 9, - 1,58,50,42,34,26,18, - 10, 2,59,51,43,35,27, - 19,11, 3,60,52,44,36, -}; -static SINT8 PC1_D[] = -{ - 63,55,47,39,31,23,15, - 7,62,54,46,38,30,22, - 14, 6,61,53,45,37,29, - 21,13, 5,28,20,12, 4, -}; -static SINT8 shifts[] = {1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1}; -static SINT8 PC2_C[] = -{ - 14,17,11,24, 1, 5, - 3,28,15, 6,21,10, - 23,19,12, 4,26, 8, - 16, 7,27,20,13, 2, -}; -static SINT8 PC2_D[] = -{ - 41,52,31,37,47,55, - 30,40,51,45,33,48, - 44,49,39,56,34,53, - 46,42,50,36,29,32, -}; -static SINT8 C[28]; -static SINT8 D[28]; -static SINT8 KS[16][48]; -static SINT8 E[48]; -static SINT8 e2[] = -{ - 32, 1, 2, 3, 4, 5, - 4, 5, 6, 7, 8, 9, - 8, 9,10,11,12,13, - 12,13,14,15,16,17, - 16,17,18,19,20,21, - 20,21,22,23,24,25, - 24,25,26,27,28,29, - 28,29,30,31,32, 1, -}; -static SINT8 S[8][64] = -{ - { - 14, 4,13, 1, 2,15,11, 8, 3,10, 6,12, 5, 9, 0, 7, - 0,15, 7, 4,14, 2,13, 1,10, 6,12,11, 9, 5, 3, 8, - 4, 1,14, 8,13, 6, 2,11,15,12, 9, 7, 3,10, 5, 0, - 15,12, 8, 2, 4, 9, 1, 7, 5,11, 3,14,10, 0, 6,13, - }, - { - 15, 1, 8,14, 6,11, 3, 4, 9, 7, 2,13,12, 0, 5,10, - 3,13, 4, 7,15, 2, 8,14,12, 0, 1,10, 6, 9,11, 5, - 0,14, 7,11,10, 4,13, 1, 5, 8,12, 6, 9, 3, 2,15, - 13, 8,10, 1, 3,15, 4, 2,11, 6, 7,12, 0, 5,14, 9, - }, - { - 10, 0, 9,14, 6, 3,15, 5, 1,13,12, 7,11, 4, 2, 8, - 13, 7, 0, 9, 3, 4, 6,10, 2, 8, 5,14,12,11,15, 1, - 13, 6, 4, 9, 8,15, 3, 0,11, 1, 2,12, 5,10,14, 7, - 1,10,13, 0, 6, 9, 8, 7, 4,15,14, 3,11, 5, 2,12, - }, - { - 7,13,14, 3, 0, 6, 9,10, 1, 2, 8, 5,11,12, 4,15, - 13, 8,11, 5, 6,15, 0, 3, 4, 7, 2,12, 1,10,14, 9, - 10, 6, 9, 0,12,11, 7,13,15, 1, 3,14, 5, 2, 8, 4, - 3,15, 0, 6,10, 1,13, 8, 9, 4, 5,11,12, 7, 2,14, - }, - { - 2,12, 4, 1, 7,10,11, 6, 8, 5, 3,15,13, 0,14, 9, - 14,11, 2,12, 4, 7,13, 1, 5, 0,15,10, 3, 9, 8, 6, - 4, 2, 1,11,10,13, 7, 8,15, 9,12, 5, 6, 3, 0,14, - 11, 8,12, 7, 1,14, 2,13, 6,15, 0, 9,10, 4, 5, 3, - }, - { - 12, 1,10,15, 9, 2, 6, 8, 0,13, 3, 4,14, 7, 5,11, - 10,15, 4, 2, 7,12, 9, 5, 6, 1,13,14, 0,11, 3, 8, - 9,14,15, 5, 2, 8,12, 3, 7, 0, 4,10, 1,13,11, 6, - 4, 3, 2,12, 9, 5,15,10,11,14, 1, 7, 6, 0, 8,13, - }, - { - 4,11, 2,14,15, 0, 8,13, 3,12, 9, 7, 5,10, 6, 1, - 13, 0,11, 7, 4, 9, 1,10,14, 3, 5,12, 2,15, 8, 6, - 1, 4,11,13,12, 3, 7,14,10,15, 6, 8, 0, 5, 9, 2, - 6,11,13, 8, 1, 4,10, 7, 9, 5, 0,15,14, 2, 3,12, - }, - { - 13, 2, 8, 4, 6,15,11, 1,10, 9, 3,14, 5, 0,12, 7, - 1,15,13, 8,10, 3, 7, 4,12, 5, 6,11, 0,14, 9, 2, - 7,11, 4, 1, 9,12,14, 2, 0, 6,10,13,15, 3, 5, 8, - 2, 1,14, 7, 4,10, 8,13,15,12, 9, 0, 3, 5, 6,11, - } -}; -static SINT8 P[] = -{ - 16, 7,20,21, - 29,12,28,17, - 1,15,23,26, - 5,18,31,10, - 2, 8,24,14, - 32,27, 3, 9, - 19,13,30, 6, - 22,11, 4,25, -}; -static SINT8 L[64], *R = L + 32; -static SINT8 tempL[32]; -static SINT8 f[32]; -static SINT8 preS[48]; - -//======================================================================= - -static void setKey(const SINT8 *key) -{ - register INT32 i, j, k; - INT32 t; - - for (i = 0; i < 28; i++) - { - C[i] = key[PC1_C[i]-1]; - D[i] = key[PC1_D[i]-1]; - } - for (i = 0; i < 16; i++) - { - for (k = 0; k < shifts[i]; k++) - { - t = C[0]; - for (j = 0; j < 28-1; j++) - C[j] = C[j+1]; - C[27] = t; - t = D[0]; - for (j = 0; j < 28-1; j++) - D[j] = D[j+1]; - D[27] = t; - } - for (j = 0; j < 24; j++) - { - KS[i][j] = C[PC2_C[j]-1]; - KS[i][j+24] = D[PC2_D[j]-28-1]; - } - } - for (i = 0; i < 48; i++) - E[i] = e2[i]; -} - -void enCrypt(SINT8 *block) -{ - INT32 i, ii; - register INT32 t, j, k; - - for (j = 0; j < 64; j++) - L[j] = block[IP[j]-1]; - for (ii = 0; ii < 16; ii++) - { - i = ii; - for (j = 0; j < 32; j++) - tempL[j] = R[j]; - for (j = 0; j < 48; j++) - preS[j] = R[E[j]-1] ^ KS[i][j]; - for (j = 0; j < 8; j++) - { - t = 6*j; - k = S[j][(preS[t+0]<<5)+ - (preS[t+1]<<3)+ - (preS[t+2]<<2)+ - (preS[t+3]<<1)+ - (preS[t+4]<<0)+ - (preS[t+5]<<4)]; - t = 4*j; - f[t+0] = (k>>3)&01; - f[t+1] = (k>>2)&01; - f[t+2] = (k>>1)&01; - f[t+3] = (k>>0)&01; - } - for (j = 0; j < 32; j++) - R[j] = L[j] ^ f[P[j]-1]; - for (j = 0; j < 32; j++) - L[j] = tempL[j]; - } - for (j = 0; j < 32; j++) - { - t = L[j]; - L[j] = R[j]; - R[j] = t; - } - for (j = 0; j < 64; j++) - block[j] = L[FP[j]-1]; -} - -const char *pCrypt(const char *pw, const char *salt) -{ - register INT32 i, j, c; - INT32 temp; - static SINT8 block[66]; - static char iobuf[16]; - - for (i = 0; i < 66; i++) - block[i] = 0; - for (i = 0; (c = *pw) != '\0' && i < 64; pw++) - { - for (j = 0; j < 7; j++, i++) - block[i] = (c>>(6-j)) & 01; - i++; - } - - setKey(block); - - for (i = 0; i < 66; i++) - block[i] = 0; - - for (i = 0; i < 2; i++) - { - c = *salt++; - iobuf[i] = c; - if (c > 'Z') - c -= 6; - if (c > '9') - c -= 7; - c -= '.'; - for (j = 0; j < 6; j++) - { - if ((c>>j) & 01) - { - temp = E[6*i+j]; - E[6*i+j] = E[6*i+j+24]; - E[6*i+j+24] = temp; - } - } - } - - for (i = 0; i < 25; i++) - enCrypt(block); - - for (i = 0; i < 11; i++) - { - c = 0; - for (j = 0; j < 6; j++) - { - c <<= 1; - c |= block[6*i+j]; - } - c += '.'; - if (c > '9') - c += 7; - if (c > 'Z') - c += 6; - iobuf[i+2] = c; - } - iobuf[i+2] = 0; - if (iobuf[1] == 0) - iobuf[1] = iobuf[0]; - return(iobuf); -} diff --git a/tools/masterserver/ipcs.cpp b/tools/masterserver/ipcs.cpp deleted file mode 100644 index 4c3c6de74..000000000 --- a/tools/masterserver/ipcs.cpp +++ /dev/null @@ -1,595 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// 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 2 -// 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. -// -//----------------------------------------------------------------------------- - -#ifdef __GNUC__ -#include -#endif - -#ifdef _WIN32 -//#include -#else -#include // socket(),... -#include // socket(),... -#endif -#include // atoi(),... -#include // signal(),... -#ifndef _WIN32 -#include // gethostbyname(),... -#endif -#ifdef _WIN32 -#include -#else -#include // timeval,... (TIMEOUT) -#endif -#include // memset(),... -#include "ipcs.h" -#include "common.h" - -typedef void Sigfunc(int); - -#ifndef _WIN32 -static void sigHandler(int signr); -static Sigfunc *mySignal(int signo, Sigfunc *func); -#endif - -#ifdef _MSC_VER -#pragma warning(disable : 4127) -#endif -//============================================================================= - -#if defined (_WIN32) || defined (__OS2__) -// it seems windows doesn't define that... maybe some other OS? OS/2 -static int inet_aton(const char *hostname, struct in_addr *addr) -{ - return ((addr->s_addr=inet_addr(hostname)) != INADDR_NONE); -} -#endif - -/* -** CSocket() -*/ -CSocket::CSocket() -{ - dbgPrintf(DEFCOL, "Initializing socket... "); -#ifdef _WIN32 -//#warning SIGPIPE needed - WSADATA winsockdata; - if (WSAStartup(MAKEWORD(1, 1), &winsockdata)) - conPrintf(RED,"No TCP/IP driver detected"); -#else - signal(SIGPIPE, sigHandler); -#endif - FD_ZERO(&rset); - memset(&addr, 0, sizeof (addr)); - addr.sin_family = AF_INET; - dbgPrintf(DEFCOL, "DONE1.\n"); -} - -/* -** ~CSocket() -*/ -CSocket::~CSocket() -{ - dbgPrintf(DEFCOL, "Freeing socket... "); -#ifdef _WIN32 - WSACleanup(); -#endif - dbgPrintf(DEFCOL, "DONE2.\n"); -} - -/* -** getIP() -*/ -int CSocket::getIP(const char *ip_addr) -{ - struct hostent *host_ent; - - dbgPrintf(DEFCOL, "get IP for %s... ", ip_addr); - if (!inet_aton(ip_addr, &addr.sin_addr)) - { - host_ent = gethostbyname(ip_addr); - if (host_ent == NULL) - return GETHOSTBYNAME_ERROR; - memcpy(&addr.sin_addr, host_ent->h_addr_list[0], - sizeof (struct in_addr)); - } - dbgPrintf(DEFCOL, "got %s. ", inet_ntoa(addr.sin_addr)); - dbgPrintf(DEFCOL, "DONE3.\n"); - return 0; -} - -/* -** CClientSocket() -*/ -CClientSocket::CClientSocket() -{ - dbgPrintf(DEFCOL, "Initializing client socket... "); - socket_fd = (SOCKET)-1; - dbgPrintf(DEFCOL, "DONE4.\n"); -} - -/* -** ~CClientSocket() -*/ -CClientSocket::~CClientSocket() -{ - dbgPrintf(DEFCOL, "Freeing client socket... "); - if (socket_fd != (SOCKET)-1) - close(socket_fd); - dbgPrintf(DEFCOL, "DONE5.\n"); -} - -/* -** connect() -*/ -int CClientSocket::connect(const char *ip_addr, const char *str_port) -{ - dbgPrintf(DEFCOL, "Connect to %s %s...\n", ip_addr, str_port); - - // put that in the constructor? - if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == (SOCKET)-1) - return SOCKET_ERROR; - - if (getIP(ip_addr) == GETHOSTBYNAME_ERROR) - return GETHOSTBYNAME_ERROR; - addr.sin_port = htons(atoi(str_port)); - - if (::connect(socket_fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) - return CONNECT_ERROR; - - FD_SET(socket_fd, &rset); - - dbgPrintf(DEFCOL, "DONE6.\n"); - - return 0; -} - -/* - * write() - */ -int CClientSocket::write(msg_t *msg) -{ - int len; - - if (msg->length < 0) - msg->length = (INT32)strlen(msg->buffer); - if (msg->length > PACKET_SIZE) - return WRITE_ERROR; // too big - len = msg->length + HEADER_SIZE; - - msg->id = htonl(msg->id); - msg->type = htonl(msg->type); - msg->length = htonl(msg->length); - msg->room = htonl(msg->room); - - dbgPrintf(DEFCOL, "Write a message %d (%s)... ", len, msg->buffer); - - if (send(socket_fd, (const char *)msg, len, 0) != len) - return WRITE_ERROR; - - dbgPrintf(DEFCOL, "DONE7.\n"); - - return 0; -} - -/* - * read() - */ -int CClientSocket::read(msg_t *msg) -{ - struct timeval timeout; - fd_set tset; - - dbgPrintf(DEFCOL, "Waiting a message... "); - - timeout.tv_sec = 60, timeout.tv_usec = 0; - memcpy(&tset, &rset, sizeof (tset)); - if ((select(255, &tset, NULL, NULL, &timeout)) <= 0) - return TIMEOUT_ERROR; - - if (!FD_ISSET(socket_fd, &tset)) - return READ_ERROR; - - dbgPrintf(DEFCOL, "Reading a message.\n"); - - if (recv(socket_fd, (char *)msg, HEADER_SIZE, 0) != HEADER_SIZE) - return READ_ERROR; - - msg->id = ntohl(msg->id); - msg->type = ntohl(msg->type); - msg->length = ntohl(msg->length); - msg->room = ntohl(msg->room); - - if (!msg->length) // work around a bug in Windows 2000 - return 0; - - if (msg->length > PACKET_SIZE) - return READ_ERROR; // packet too big - - if (recv(socket_fd, msg->buffer, msg->length, 0) != msg->length) - return READ_ERROR; - - dbgPrintf(DEFCOL, "DONE8.\n"); - - return 0; -} - -/* -** CServerSocket() -*/ -CServerSocket::CServerSocket() -{ - size_t id; - dbgPrintf(DEFCOL, "Initializing server socket... "); - num_clients = 0; - accept_fd = udp_fd = (SOCKET)-1; - for (id = 0; id < MAX_CLIENT; id++) - client_fd[id] = (SOCKET)-1; - udp_addr.sin_family = AF_INET; - dbgPrintf(DEFCOL, "DONE9.\n"); -} - -/* -** ~CServerSocket() -*/ -CServerSocket::~CServerSocket() -{ - size_t id; - dbgPrintf(DEFCOL, "Freeing server socket... "); - if (udp_fd != (SOCKET)-1) - close(udp_fd); - if (accept_fd != (SOCKET)-1) - close(accept_fd); - for (id = 0; id < num_clients || id < MAX_CLIENT; id++) - if (client_fd[id] != (SOCKET)-1) - close(client_fd[id]); - dbgPrintf(DEFCOL, "DONE10.\n"); -} - -/* -** listen() -*/ -int CServerSocket::listen(const char *str_port) -{ - dbgPrintf(DEFCOL, "Listen on %s... ", str_port); - // Init TCP socket - if ((accept_fd = socket(AF_INET, SOCK_STREAM, 0)) == (SOCKET)-1) - return SOCKET_ERROR; - int one = 1; setsockopt(accept_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&one, sizeof(int)); - - addr.sin_addr.s_addr = htonl(INADDR_ANY); - addr.sin_port = htons(atoi(str_port)); - - if (bind(accept_fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) - return BIND_ERROR; - - if (::listen(accept_fd, 5) < 0) - return LISTEN_ERROR; - - FD_SET(accept_fd, &rset); - - // Init UDP socket - if ((udp_fd = socket(AF_INET, SOCK_DGRAM, 0)) == (SOCKET)-1) - return SOCKET_ERROR; - - udp_addr.sin_addr.s_addr = htonl(INADDR_ANY); - udp_addr.sin_port = htons(atoi(str_port)+1); - - if (bind(udp_fd, (struct sockaddr *) &udp_addr, sizeof (udp_addr)) < 0) - return BIND_ERROR; - - FD_SET(udp_fd, &rset); - - dbgPrintf(DEFCOL, "DONE11.\n"); - - return 0; -} - -/* - * deleteClient(): - */ -int CServerSocket::deleteClient(size_t id) -{ - dbgPrintf(DEFCOL, "Deleting (client %u) of %u... ", id+1, num_clients); - FD_CLR(client_fd[id], &rset); - close(client_fd[id]); - if (num_clients != 0) - num_clients--; - client_fd[id] = client_fd[num_clients]; // move the top socket into this now empty space - memmove(&client_addr[id], &client_addr[num_clients], sizeof (client_addr[num_clients])); - client_fd[num_clients] = (SOCKET)-1; // now empty the top socket - memset(&client_addr[num_clients], 0 , sizeof (client_addr[num_clients])); - - dbgPrintf(DEFCOL, "DONE12.\n"); - - return 0; -} - -/* - * getUdpIP() - */ -const char *CServerSocket::getUdpIP(void) -{ - return inet_ntoa(udp_in_addr.sin_addr); -} - -/* - * getUdpPort() - */ -const char *CServerSocket::getUdpPort(bool offset) -{ - static char buffer[8]; - UINT16 port = htons(udp_in_addr.sin_port); - if (offset) - port--; - snprintf(buffer, sizeof buffer, "%d", port); - return buffer; -} - -/* - * read(): wait message on a socket, if it's an accept, call the accept method, - * otherwise read the message and update msg->id to the right value - * (client cannot put valid entry in msg->id) - */ -int CServerSocket::read(msg_t *msg) -{ - struct timeval timeout; - fd_set tset; - UINT32 id; - socklen_t lg = sizeof (addr); - - timeout.tv_sec = 20, timeout.tv_usec = 0; - memcpy(&tset, &rset, sizeof (tset)); - if ((select(255, &tset, NULL, NULL, &timeout)) <= 0) - { - msg->type = TIMEOUT_MSG; - return TIMEOUT_ERROR; - } - - if (FD_ISSET(udp_fd, &tset)) - { - msg->type = UDP_RECV_MSG; // This is a UDP packet - msg->length = recvfrom(udp_fd, msg->buffer, PACKET_SIZE, 0, (struct sockaddr *)&udp_in_addr, &lg); - return 0; - } - - if (FD_ISSET(accept_fd, &tset)) - { - msg->type = ACCEPT_MSG; - return this->accept(); - } - - id = 0; - while (!FD_ISSET(client_fd[id], &tset) && id < MAX_CLIENT) - id++; - - // paranoia - if ( (id >= num_clients) || (id >= MAX_CLIENT) ) - { - dbgPrintf(DEFCOL, "This should never happen\n"); - return READ_ERROR; - } - - dbgPrintf(DEFCOL, "Reading a message from (socket %u) for (client %u)... ", client_fd[id], id+1); - - if (recv(client_fd[id], (char *)msg, HEADER_SIZE, 0) != HEADER_SIZE) - { - deleteClient(id); // the connection is not good with the client, kick him - return READ_ERROR; - } - - //msg->id = ntohl(msg->id); // see comment above - msg->type = ntohl(msg->type); - msg->length = ntohl(msg->length); - msg->room = ntohl(msg->room); - - if ((0 < msg->length) && (msg->length < PACKET_SIZE)) - { - timeout.tv_sec = 0, timeout.tv_usec = 0; // the info should be already in the socket, so don't wait - memcpy(&tset, &rset, sizeof (tset)); - if ((select(255, &tset, NULL, NULL, &timeout)) <= 0) - { - deleteClient(id); - return READ_ERROR; - } - - if (!FD_ISSET(client_fd[id], &tset)) - { - deleteClient(id); - return READ_ERROR; - } - if (recv(client_fd[id], msg->buffer, msg->length, 0) != msg->length) - { - deleteClient(id); - return READ_ERROR; - } - } - - msg->id = id; - - dbgPrintf(DEFCOL, "DONE13.\n"); - - return 0; -} - -/* - * write(): - */ -int CServerSocket::write(msg_t *msg) -{ - struct timeval timeout; - fd_set tset; - int len; - - dbgPrintf(DEFCOL, "Write a message... "); - FD_ZERO(&tset); - /* - * Be sure the msg->id is still valid; we cannot do - * a delete between a read and a write. Should we - * use a readpending set in read method, so we know - * that we are still waiting for writing? For now, - * it's the responsibility of server code. - */ - FD_SET(client_fd[msg->id], &tset); - timeout.tv_sec = 0, timeout.tv_usec = 0; - if ((select(255, NULL, &tset, NULL, &timeout)) <= 0) - { - deleteClient(msg->id); // this shouldn't happen if the net connection is good - return TIMEOUT_ERROR; - } - if (msg->length < 0) - msg->length = (INT32)strlen(msg->buffer); - if (msg->length > PACKET_SIZE) - return WRITE_ERROR; // too big - len = msg->length+HEADER_SIZE; - //msg->id = htonl(msg->id); // same comment as for read - msg->type = htonl(msg->type); - msg->length = htonl(msg->length); - if (send(client_fd[msg->id], (const char *)msg, len, 0) != len) - { - deleteClient(msg->id); - return WRITE_ERROR; - } - - dbgPrintf(DEFCOL, "DONE14.\n"); - - return 0; -} - -/* - * writeUDP() - */ -int CServerSocket::writeUDP(const char *data, size_t length, const char *ip, UINT16 port) -{ - sockaddr_in sin; - struct timeval timeout; - fd_set tset; - - FD_ZERO(&tset); - FD_SET(udp_fd, &tset); - - if ((select(255, NULL, &tset, NULL, &timeout)) <= 0) - { - return TIMEOUT_ERROR; - } - - sin.sin_family = AF_INET; - inet_aton(ip, &sin.sin_addr); - sin.sin_port = htons(port); - - sendto(udp_fd, data, (int)length, 0, (sockaddr*)&sin, sizeof(sin)); - - return 0; -} - - -/* - * accept() - */ -int CServerSocket::accept() -{ - socklen_t lg = sizeof (addr); - - dbgPrintf(DEFCOL, "Accepting on (socket %u)... ", accept_fd); - - if ((client_fd[num_clients] = ::accept(accept_fd, (struct sockaddr *) &addr, &lg)) == (SOCKET)-1) - { - //client_fd[num_clients] = (SOCKET)-1; // we haven't accepted the client, so set it at default value - return ACCEPT_ERROR; - } - - if (num_clients < MAX_CLIENT-1) - { - extern FILE *sockfile; - - logPrintf(sockfile, "Accepting on socket %u for client %u (%s:%i)\n", - client_fd[num_clients], num_clients+1, inet_ntoa(addr.sin_addr), htons(addr.sin_port)); - memcpy(&client_addr[num_clients], &addr, sizeof (addr)); - FD_SET(client_fd[num_clients], &rset); - num_clients++; - } - else // we have reached the maximum number of clients - { - // close the connection (meaning "try again" for the client) - close(client_fd[num_clients]); - client_fd[num_clients] = (SOCKET)-1; - return ACCEPT_ERROR; - } - - //dbgPrintf(DEFCOL, "DONE15.\n"); - - return 0; -} - -/* - * getClientIP() - */ -const char *CServerSocket::getClientIP(size_t id) -{ - dbgPrintf(DEFCOL, "getClientIP: %u\n", id); - return inet_ntoa(client_addr[id].sin_addr); -} - -/* - * getClientPort() - */ -const char *CServerSocket::getClientPort(size_t id) -{ - static char buffer[8]; - - dbgPrintf(DEFCOL, "getClientPort: %u\n", id); - UINT16 port = htons(client_addr[id].sin_port); - snprintf(buffer, sizeof buffer, "%d", port); - return buffer; -} - -/* - * mySignal() - */ -#ifndef _WIN32 -static Sigfunc *mySignal(int signo, Sigfunc *func) -{ - struct sigaction act, oact; - - act.sa_handler = func; - sigemptyset(&act.sa_mask); -#if defined (SA_RESTART) - act.sa_flags = SA_RESTART; -#else - act.sa_flags = 0; -#endif - if (sigaction(signo, &act, &oact) < 0) - return SIG_ERR; - return oact.sa_handler; -} - -/* - * sigHandler() - */ -static void sigHandler(int signr) -{ - mySignal(signr, sigHandler); - switch (signr) - { - case SIGPIPE: - dbgPrintf(DEFCOL, "Catch SIG_PIPE\n"); - /// TODO be sure the socket is closed if the client - /// didn't quit properly - break; - } -} -#endif diff --git a/tools/masterserver/ipcs.h b/tools/masterserver/ipcs.h deleted file mode 100644 index b9dc52fdf..000000000 --- a/tools/masterserver/ipcs.h +++ /dev/null @@ -1,281 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// 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 2 -// 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. -// -//----------------------------------------------------------------------------- - -#ifndef _IPCS_H_ -#define _IPCS_H_ - -#include "common.h" - -#if defined (_WIN32) || defined ( __OS2__) -#include -#include -typedef int socklen_t; -#if defined (__OS2__) -#include -#endif -#endif -#ifdef _WIN32 -#include -#define close closesocket -#else -#include // inet_addr(),... -#endif - -#ifndef SOCKET -#define SOCKET u_int -#endif - -// ================================ DEFINITIONS =============================== - -#define PACKET_SIZE 1024 -#define MAX_CLIENT 512 - -#ifndef _WIN32 -#define NO_ERROR 0 -#define SOCKET_ERROR -201 -#endif -#define BIND_ERROR -202 -#define CONNECT_ERROR -203 -#define LISTEN_ERROR -204 -#define ACCEPT_ERROR -205 -#define WRITE_ERROR -210 -#define READ_ERROR -211 -#define CLOSE_ERROR -212 -#define GETHOSTBYNAME_ERROR -220 -#define SELECT_ERROR -230 -#define TIMEOUT_ERROR -231 -#define MALLOC_ERROR -301 - -#define INVALID_MSG -1 -#define ACCEPT_MSG 100 -#define ADD_SERVER_MSG 101 -#define ADD_CLIENT_MSG 102 -#define REMOVE_SERVER_MSG 103 -#define ADD_SERVERv2_MSG 104 -#define GET_SERVER_MSG 200 -#define SEND_SERVER_MSG 201 -#define GET_LOGFILE_MSG 202 -#define SEND_FILE_MSG 203 -#define ERASE_LOGFILE_MSG 204 -#define GET_SHORT_SERVER_MSG 205 -#define SEND_SHORT_SERVER_MSG 206 -#define ASK_SERVER_MSG 206 -#define ANSWER_ASK_SERVER_MSG 207 -#define GET_MOTD_MSG 208 -#define SEND_MOTD_MSG 209 -#define GET_ROOMS_MSG 210 -#define SEND_ROOMS_MSG 211 -#define GET_ROOMS_HOST_MSG 212 -#define GET_VERSION_MSG 213 -#define SEND_VERSION_MSG 214 -#define GET_BANNED_MSG 215 -#define PING_SERVER_MSG 216 - -#define UDP_RECV_MSG 300 -#define TIMEOUT_MSG 301 -#define HTTP_REQUEST_MSG 875770417 // "4321" -#define SEND_HTTP_REQUEST_MSG 875770418 // "4322" -#define TEXT_REQUEST_MSG 825373494 // "1236" -#define SEND_TEXT_REQUEST_MSG 825373495 // "1237" -#define RSS92_REQUEST_MSG 825373496 // "1238" -#define SEND_RSS92_REQUEST_MSG 825373497 // "1239" -#define RSS10_REQUEST_MSG 825373744 // "1240" -#define SEND_RSS10_REQUEST_MSG 825373745 // "1241" -#define ADD_PSERVER_MSG 0xabacab81 // this number just need to be different than the others -#define REMOVE_PSERVER_MSG 0xabacab82 - -// Sent FROM Client -#define LIVE_AUTH_USER 600 -#define LIVE_AUTH_KEY 601 -#define LIVE_GET_USER 602 -#define LIVE_UPDATE_LOCATION 603 -#define LIVE_UPDATE_PUBLIC_KEY 604 -#define LIVE_AUTH_PUBLIC_KEY 605 - -// Sent TO Client -#define LIVE_INVALID_KEY 800 -#define LIVE_INVALID_USER 801 -#define LIVE_AUTHORISED_KEY 802 -#define LIVE_SEND_USER 803 -#define LIVE_VALIDATED_USER 804 - -// Location Types -#define LIVE_LOCATION_SP 100 -#define LIVE_LOCATION_MENU 101 -#define LIVE_LOCATION_MP_JOIN 102 -#define LIVE_LOCATION_MP_HOST 103 -#define LIVE_LOCATION_MP_LOCAL 104 -#define LIVE_LOCATION_MP_PRIVATE 105 - -#define HEADER_SIZE ((UINT32)sizeof (UINT32)*4) - -#define HEADER_MSG_POS 0 -#define IP_MSG_POS 16 -#define PORT_MSG_POS 32 -#define HOSTNAME_MSG_POS 40 - -#if defined(_MSC_VER) -#pragma pack(1) -#endif - -// Keep this structure 8 bytes aligned (current size is 80) -typedef struct -{ - char header[16]; // information such as password - char ip[16]; - char port[8]; - char name[32]; - INT32 room; - char key[32]; // Secret key for linking dedicated servers to accounts - char version[8]; // format is: x.yy.z (like 1.30.2 or 1.31) -} ATTRPACK msg_server_t; - -typedef struct -{ - char header[16]; - UINT32 id; - char name[32]; - char motd[256]; -} ATTRPACK msg_rooms_t; - -typedef struct -{ - char header[16]; - char ipstart[16]; - char ipend[16]; - char endstamp[32]; - char reason[256]; - UINT8 hostonly; -} ATTRPACK msg_ban_t; - -typedef struct -{ - char header[16]; - INT32 id; - char username[100]; - char password[32]; -} ATTRPACK msg_live_auth_t; - -typedef struct -{ - char header[16]; - INT32 uid; - char username[100]; - INT32 location_type; - char location_ip[32]; - INT32 location_port; - INT32 lastseen_type; - char lastseen_data1[256]; - char lastseen_data2[256]; - char lastseen_data3[256]; -} ATTRPACK msg_live_user_t; - -typedef struct -{ - char header[16]; - UINT8 location_type; - char location_ip[32]; - INT32 location_port; - char location_data1[256]; - char location_data2[256]; - char location_data3[256]; -} ATTRPACK msg_live_updatelocation_t; - -typedef struct -{ - char header[16]; - char publickey[256]; - char username[256]; -} ATTRPACK msg_live_validateuser_t; - -typedef struct -{ - char header[16]; - char username[256]; - UINT8 keytype; - char keydata[256]; -} ATTRPACK msg_live_update_key_t; - - -typedef struct -{ - UINT32 id; - INT32 type; - INT32 room; - INT32 length; - char buffer[PACKET_SIZE]; -} ATTRPACK msg_t; - -#if defined(_MSC_VER) -#pragma pack() -#endif - -class CSocket -{ -protected: - sockaddr_in addr; - msg_t msg; - fd_set rset; -public: - int getIP(const char *); - CSocket(); - ~CSocket(); -}; - -class CServerSocket : public CSocket -{ -private: - sockaddr_in udp_addr; - sockaddr_in udp_in_addr; - SOCKET udp_fd; - SOCKET accept_fd; - size_t num_clients; - SOCKET client_fd[MAX_CLIENT]; - sockaddr_in client_addr[MAX_CLIENT]; - -public: - int deleteClient(size_t id); - int listen(const char *str_port); - int accept(void); - int read(msg_t *msg); - const char *getUdpIP(void); - const char *getUdpPort(bool); - int write(msg_t *msg); - int writeUDP(const char *data, size_t length, const char *ip, UINT16 port); - const char *getClientIP(size_t id); - const char *getClientPort(size_t id); - CServerSocket(void); - ~CServerSocket(void); -}; - -class CClientSocket : public CSocket -{ -private: - SOCKET socket_fd; -public: - int connect(const char *ip_addr, const char *str_port); - int read(msg_t *msg); - int write(msg_t *msg); - CClientSocket(void); - ~CClientSocket(void); -}; - -// ================================== PROTOS ================================== - -// ================================== EXTERNS ================================= - -#endif diff --git a/tools/masterserver/masterserver.sh b/tools/masterserver/masterserver.sh deleted file mode 100755 index 9b1adb128..000000000 --- a/tools/masterserver/masterserver.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/sh -e -# -# SRB2 MasterServer - start up the masterserver -# - -# Get LSB functions -. /lib/lsb/init-functions -. /etc/default/rcS - -SRB2MS=/usr/local/bin/masterserver -SRB2MS_PORT=28900 - -# Check that the package is still installed -[ -x $SRB2MS ] || exit 0; - -case "$1" in - start) - log_begin_msg "Starting SRB2MS..." - umask 002 - if start-stop-daemon --start \ - --exec $SRB2MS \ - -- $SRB2MS_PORT; then - log_end_msg 0 - else - log_end_msg $? - fi - ;; - - stop) - log_begin_msg "Stopping SRB2MS..." - if start-stop-daemon --stop --exec $SRB2MS; then - log_end_msg 0 - else - log_end_msg $? - fi - ;; - - restart|force-reload) - "$0" stop && "$0" start - ;; - - *) - e cho "Usage: /etc/init.d/masterserver {start|stop|restart|force-reload}" - exit 1 - ;; -esac - -exit 0 diff --git a/tools/masterserver/md5.cpp b/tools/masterserver/md5.cpp deleted file mode 100644 index 4f4ff2292..000000000 --- a/tools/masterserver/md5.cpp +++ /dev/null @@ -1,363 +0,0 @@ -/* MD5 - converted to C++ class by Frank Thilo (thilo@unix-ag.org) - for bzflag (http://www.bzflag.org) - - based on: - - md5.h and md5.c - reference implemantion of RFC 1321 - - Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -rights reserved. - -License to copy and use this software is granted provided that it -is identified as the "RSA Data Security, Inc. MD5 Message-Digest -Algorithm" in all material mentioning or referencing this software -or this function. - -License is also granted to make and use derivative works provided -that such works are identified as "derived from the RSA Data -Security, Inc. MD5 Message-Digest Algorithm" in all material -mentioning or referencing the derived work. - -RSA Data Security, Inc. makes no representations concerning either -the merchantability of this software or the suitability of this -software for any particular purpose. It is provided "as is" -without express or implied warranty of any kind. - -These notices must be retained in any copies of any part of this -documentation and/or software. - -*/ - -/* interface header */ -#include "md5.h" - -/* system implementation headers */ -#include -#include - - -// Constants for MD5Transform routine. -#define S11 7 -#define S12 12 -#define S13 17 -#define S14 22 -#define S21 5 -#define S22 9 -#define S23 14 -#define S24 20 -#define S31 4 -#define S32 11 -#define S33 16 -#define S34 23 -#define S41 6 -#define S42 10 -#define S43 15 -#define S44 21 - -/////////////////////////////////////////////// - -// F, G, H and I are basic MD5 functions. -inline MD5::uint4 MD5::F(uint4 x, uint4 y, uint4 z) { - return (x&y) | (~x&z); -} - -inline MD5::uint4 MD5::G(uint4 x, uint4 y, uint4 z) { - return (x&z) | (y&~z); -} - -inline MD5::uint4 MD5::H(uint4 x, uint4 y, uint4 z) { - return x^y^z; -} - -inline MD5::uint4 MD5::I(uint4 x, uint4 y, uint4 z) { - return y ^ (x | ~z); -} - -// rotate_left rotates x left n bits. -inline MD5::uint4 MD5::rotate_left(uint4 x, int n) { - return (x << n) | (x >> (32-n)); -} - -// FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. -// Rotation is separate from addition to prevent recomputation. -inline void MD5::FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a+ F(b,c,d) + x + ac, s) + b; -} - -inline void MD5::GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + G(b,c,d) + x + ac, s) + b; -} - -inline void MD5::HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + H(b,c,d) + x + ac, s) + b; -} - -inline void MD5::II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + I(b,c,d) + x + ac, s) + b; -} - -////////////////////////////////////////////// - -// default ctor, just initailize -MD5::MD5() -{ - init(); -} - -////////////////////////////////////////////// - -// nifty shortcut ctor, compute MD5 for string and finalize it right away -MD5::MD5(const std::string &text) -{ - init(); - update(text.c_str(), text.length()); - finalize(); -} - -////////////////////////////// - -void MD5::init() -{ - finalized=false; - - count[0] = 0; - count[1] = 0; - - // load magic initialization constants. - state[0] = 0x67452301; - state[1] = 0xefcdab89; - state[2] = 0x98badcfe; - state[3] = 0x10325476; -} - -////////////////////////////// - -// decodes input (unsigned char) into output (uint4). Assumes len is a multiple of 4. -void MD5::decode(uint4 output[], const uint1 input[], size_type len) -{ - for (unsigned int i = 0, j = 0; j < len; i++, j += 4) - output[i] = ((uint4)input[j]) | (((uint4)input[j+1]) << 8) | - (((uint4)input[j+2]) << 16) | (((uint4)input[j+3]) << 24); -} - -////////////////////////////// - -// encodes input (uint4) into output (unsigned char). Assumes len is -// a multiple of 4. -void MD5::encode(uint1 output[], const uint4 input[], size_type len) -{ - for (size_type i = 0, j = 0; j < len; i++, j += 4) { - output[j] = input[i] & 0xff; - output[j+1] = (input[i] >> 8) & 0xff; - output[j+2] = (input[i] >> 16) & 0xff; - output[j+3] = (input[i] >> 24) & 0xff; - } -} - -////////////////////////////// - -// apply MD5 algo on a block -void MD5::transform(const uint1 block[blocksize]) -{ - uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; - decode (x, block, blocksize); - - /* Round 1 */ - FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ - FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ - FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ - FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ - FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ - FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ - FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ - FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ - FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ - FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ - FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ - FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ - FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ - FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ - FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ - FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ - - /* Round 2 */ - GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ - GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ - GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ - GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ - GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ - GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ - GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ - GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ - GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ - GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ - GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ - GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ - GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ - GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ - GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ - GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ - - /* Round 3 */ - HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ - HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ - HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ - HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ - HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ - HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ - HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ - HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ - HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ - HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ - HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ - HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ - HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ - HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ - HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ - HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ - - /* Round 4 */ - II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ - II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ - II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ - II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ - II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ - II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ - II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ - II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ - II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ - II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ - II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ - II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ - II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ - II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ - II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ - II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ - - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - - // Zeroize sensitive information. - memset(x, 0, sizeof x); -} - -////////////////////////////// - -// MD5 block update operation. Continues an MD5 message-digest -// operation, processing another message block -void MD5::update(const unsigned char input[], size_type length) -{ - // compute number of bytes mod 64 - size_type index = count[0] / 8 % blocksize; - - // Update number of bits - if ((count[0] += (length << 3)) < (length << 3)) - count[1]++; - count[1] += (length >> 29); - - // number of bytes we need to fill in buffer - size_type firstpart = 64 - index; - - size_type i; - - // transform as many times as possible. - if (length >= firstpart) - { - // fill buffer first, transform - memcpy(&buffer[index], input, firstpart); - transform(buffer); - - // transform chunks of blocksize (64 bytes) - for (i = firstpart; i + blocksize <= length; i += blocksize) - transform(&input[i]); - - index = 0; - } - else - i = 0; - - // buffer remaining input - memcpy(&buffer[index], &input[i], length-i); -} - -////////////////////////////// - -// for convenience provide a verson with signed char -void MD5::update(const char input[], size_type length) -{ - update((const unsigned char*)input, length); -} - -////////////////////////////// - -// MD5 finalization. Ends an MD5 message-digest operation, writing the -// the message digest and zeroizing the context. -MD5& MD5::finalize() -{ - static unsigned char padding[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - - if (!finalized) { - // Save number of bits - unsigned char bits[8]; - encode(bits, count, 8); - - // pad out to 56 mod 64. - size_type index = count[0] / 8 % 64; - size_type padLen = (index < 56) ? (56 - index) : (120 - index); - update(padding, padLen); - - // Append length (before padding) - update(bits, 8); - - // Store state in digest - encode(digest, state, 16); - - // Zeroize sensitive information. - memset(buffer, 0, sizeof buffer); - memset(count, 0, sizeof count); - - finalized=true; - } - - return *this; -} - -////////////////////////////// - -// return hex representation of digest as string -std::string MD5::hexdigest() const -{ - if (!finalized) - return ""; - - char buf[33]; - for (int i=0; i<16; i++) - sprintf(buf+i*2, "%02x", digest[i]); - buf[32]=0; - - return std::string(buf); -} - -////////////////////////////// - -std::ostream& operator<<(std::ostream& out, MD5 md5) -{ - return out << md5.hexdigest(); -} - -////////////////////////////// - -std::string md5(const std::string str) -{ - MD5 md5 = MD5(str); - - return md5.hexdigest(); -} diff --git a/tools/masterserver/md5.h b/tools/masterserver/md5.h deleted file mode 100644 index 55a90c4cb..000000000 --- a/tools/masterserver/md5.h +++ /dev/null @@ -1,93 +0,0 @@ -/* MD5 - converted to C++ class by Frank Thilo (thilo@unix-ag.org) - for bzflag (http://www.bzflag.org) - - based on: - - md5.h and md5.c - reference implementation of RFC 1321 - - Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -rights reserved. - -License to copy and use this software is granted provided that it -is identified as the "RSA Data Security, Inc. MD5 Message-Digest -Algorithm" in all material mentioning or referencing this software -or this function. - -License is also granted to make and use derivative works provided -that such works are identified as "derived from the RSA Data -Security, Inc. MD5 Message-Digest Algorithm" in all material -mentioning or referencing the derived work. - -RSA Data Security, Inc. makes no representations concerning either -the merchantability of this software or the suitability of this -software for any particular purpose. It is provided "as is" -without express or implied warranty of any kind. - -These notices must be retained in any copies of any part of this -documentation and/or software. - -*/ - -#ifndef BZF_MD5_H -#define BZF_MD5_H - -#include -#include - - -// a small class for calculating MD5 hashes of strings or byte arrays -// it is not meant to be fast or secure -// -// usage: 1) feed it blocks of uchars with update() -// 2) finalize() -// 3) get hexdigest() string -// or -// MD5(std::string).hexdigest() -// -// assumes that char is 8 bit and int is 32 bit -class MD5 -{ -public: - typedef unsigned int size_type; // must be 32bit - - MD5(); - MD5(const std::string& text); - void update(const unsigned char *buf, size_type length); - void update(const char *buf, size_type length); - MD5& finalize(); - std::string hexdigest() const; - friend std::ostream& operator<<(std::ostream&, MD5 md5); - -private: - void init(); - typedef unsigned char uint1; // 8bit - typedef unsigned int uint4; // 32bit - enum {blocksize = 64}; // VC6 won't eat a const static int here - - void transform(const uint1 block[blocksize]); - static void decode(uint4 output[], const uint1 input[], size_type len); - static void encode(uint1 output[], const uint4 input[], size_type len); - - bool finalized; - uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk - uint4 count[2]; // 64bit counter for number of bits (lo, hi) - uint4 state[4]; // digest so far - uint1 digest[16]; // the result - - // low level logic operations - static inline uint4 F(uint4 x, uint4 y, uint4 z); - static inline uint4 G(uint4 x, uint4 y, uint4 z); - static inline uint4 H(uint4 x, uint4 y, uint4 z); - static inline uint4 I(uint4 x, uint4 y, uint4 z); - static inline uint4 rotate_left(uint4 x, int n); - static inline void FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); -}; - -std::string md5(const std::string str); - -#endif diff --git a/tools/masterserver/server.cpp b/tools/masterserver/server.cpp deleted file mode 100644 index b7ed0d6b4..000000000 --- a/tools/masterserver/server.cpp +++ /dev/null @@ -1,1037 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// 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 2 -// 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. -// -//----------------------------------------------------------------------------- -#ifdef __GNUC__ -#include -#include -#endif -#include -#include -#include -#include "ipcs.h" -#include "common.h" -#include "mysql.h" -#include "md5.h" -#include -//#include - -//============================================================================= - -#ifdef __GNUC__ -#define ATTRPACK __attribute__ ((packed)) -#else -#define ATTRPACK -#endif - -#define PT_ASKINFOVIAMS 15 - -static CServerSocket server_socket; - -FILE *logfile; -FILE *errorfile; -FILE *mysqlfile; -FILE *sockfile; -FILE *pidfile; - -#if defined(_MSC_VER) -#pragma pack(1) -#endif - -typedef struct -{ - char ip[16]; // Big enough to hold a full address. - UINT16 port; - UINT8 padding1[2]; - UINT32 time; -} ATTRPACK ms_holepunch_packet_t; - -typedef struct -{ - char clientaddr[22]; - UINT8 padding1[2]; - UINT32 time; -} ATTRPACK msaskinfo_pak; - -// -// SRB2 network packet data. -// -typedef struct -{ - UINT32 checksum; - UINT8 ack; // if not null the node asks for acknowledgement, the receiver must resend the ack - UINT8 ackreturn; // the return of the ack number - - UINT8 packettype; - UINT8 reserved; // padding - - msaskinfo_pak msaskinfo; -} ATTRPACK doomdata_t; - -#if defined(_MSC_VER) -#pragma pack() -#endif - -//============================================================================= - -#define HOSTNAME "loopback" -#define USER "srb2_ms" -#define PASSWORD "gLRDRb7WgLRDRb7W" -#define DATABASE "srb2_ms" - -// MySQL Stuff :D - - const char *server = HOSTNAME; - const char *user = USER; - const char *password = PASSWORD; - const char *database = DATABASE; - time_t lastupdate; - - MYSQL *conn; - MYSQL_RES *res; - MYSQL_ROW row; - int mysqlconnected = 0; -/* -char *str_replace(char * t1, char * t2, char * t6) -{ - char*t4; - char*t5=new(0); - - while(strstr(t6,t1)){ - t4=strstr(t6,t1); - strncpy(t5+strlen(t5),t6,t4-t6); - strcat(t5,t2); - t4+=strlen(t1); - t6=t4; - } - return strcat(t5,t4); -} -*/ -/* -// Cue was here -char *str_quakeformat(char *msg) -{ - char *quakemsg , *quakemsg1, *quakemsg2; - char *quakemsg3, *quakemsg4, *quakemsg5; - char *quakemsg6, *quakemsg7, *quakemsg8; - - quakemsg1 = new(sizeof(char) * (strlen(msg) + 1)); - strcpy(quakemsg1, msg); - quakemsg2 = str_replace("^1", "\x81",quakemsg1); - quakemsg3 = str_replace("^2", "\x82",quakemsg2); - quakemsg4 = str_replace("^3", "\x83",quakemsg3); - quakemsg5 = str_replace("^4", "\x84",quakemsg4); - quakemsg6 = str_replace("^5", "\x85",quakemsg5); - quakemsg7 = str_replace("^6", "\x86",quakemsg6); - quakemsg8 = str_replace("^7", "\x87",quakemsg7); - quakemsg = str_replace("^0", "\x80",quakemsg8); - delete(quakemsg1); - delete(quakemsg2); - delete(quakemsg3); - delete(quakemsg4); - delete(quakemsg5); - delete(quakemsg6); - delete(quakemsg7); - delete(quakemsg8); - - return quakemsg; -} - */ -void MySQL_Conn(bool force) { - //if(mysql_ping(conn)) - //mysqlconnected = 0; - logPrintf(mysqlfile, "Trying to connect to MySQL...\n"); - if(mysqlconnected != 1 || force) { - if(force) - mysql_close(conn); - const char *server = HOSTNAME; - const char *user = USER; - const char *password = PASSWORD; - const char *database = DATABASE; - - conn = mysql_init(NULL); - - /* Connect to database */ - if (!mysql_real_connect(conn, server, - user, password, database, 8219, NULL, 0)) { - logPrintf(errorfile, "%s\n", mysql_error(conn)); - } - conn = mysql_init(NULL); - - /* Connect to database */ - if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) { - logPrintf(errorfile, "%s\n", mysql_error(conn)); - mysqlconnected = 0; - } else { - logPrintf(mysqlfile, "Connection to MySQL Database successful!\n"); - mysqlconnected = 1; - } - } -} - -static int MySQL_CheckBan(const char *ip, UINT32 id, bool sendinfo, bool type) { - msg_t msg; - int writecode; - MySQL_Conn(false); - msg.id = id; - char banqueryp1[500] = "SELECT bid,INET_NTOA(ipstart),INET_NTOA(ipend),DATE_FORMAT(FROM_UNIXTIME(full_endtime),'%%a %%b %%e %%Y at %%k:%%i (CDT)'),reason,hostonly,permanent FROM ms_bans WHERE INET_ATON('%s') BETWEEN `ipstart` AND `ipend` AND (`full_endtime` > %ld OR `permanent` = '1') LIMIT 1"; -// char exqueryp1[500] = "SELECT * FROM ms_exceptions WHERE `ip` = '%s' AND `bid` = '%s' LIMIT 1"; -// char exquery[500]; - char banquery[500]; -// char bid[5]; - - time_t current_time = time (NULL); - sprintf(banquery, banqueryp1, ip, current_time); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", banquery); - if(mysql_query(conn, banquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - return false; - } else { - res = mysql_store_result(conn); - if(mysql_num_rows(res) >= 1) { - logPrintf(logfile, "We got a ban coming on!\n"); - row = mysql_fetch_row(res); - if(!type && strcmp(row[5],"1") == 0) - return false; - if(sendinfo) - { - logPrintf(logfile, "And we're meant to tell them some more!\n"); - msg_ban_t *info = (msg_ban_t *) msg.buffer; - info->header[0] = '\0'; - - logPrintf(logfile, "Got Ban: %s - %s, ends %s, for %s\n", row[1], row[2], row[3], row[4]); - logPrintf(logfile, "COPY: ipstart\n"); - strcpy(info->ipstart, row[1]); - logPrintf(logfile, "COPY: ipend\n"); - strcpy(info->ipend, row[2]); - logPrintf(logfile, "COPY: endtime\n"); - if(strcmp(row[6], "0") == 0) - { - logPrintf(logfile, "COPY: It's not permanent.\n"); - strcpy(info->endstamp, row[3]); - } - else - { - logPrintf(logfile, "COPY: It's permanent.\n"); - strcpy(info->endstamp, "Never"); - } - logPrintf(logfile, "COPY: reason\n"); - strcpy(info->reason, row[4]); - logPrintf(logfile, "COPY: hostonly\n"); - if(strcmp(row[5],"0") == 0) - info->hostonly = false; - else - info->hostonly = true; - - if(info->hostonly) - logPrintf(logfile, "BAN HAMMER: %s - %s || Reason: %s || Endstamp: %s || HOSTONLY\n", info->ipstart, info->ipend, info->reason, info->endstamp); - else - logPrintf(logfile, "BAN HAMMER: %s - %s || Reason: %s || Endstamp: %s || NOTHOSTONLY\n", info->ipstart, info->ipend, info->reason, info->endstamp); - mysql_free_result(res); - msg.type = GET_BANNED_MSG; - msg.length = sizeof (msg_ban_t); - msg.room = 0; - logPrintf(logfile, "Sending message?\n"); - writecode = server_socket.write(&msg); - logPrintf(logfile, "Message sent! :D\n"); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d " - "deleted\n", writecode, id); - return true; - } - } - return true; - } else { - mysql_free_result(res); - return false; - } - } -} - -int MySQL_CheckRoom(UINT32 room) -{ - MySQL_Conn(false); - char checkqueryp1[500] = "SELECT private FROM `ms_rooms` WHERE `room_id` = '%d' AND `private` = '1' LIMIT 1"; - char checkquery[500]; - sprintf(checkquery, checkqueryp1, room); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", checkquery); - if(mysql_query(conn, checkquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - return false; - } else { - res = mysql_store_result(conn); - if(mysql_num_rows(res) < 1) - return true; - else - return false; - } -} - -void MySQL_AddServer(const char *ip, const char *port, const char *name, const char *version, UINT32 room, bool firstadd, const char *key) { - char escapedName[255]; - char escapedPort[10]; - char escapedVersion[10]; - char escapedKey[32]; - char insertquery[5000]; - char checkquery[500]; - char updatequery[5000]; - char queryp1[5000] = "INSERT INTO `ms_servers` (`name`,`ip`,`port`,`version`,`timestamp`,`room`,`key`) VALUES ('%s','%s','%s','%s','%ld','%d','%s')"; - char checkqueryp1[500] = "SELECT room_override FROM `ms_servers` WHERE `ip` = '%s'"; - char updatequeryp1[5000]; - if(firstadd) - { - logPrintf(logfile, "First add.\n"); - strcpy(updatequeryp1, "UPDATE `ms_servers` SET `name` = '%s', `port` = '%s', `version` = '%s', timestamp = '%ld', upnow = '1', `room` = '%d', `delisted` = '0', `key` = '%s' WHERE `ip` = '%s'"); - } - else - { - logPrintf(logfile, "Update ping.\n"); - strcpy(updatequeryp1, "UPDATE `ms_servers` SET `name` = '%s', `port` = '%s', `version` = '%s', timestamp = '%ld', upnow = '1', `room` = '%d', `key` = '%s' WHERE `ip` = '%s' AND `delisted` = '0'"); - } - MySQL_Conn(false); - mysql_real_escape_string(conn, escapedName, name, (unsigned long)strlen(name)); - mysql_real_escape_string(conn, escapedPort, port, (unsigned long)strlen(port)); - mysql_real_escape_string(conn, escapedVersion, version, (unsigned long)strlen(version)); - mysql_real_escape_string(conn, escapedKey, key, (unsigned long)strlen(key)); - if(!MySQL_CheckBan(ip,0,false,1)) { - if(!MySQL_CheckRoom(room)) - { - logPrintf(errorfile, "IP %s tried to use the private room %d! THIS SHOULD NOT HAPPEN\n", ip, room); - return; - } - sprintf(checkquery, checkqueryp1, ip); - time_t timestamp; - timestamp = time (NULL); - logPrintf(logfile, "Checking for existing servers in table with the same IP...\n"); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", checkquery); - if(mysql_query(conn, checkquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - res = mysql_store_result(conn); - logPrintf(logfile, "Found %d rows...\n", mysql_num_rows(res)); - if(mysql_num_rows(res) < 1) { - mysql_free_result(res); - logPrintf(logfile, "Adding the temporary server: %s:%s || Name: %s || Version: %s || Time: %ld || Room: %d || Key: %s\n", ip, port, name, version, timestamp, room, key); - sprintf(insertquery, queryp1, escapedName, ip, escapedPort, escapedVersion, timestamp, room, escapedKey); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", insertquery); - if(mysql_query(conn, insertquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - logPrintf(logfile, "Server added successfully!\n"); - } - } else { - row = mysql_fetch_row(res); - if(atoi(row[0]) != 0) - room = atoi(row[0]); - mysql_free_result(res); - logPrintf(logfile, "Server's IP already exists, so let's just update it instead...\n"); - logPrintf(logfile, "Updating Server Data for %s\n", ip); - sprintf(updatequery, updatequeryp1, escapedName, escapedPort, escapedVersion, timestamp, room, escapedKey, ip); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", updatequery); - if(mysql_query(conn, updatequery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - logPrintf(logfile, "Server status for Server: %s:%s || Name: %s || Version: %s || Time: %ld || Room: %d || Key: %s set successfully.\n", ip, port, name, version, timestamp, room, key); - } - } - } - } else { - logPrintf(logfile, "IP %s is banned so do nothing.\n", ip); - } -} - -void MySQL_ListServers(UINT32 id, UINT32 type, const char *ip, UINT32 room) { - msg_t msg; - int writecode; - MySQL_Conn(false); - msg.id = id; - msg.type = type; - char servquery[1000]; - if(room == 0) - sprintf(servquery, "SELECT ip, port, name, version FROM ( SELECT * FROM `ms_servers` WHERE `upnow` = '1' ORDER BY `sid` ASC) as t2 ORDER BY `sticky` DESC"); - else - { - char servqueryp1[1000] = "SELECT ip, port, name, version FROM ( SELECT * FROM `ms_servers` WHERE `upnow` = '1' AND `room` = '%d' ORDER BY `sid` ASC) as t2 ORDER BY `sticky` DESC"; - sprintf(servquery, servqueryp1, room); - } - if(!MySQL_CheckBan(ip,0,false,0)) { - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", servquery); - if(mysql_query(conn, servquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - res = mysql_store_result(conn); - logPrintf(logfile, "Found %d servers...\n", mysql_num_rows(res)); - while ((row = mysql_fetch_row(res)) != NULL) - { - msg_server_t *info = (msg_server_t *) msg.buffer; - - info->header[0] = '\0'; // nothing interresting in it (for now) - strcpy(info->ip, row[0]); - strcpy(info->port, row[1]); - strcpy(info->name, row[2]); - strcpy(info->version, row[3]); - - msg.length = sizeof (msg_server_t); - msg.room = 0; - logPrintf(logfile, "Sending message?\n"); - writecode = server_socket.write(&msg); - logPrintf(logfile, "Message sent! :D\n"); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d " - "deleted\n", writecode, id); - return; - } - } - mysql_free_result(res); - } - } else { - logPrintf(logfile, "IP %s is banned so do nothing.\n", ip); - } -} - -void MySQL_ListRooms(UINT32 id, UINT32 type, const char *ip, bool sendtype) { - msg_t msg; - int writecode; - //(void)ip; - MySQL_Conn(false); - msg.id = id; - msg.type = type; - char roomquery[1000]; - logPrintf(logfile, "Check their ban status first... (ID %d)\n",id); - if(MySQL_CheckBan(ip,id,true,sendtype)) - return; - - //Hmph! I suppose it'll be up to me to handle this. ~Inuyasha - if (sendtype) - { - char overridequery[500]; - - sprintf(overridequery, "SELECT room_override FROM `ms_servers` WHERE `ip` = '%s' AND `room_override` > 0", ip); - logPrintf(mysqlfile, "Checking for room overrides! Executing MySQL Query: %s\n", overridequery); - if (mysql_query(conn, overridequery)) - { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - return; - } - - res = mysql_store_result(conn); - if (mysql_num_rows(res) >= 1) - { - int overriddenRoom; - - row = mysql_fetch_row(res); - overriddenRoom = atoi(row[0]); - mysql_free_result(res); - - sprintf(roomquery, "SELECT room_id, title, motd FROM `ms_rooms` WHERE `room_id` = '%d' LIMIT 1", overriddenRoom); - if (mysql_query(conn, roomquery)) - { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - return; - } - res = mysql_store_result(conn); - if (mysql_num_rows(res) >= 1) - { - msg_rooms_t *info = (msg_rooms_t *) msg.buffer; - char roommotd[300]; - - row = mysql_fetch_row(res); - - info->header[0] = '\0'; // nothing interesting in it (for now) - strcpy(info->name, row[1]); - - // Just in case, let's make sure we don't overflow. - sprintf(roommotd, "\x85Your server has had a room override applied to it, so this is the only room you may host in.\x80\n\n%s", row[2]); - strncpy(info->motd, roommotd, 255); - info->motd[255] = '\0'; - - info->id = atoi(row[0]); - - logPrintf(logfile, "Sending Room %s with ID %d and MOTD %s\n", info->name, info->id, info->motd); - - msg.length = sizeof (msg_rooms_t); - msg.room = 0; - logPrintf(logfile, "Sending message?\n"); - writecode = server_socket.write(&msg); - logPrintf(logfile, "Message sent! :D\n"); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d " - "deleted\n", writecode, id); - } - mysql_free_result(res); - return; - } - else - { - logPrintf(errorfile, "Someone's room override isn't set correctly! Room %d doesn't exist!", overriddenRoom); - mysql_free_result(res); - } - } - } - - if(sendtype) - sprintf(roomquery, "SELECT room_id, title, motd FROM `ms_rooms` WHERE `private` = '0' AND `visible` = '1' ORDER BY `order` ASC"); - else - sprintf(roomquery, "SELECT room_id, title, motd FROM `ms_rooms` WHERE `visible` = '1' ORDER BY `order` ASC"); - if(mysql_query(conn, roomquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else - { - res = mysql_store_result(conn); - logPrintf(logfile, "Found %d rooms...\n", mysql_num_rows(res)); - while ((row = mysql_fetch_row(res)) != NULL) - { - msg_rooms_t *info = (msg_rooms_t *) msg.buffer; - - info->header[0] = '\0'; // nothing interresting in it (for now) - strcpy(info->name, row[1]); - strcpy(info->motd, row[2]); - info->id = atoi(row[0]); - - logPrintf(logfile, "Sending Room %s with ID %d and MOTD %s\n", info->name, info->id, info->motd); - - msg.length = sizeof (msg_rooms_t); - msg.room = 0; - logPrintf(logfile, "Sending message?\n"); - writecode = server_socket.write(&msg); - logPrintf(logfile, "Message sent! :D\n"); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d " - "deleted\n", writecode, id); - return; - } - } - mysql_free_result(res); - } -} - -void MySQL_CheckVersion(UINT32 id, UINT32 type, const char *ip, UINT32 modid, const char *modversion) { - msg_t msg; - int writecode; - (void)ip; - MySQL_Conn(false); - msg.id = id; - msg.type = type; - char versionquery[1000]; - sprintf(versionquery, "SELECT * FROM `ms_versions` WHERE `mod_id` = '%d' AND `mod_version` > %s LIMIT 1",modid, modversion); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", versionquery); - if(mysql_query(conn, versionquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else - { - res = mysql_store_result(conn); - if(mysql_num_rows(res) < 1) - { - logPrintf(logfile, "Buffer to NULL\n"); - strcpy(msg.buffer,"NULL"); - } - else - { - row = mysql_fetch_row(res); - logPrintf(logfile, "Version found: %s || Codebase: %s || Version: %s || Version String: %s || Mod ID: %s\n", row[4], row[3], row[1], row[2], row[0]); - strcpy(msg.buffer,row[2]); - } - msg.length = sizeof msg.buffer; - msg.room = 0; - logPrintf(logfile, "Sending message?\n"); - writecode = server_socket.write(&msg); - logPrintf(logfile, "Message sent! :D\n"); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d " - "deleted\n", writecode, id); - return; - } - mysql_free_result(res); - } -} - -void MySQL_ListServServers(UINT32 id, UINT32 type, const char *ip) { - msg_t msg; - int writecode; - static char str[1024]; - //char banqueryp1[500] = "SELECT reason,name,FROM_UNIXTIME(endtime) FROM ms_bans WHERE INET_ATON('%s') BETWEEN `ipstart` AND `ipend` AND `endtime` < %ld LIMIT 1"; - //char banquery[500]; - //time_t current_time = time (NULL); - char servquery[1000] = "SELECT ip, port, name, version, permanent FROM ( SELECT * FROM `ms_servers` WHERE `upnow` = '1' OR `permanent` = '1' ORDER BY `sid` ASC) as ms_servers ORDER BY `sticky` DESC"; - MySQL_Conn(false); - if(!MySQL_CheckBan(ip,0,false,0)) { - msg.id = id; - msg.type = type; - msg.room = 0; - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", servquery); - if(mysql_query(conn, servquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - res = mysql_store_result(conn); - logPrintf(logfile, "Found %d servers...\n", mysql_num_rows(res)); - while ((row = mysql_fetch_row(res)) != NULL) - { - if(strcmp(row[4], "0") == 1) - snprintf(str, sizeof str, "IP\t\t: %s\nPort\t\t: %s\nHostname\t: %s\nVersion\t\t: %s\nPermanent\t: %s\n", row[0], row[1], row[2], row[3], "Yes"); - else - snprintf(str, sizeof str, "IP\t\t: %s\nPort\t\t: %s\nHostname\t: %s\nVersion\t\t: %s\nPermanent\t: %s\n", row[0], row[1], row[2], row[3], "No"); - - msg.length = (INT32)(strlen(str)+1); // send also the '\0' - strcpy(msg.buffer, str); - dbgPrintf(CYAN, "Writing: (%d)\n%s\n", msg.length, msg.buffer); - writecode = server_socket.write(&msg); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d deleted\n", writecode, id); - return; - } - } - mysql_free_result(res); - } - } else { - logPrintf(logfile, "IP %s is banned so do nothing! Let them find out for themselves.\n", ip); - } -} - -void MySQL_RemoveServer(char *ip, char *port, char *name, char *version) { - char escapedName[255]; - char updatequery[5000]; - char updatequeryp1[5000] = "UPDATE `ms_servers` SET upnow = '0' WHERE `ip` = '%s' AND `permanent` = '0'"; - MySQL_Conn(false); - mysql_real_escape_string(conn, escapedName, name, (unsigned long)strlen(name)); - sprintf(updatequery, updatequeryp1, ip); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", updatequery); - if(mysql_query(conn, updatequery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - logPrintf(logfile, "Server: %s:%s || Name: %s || Version: %s removed successfully.\n", ip, port, name, version); - } -} - -/* LIVE FUNCTIONS */ -void LIVE_AuthUser(UINT32 id, char *buffer) -{ - msg_live_auth_t *auth; - char escapedName[255]; - char saltedPassword[62]; - char hashedPassword[34]; - char namequery[1000]; - char namequeryp1[1000] = "SELECT username,userid,salt,password FROM `user` WHERE `username` = '%s' LIMIT 1"; - char userquery[1000]; - char userqueryp1[1000] = "SELECT userid,username,live_authkey,live_publickey FROM `user` WHERE `userid` = '%s' LIMIT 1"; - msg_t msg2; - char ip[32]; - int writecode; - msg2.type = LIVE_INVALID_USER; - - auth = (msg_live_auth_t *)buffer; - - logPrintf(logfile, "Got User %s Pass %s\n", auth->username, auth->password); - // retrieve the true ip of the server - strcpy(ip, server_socket.getClientIP(id)); - MySQL_Conn(false); - msg2.id = id; - logPrintf(logfile, "Check their ban status first... (ID %d)\n",id); - if(MySQL_CheckBan(ip,0,false,0)) - return; - mysql_real_escape_string(conn, escapedName, auth->username, (unsigned long)strlen(auth->username)); - sprintf(namequery, namequeryp1, escapedName); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", namequery); - if(mysql_query(conn, namequery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - res = mysql_store_result(conn); - if(mysql_num_rows(res) < 1) - { - logPrintf(logfile, "Invalid user: %s\n", auth->username); - msg2.type = LIVE_INVALID_USER; - } - else - { - row = mysql_fetch_row(res); - sprintf(saltedPassword, "%s%s", auth->password, row[2]); - logPrintf(logfile, "Pre-hash: %s (Salt is %s)\n", saltedPassword, row[2]); - sprintf(hashedPassword, md5(saltedPassword).c_str()); - logPrintf(logfile, "Got Hashed Password: %s\n", hashedPassword); - if(strcmp(hashedPassword, row[3]) != 0) - { - msg2.type = LIVE_INVALID_USER; - logPrintf(logfile, "INVALID USER!\n"); - } else { - msg2.type = LIVE_SEND_USER; - sprintf(userquery, userqueryp1, row[1]); - mysql_free_result(res); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", userquery); - if(mysql_query(conn, userquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - res = mysql_store_result(conn); - if(mysql_num_rows(res) < 1) - { - logPrintf(errorfile, "User Information Error, invalid USER ID!\n"); - msg2.type = LIVE_INVALID_USER; - } else { - row = mysql_fetch_row(res); - msg_live_user_t *user = (msg_live_user_t *) msg2.buffer; - - user->header[0] = '\0'; // nothing interresting in it (for now) - user->uid = atoi(row[0]); - strcpy(user->username, row[1]); - logPrintf(logfile, "Found user: %s, id %s\n", row[1], row[0]); - logPrintf(logfile, "Sending User %s with ID %d\n", user->username, user->uid); - - msg2.length = sizeof (msg_live_user_t); - } - } - } - } - } - msg2.length = sizeof msg2.buffer; - msg2.room = 0; - logPrintf(logfile, "Sending message?\n"); - writecode = server_socket.write(&msg2); - logPrintf(logfile, "Message sent! :D\n"); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d " - "deleted\n", writecode, id); - return; - } - mysql_free_result(res); -} - -/* -** sendServersInformations() -*/ -static void sendServersInformations(UINT32 id, UINT32 room) -{ - msg_t msg; - int writecode; - char ip[16]; - strcpy(ip, server_socket.getClientIP(id)); - (void)room; - logPrintf(logfile, "Sending servers informations\n"); - msg.id = id; - msg.type = SEND_SERVER_MSG; - msg.room = 0; - MySQL_ListServServers(id, SEND_SERVER_MSG, ip); // Awesome new MySQL Code! - msg.length = 0; - //dbgPrintf(CYAN, "Writing: (%d) %s\n", msg.length, ""); - writecode = server_socket.write(&msg); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d deleted\n", - writecode, id); - } -} - -/* -** sendShortServersInformations() -*/ -static void sendShortServersInformations(UINT32 id, UINT32 room) -{ - msg_t msg; - int writecode; - char ip[16]; - strcpy(ip, server_socket.getClientIP(id)); - - logPrintf(logfile, "Sending short servers informations\n"); - msg.id = id; - msg.type = SEND_SHORT_SERVER_MSG; - MySQL_ListServers(id, SEND_SHORT_SERVER_MSG, ip, room); // New code that's full of win! - logPrintf(logfile, "Packet Room: %d\n", room); - msg.length = 0; - writecode = server_socket.write(&msg); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d deleted\n", - writecode, id); - } -} - -/* -** sendRoomInformations() -*/ -static void sendRoomInformations(UINT32 id, UINT32 room, bool type) -{ - msg_t msg; - int writecode; - char ip[16]; - strcpy(ip, server_socket.getClientIP(id)); - (void)room; - logPrintf(logfile, "Sending room information\n"); - msg.id = id; - msg.type = SEND_ROOMS_MSG; - msg.room = 0; - MySQL_ListRooms(id, SEND_ROOMS_MSG, ip, type); // New code that's full of win! - msg.length = 0; - writecode = server_socket.write(&msg); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d deleted\n", - writecode, id); - } -} - -/* -** sendVersionInformations() -*/ -static void sendVersionInformations(UINT32 id, UINT32 modid, char *modversion) -{ - msg_t msg; - int writecode; - char ip[16]; - strcpy(ip, server_socket.getClientIP(id)); - - logPrintf(logfile, "Sending version information\n"); - msg.id = id; - msg.type = SEND_VERSION_MSG; - msg.room = 0; - MySQL_CheckVersion(id, SEND_VERSION_MSG, ip, modid, modversion); // New code that's full of win! - msg.length = sizeof msg.buffer; - writecode = server_socket.write(&msg); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d deleted\n", - writecode, id); - } -} - -/* -** addServer() -*/ -static void addServer(int id, char *buffer, bool firstadd) -{ - msg_server_t *info; - char oldversion = 0; - - //TODO: Be sure there is no flood from a given IP: - // If a host need more than 2 servers, then it should be registrated - // manually - - info = (msg_server_t *)buffer; - - // I want to be sure the informations are correct, of course! - info->port[sizeof (info->port)-1] = '\0'; - info->name[sizeof (info->name)-1] = '\0'; - info->version[sizeof (info->version)-1] = '\0'; - // retrieve the true ip of the server - strcpy(info->ip, server_socket.getClientIP(id)); - //strcpy(info->port, server_socket.getClientPort(id)); - - if (info->version[0] == '1' && - info->version[1] == '.' && - info->version[2] == '0' && - info->version[3] == '9' && - info->version[4] == '.') - { - if ((info->version[5] == '2') || (info->version[5] == '3')) - { - oldversion = 1; - } - } - - if (info->version[0] == '1' && - info->version[1] == '.' && - info->version[2] == '6' && - info->version[3] == '9' && - info->version[4] == '.' && - info->version[5] == '6') - { - oldversion = 1; - } - - if (!oldversion) - { - MySQL_AddServer(info->ip, info->port, info->name, info->version, info->room, firstadd, info->key); - } - else - { - logPrintf(logfile, "Not adding the temporary server: %s %s %s %s\n", info->ip, info->port, info->name, info->version); - } -} - -/* -** removeServer() -*/ -static void removeServer(int id, char *buffer) -{ - msg_server_t *info; - - info = (msg_server_t *)buffer; - - // I want to be sure the informations are correct, of course! - info->port[sizeof (info->port)-1] = '\0'; - info->name[sizeof (info->name)-1] = '\0'; - info->version[sizeof (info->version)-1] = '\0'; - - // retrieve the true ip of the server - strcpy(info->ip, server_socket.getClientIP(id)); - - logPrintf(logfile, "Removing the temporary server: %s %s %s %s\n", info->ip, info->port, info->name, info->version); - MySQL_RemoveServer(info->ip, info->port, info->name, info->version); // New and win. -} - -/* -** analyseUDP() -*/ -static int analyseUDP(size_t size, const char *buffer) -{ - // this would be the part of reading the PT_SERVERINFO packet, - // but i'm not about to backport that sloppy code - (void)size; - (void)buffer; - return INVALID_MSG; -} - -/* -** UDPMessage() -*/ -static int UDPMessage(size_t size, const char *buffer) -{ - if (size == 4) - { - return 0; - } - else if (size == sizeof(ms_holepunch_packet_t)) - { - return 0; - } - else if (size > 58) - { - dbgPrintf(LIGHTGREEN, "Got a UDP %d byte long message\n", size); - return analyseUDP(size, buffer); - } - else - return INVALID_MSG; -} - -/* -** analyseMessage() -*/ -static int analyseMessage(msg_t *msg) -{ - switch (msg->type) - { - case UDP_RECV_MSG: - return UDPMessage(msg->length, msg->buffer); - case ACCEPT_MSG: - break; - case ADD_SERVER_MSG: - addServer(msg->id, msg->buffer, true); - break; - case PING_SERVER_MSG: - addServer(msg->id, msg->buffer, false); - break; - case REMOVE_SERVER_MSG: - removeServer(msg->id, msg->buffer); - break; - case GET_SERVER_MSG: - sendServersInformations(msg->id, msg->room); - break; - case GET_SHORT_SERVER_MSG: - sendShortServersInformations(msg->id, msg->room); - break; - case GET_ROOMS_MSG: - sendRoomInformations(msg->id, msg->room, 0); - break; - case GET_ROOMS_HOST_MSG: - sendRoomInformations(msg->id, msg->room, 1); - break; - case GET_VERSION_MSG: - sendVersionInformations(msg->id, msg->room, msg->buffer); - break; - case LIVE_AUTH_USER: - LIVE_AuthUser(msg->id, msg->buffer); - break; - default: - return INVALID_MSG; - } - return 0; -} - -/* -** main() -*/ -int main(int argc, char *argv[]) -{ - msg_t msg; -#ifdef __unix__ - pid_t pid; - char pidstr[12]; -#endif - - if (argc <= 1) - { - fprintf(stderr, "usage: %s port\n", argv[0]); - exit(1); - } - - if (server_socket.listen(argv[1]) < 0) - { - fprintf(stderr, "Error while initializing the server\n"); - exit(2); - } - - logfile = openFile("server.log"); - errorfile = openFile("error.log"); - mysqlfile = openFile("mysql.log"); - sockfile = openFile("sockets.log"); - MySQL_Conn(false); -#if !defined (DEBUG) && defined (__unix__) - pid = fork(); - switch (pid) - { - case 0: break; // child - case -1: printf("Error while launching the server in background\n"); return -1; - default: - pidfile = fopen("msd.pid", "w+"); - sprintf(pidstr, "%d", pid); - fputs(pidstr, pidfile); - fclose(pidfile); - return 0; // parent: keep child in background - } -#endif - srand((unsigned)time(NULL)); // Alam: GUIDs - for (;;) - { - memset(&msg, 0, sizeof (msg)); // remove previous message - if (!server_socket.read(&msg)) - { - // valid message: header message seems ok - analyseMessage(&msg); - //servers_list.show(); // for debug purpose - } - } - -#ifndef _MSC_VER - /* NOTREACHED */ - return 0; -#endif -} diff --git a/tools/masterserver/srvlist.cpp b/tools/masterserver/srvlist.cpp deleted file mode 100644 index c9a6feea9..000000000 --- a/tools/masterserver/srvlist.cpp +++ /dev/null @@ -1,405 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// 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 2 -// 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. -// -//----------------------------------------------------------------------------- - -#ifdef __GNUC__ -#include -#endif -#include -#include "common.h" -#include "srvlist.h" - -//============================================================================= - -/* -** -*/ -CList::CList() -{ - list = NULL; - current = NULL; -} - -/* -** -*/ -CList::~CList() -{ - CItem *p; - - while (list) - { - p = list; - list = list->next; - delete(p); - } -} - -/* -** -*/ -int CList::insert(CItem *item) -{ - item->next = list; - list = item; - return 0; -} - -/* -** -*/ -int CList::remove(CItem *item) -{ - CItem *position, *q; - - q = NULL; - position = list; - - while (position && (position != item)) - { - q = position; - position = position->next; - } - if (position) - { - if (q) - q->next = position->next; - else - list = position->next; - delete position; - - return 1; - } - - return 0; -} - -/* -** -*/ -CItem *CList::getFirst() -{ - current = list; - return current; -} - -/* -** -*/ -CItem *CList::getNext() -{ - if (current) - current = current->next; - return current; -} - -/* -** -*/ -void CList::show() -{ - CItem *p; - - p = list; - while (p) - { - p->print(); - p = p->next; - } -} - -//============================================================================= - -/* -** -*/ -CItem::CItem() -{ - next = NULL; -} - -//============================================================================= - -/* -** -*/ -CInetAddr::CInetAddr(const char *ip, const char *port) -{ - strcpy(this->ip, ip); - strcpy(this->port, port); - PortNotChanged = true; -} - -/* -** -*/ -const char *CInetAddr::getIP() -{ - return ip; -} - -/* -** -*/ -const char *CInetAddr::getPort() -{ - return port; -} - -/* -** -*/ -bool CInetAddr::setPort(const char *port) -{ - if (PortNotChanged) - { - strcpy(this->port, port); - PortNotChanged = false; - } - return !PortNotChanged; -} - -//============================================================================= - -/* -** -*/ -CPlayerItem::CPlayerItem(const char *ip, const char *port, - const char *nickname) : CInetAddr(ip, port) -{ - strcpy(this->nickname, nickname); -} - -/* -** -*/ -void CPlayerItem::print() -{ - dbgPrintf(GREEN, "\tIP\t\t: %s\n\tPort\t\t: %s\n\tNickname\t: %s\n", - ip, port, nickname); -} - -/* -** -*/ -char *CPlayerItem::getString() -{ - static char tmpbuf[1024]; - - snprintf(tmpbuf, sizeof tmpbuf, - "\tIP\t\t: %s\n\tPort\t\t: %s\n\tNickname\t: %s\n", - ip, port, nickname); - return tmpbuf; -} - -//============================================================================= - -/* -** -*/ -CServerItem::CServerItem(const char *ip, const char *port, const char *hostname, const char *version, ServerType type) : CInetAddr(ip, port) -{ - time_t timenow = time(NULL); - const tm *timeGMT = gmtime(&timenow); - // check name of server here - strcpy(this->hostname, hostname); - strcpy(this->version, version); - this->type = type; - strftime(reg_time, REG_TIME_SIZE+1, "%Y-%m-%dT%H:%MZ",timeGMT); - { - int i; - memset(guid,'\0',GUID_SIZE); - strcpy(&guid[0], ip); - strcpy(&guid[15], port); // GenUID - for (i = 0; i <= GUID_SIZE-1; i++) - { - if (guid[i] == '\0' || guid[i] == '.') - guid[i] = '0' + (rand()/(RAND_MAX/15)); - if (guid[i] > '9') - guid[i] += 'A'-'9'; - } - guid[GUID_SIZE] = '\0'; - } - - HeartBeat = time(NULL); -} - -/* -** -*/ -void CServerItem::print() -{ - dbgPrintf(GREEN, "IP\t\t: %s\nPort\t\t: %s\nHostname\t: %s\nVersion\t: %s\nPermanent\t: %s\n", - ip, port, hostname, version, (type == ST_PERMANENT) ? "Yes" : "No"); -} - -/* -** -*/ -const char *CServerItem::getString() -{ - static char tmpbuf[1024]; - - snprintf(tmpbuf, sizeof tmpbuf, - "IP\t\t: %s\nPort\t\t: %s\nHostname\t: %s\nVersion\t\t: %s\nPermanent\t: %s\n", - ip, port, hostname, version, (type==ST_PERMANENT) ? "Yes" : "No"); - return tmpbuf; -} - -/* -** -*/ -const char *CServerItem::getName() -{ - return hostname; -} - -/* -** -*/ -const char *CServerItem::getVersion() -{ - return version; -} - -/* -** -*/ -const char *CServerItem::getGuid() -{ - return guid; -} - -/* -** -*/ -const char *CServerItem::getRegtime() -{ - return reg_time; -} - -/* -** -*/ -//============================================================================= - -/* -** -*/ -void CServerList::insertPlayer(CServerItem *server, CPlayerItem *player) -{ - server->players_list.insert(player); -} - -/* -** -*/ -void CServerList::removePlayer(CServerItem *server, CPlayerItem *player) -{ - server->players_list.remove(player); -} - -/* -** -*/ -int CServerList::insert(CServerItem *server) -{ - CList::insert((CItem *)server); - return 0; -} - -/* -** -*/ -int CServerList::insert(const char *ip, const char *port, - const char *hostname, const char *version, ServerType type) -{ - CServerItem *server; - - server = new CServerItem(ip, port, hostname, version, type); - CList::insert(server); - return 0; -} - -/* -** -*/ -int CServerList::remove(CServerItem *server) -{ - return CList::remove((CItem *)server); -} - -/* -** -*/ -int CServerList::remove(const char *ip, const char *port, - const char *hostname, const char *version, ServerType type) -{ - // TODO - CServerItem *position, *q; - bool match; - - (void)hostname; - (void)port; - - match = false; - position = (CServerItem *)list; - q = NULL; - - while (position && !match) - { - if (strcmp(position->ip, ip) == 0 - && strcmp(position->version, version) == 0 - && strcmp(position->port, port) == 0 - && position->type == type) - { - match = true; - } - else - { - q = position; - position = (CServerItem *)position->next; - } - } - if (position && match) - { - if (q) - q->next = position->next; - else - list = position->next; - delete position; - - return 1; - } - - return 0; -} - -/* -** -*/ -void CServerList::show() -{ - CServerItem *p; - - p = (CServerItem *)list; - while (p) - { - p->print(); - p->players_list.show(); - p = (CServerItem *)p->next; - } -} diff --git a/tools/masterserver/srvlist.h b/tools/masterserver/srvlist.h deleted file mode 100644 index aa582ff8b..000000000 --- a/tools/masterserver/srvlist.h +++ /dev/null @@ -1,136 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// 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 2 -// 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. -// -//----------------------------------------------------------------------------- - -#ifndef SRVLIST_H -#define SRVLIST_H - -#include - -enum ServerType -{ - ST_PERMANENT = 0, - ST_TEMPORARY, -}; - -//============================================================================= - -class CItem -{ - friend class CList; -protected: - CItem *next; -public: - CItem(); - virtual ~CItem() {}; // destructor must exist and be virtual - virtual void print() = 0; -}; - -//============================================================================= - -class CList -{ -protected: - CItem *list; - CItem *current; // the current item we are pointing on (for getfirst/getnext) -public: - CList(); - virtual ~CList(); - int insert(CItem *); - int remove(CItem *); - CItem *getFirst(); - CItem *getNext(); - void show(); -}; - -//============================================================================= - -class CInetAddr -{ -protected: - char ip[16]; - char port[8]; - bool PortNotChanged; -public: - CInetAddr(const char *ip, const char *port); - const char *getIP(); - bool setPort(const char *port); - const char *getPort(); -}; - -//============================================================================= - -class CPlayerItem : public CItem, public CInetAddr -{ -friend class CPlayerList; -private: - char nickname[32]; -public: - CPlayerItem(const char *ip, const char *port, const char *nickname); - void print(); - char *getString(); -}; - -//============================================================================= - -class CPlayerList : public CList -{ -}; - -//============================================================================= - -#define REG_TIME_SIZE 24 //1970-00-00T00:00:00.0+00:00 -#define GUID_SIZE 24-1 // format is 12700000000105000 - -class CServerItem : public CItem, public CInetAddr -{ - friend class CServerList; - -private: - char hostname[32]; - char version[8]; // format is: x.yy.z (like 1.30.2 or 1.31) - CPlayerList players_list; - char reg_time[REG_TIME_SIZE]; - char guid[GUID_SIZE+1]; - -public: - ServerType type; - time_t HeartBeat; - - CServerItem(const char *ip, const char *port, const char *hostname, const char *version, ServerType type); - void print(); - const char *getString(); - const char *getName(); - const char *getVersion(); - const char *getRegtime(); - const char *getGuid(); -}; - -//============================================================================= - -class CServerList : public CList -{ -public: - void insertPlayer(CServerItem *server, CPlayerItem *player); - void removePlayer(CServerItem *server, CPlayerItem *player); - int insert(const char *ip, const char *port, const char *hostname, const char *version, ServerType type); - int insert(CServerItem *server); - int remove(const char *ip, const char *port, const char *hostname, const char *version, ServerType type); - int remove(CServerItem *server); - void show(); -}; - -#endif diff --git a/tools/masterserver/stats.cpp b/tools/masterserver/stats.cpp deleted file mode 100644 index 741d82699..000000000 --- a/tools/masterserver/stats.cpp +++ /dev/null @@ -1,147 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// 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 2 -// 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. -// -//----------------------------------------------------------------------------- - -#ifdef __GNUC__ -#include -#endif -#include // strcat(),... -#include "common.h" -#include "ipcs.h" -#include "stats.h" - -//============================================================================= - -/* -** CServerStats() -*/ -CServerStats::CServerStats() -{ - uptime = time(NULL); - num_connections = 0; - num_http_con = 0; - num_servers = 0; - snprintf(motd, sizeof motd, "%s%s", "Welcome to the SRB2 Master Server!
", SERVERMOTDTEXT); - num_add = 0; - num_removal = 0; - num_retrieval = 0; - num_autoremoval = 0; - num_badconnection = 0; - for (int i = 0; i < NUMLASTSERVERS; i++) - { - strcpy(last_server[i].ip, "0.0.0.0"); - strcpy(last_server[i].name, "Non-Existing SRB2 server"); - strcpy(last_server[i].version, "0.0.0"); - } - snprintf(version, sizeof version, "%s %s", __DATE__, __TIME__); -} - -/* -** ~CServerStats() -*/ -CServerStats::~CServerStats() -{ -} - -/* -** getUptime() -*/ -const char *CServerStats::getUptime() -{ - char *res = ctime(&uptime); - res[strlen(res)-1] = '\0'; // remove the '\n' at the end - return res; -} - -/* -** getHours() -*/ -int CServerStats::getHours() -{ - return (int)(((time(NULL) - uptime)/(60*60))%24); -} - -/* -** getDays() -*/ -int CServerStats::getDays() -{ - return (int)((time(NULL) - uptime)/(60*60*24)); -} - -/* -** getMotd() -*/ -const char *CServerStats::getMotd() -{ - return motd; -} - -/* -** getLastServers() -*/ -const char *CServerStats::getLastServers() -{ - static char res[170*NUMLASTSERVERS]; - - tzset(); - res[0] = '\0'; - for (int i = 0; i < NUMLASTSERVERS; i++) - { - char str[170]; - char *ct; - - ct = ctime(&last_time[i]); - ct[strlen(ct)-1] = '\0'; // replace \n with a \0 - snprintf(str, sizeof str, - "Address: %15s Name: %-31s v%-7s (%s %s)\n000043210000", - last_server[i].ip, last_server[i].name, last_server[i].version, ct, tzname[0]); - strcat(res, str); - } - - return res; -} - -/* -** getVersion() -*/ -const char *CServerStats::getVersion() -{ - return version; -} - -/* -** putMotd() -*/ -void CServerStats::putMotd(char *motd) -{ - strcpy(this->motd, motd); -} - -/* -** putLastServer(): -*/ -void CServerStats::putLastServer(msg_server_t *server) -{ - for (int i = NUMLASTSERVERS-1; i > 0; i--) - { - memcpy(&last_server[i], &last_server[i-1], - sizeof (msg_server_t)); - last_time[i] = last_time[i-1]; - } - memcpy(&last_server[0], server, sizeof (msg_server_t)); - last_time[0] = time(NULL); -} diff --git a/tools/masterserver/stats.h b/tools/masterserver/stats.h deleted file mode 100644 index 4494a76f9..000000000 --- a/tools/masterserver/stats.h +++ /dev/null @@ -1,68 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// 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 2 -// 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. -// -//----------------------------------------------------------------------------- - -#ifndef _STATS_H_ -#define _STATS_H_ -#ifndef _IPCS_H_ -#error "You forget to include ipcs.h" -#endif -#include - -#define NUMLASTSERVERS 6 -#define SERVERMOTDTEXT "No Clans, advertising websites, Chat, Hangout, Hacked, or Role Playing Servers Allowed" - - -// ================================ DEFINITIONS =============================== - -class CServerStats -{ - time_t uptime; // master server uptime - char motd[2048]; // increase that if not enough - msg_server_t last_server[NUMLASTSERVERS]; // keep last 6 named registered servers - time_t last_time[NUMLASTSERVERS]; // keep date/time of registration of those servers - char version[32]; // master server version - -public: - int num_connections; - int num_http_con; - int num_text_con; - int num_RSS92_con; - int num_RSS10_con; - int num_servers; - int num_add; - int num_removal; - int num_retrieval; - int num_autoremoval; - int num_badconnection; - - CServerStats(); - ~CServerStats(); - const char *getUptime(); - int getHours(); - int getDays(); - const char *getMotd(); - const char *getLastServers(); - const char *getVersion(); - void putMotd(char *); - void putLastServer(msg_server_t *); -}; - -// ================================== PROTOS ================================== - -// ================================== EXTERNS ================================= - -#endif diff --git a/tools/masterserver/structure.sql b/tools/masterserver/structure.sql deleted file mode 100644 index 3cc2cb15b..000000000 --- a/tools/masterserver/structure.sql +++ /dev/null @@ -1,117 +0,0 @@ -SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; -SET AUTOCOMMIT = 0; -START TRANSACTION; -SET time_zone = "+00:00"; - - -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; -/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; -/*!40101 SET NAMES utf8mb4 */; - --- --- Database: `srb2ms` --- - -CREATE DATABASE IF NOT EXISTS `srb2ms` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; -USE `srb2ms`; - - --- -------------------------------------------------------- - --- --- Table structure for table `ms_bans` --- - -CREATE TABLE `ms_bans` ( - `bid` int(11) DEFAULT NULL, - `ipstart` int(11) DEFAULT NULL, - `ipend` int(11) DEFAULT NULL, - `full_endtime` int(11) DEFAULT NULL, - `permanent` tinyint(1) DEFAULT NULL, - `hostonly` tinyint(1) DEFAULT NULL, - `reason` text COLLATE utf8mb4_unicode_ci -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- -------------------------------------------------------- - --- --- Table structure for table `ms_rooms` --- - -CREATE TABLE `ms_rooms` ( - `room_id` int(11) NOT NULL, - `title` text COLLATE utf8mb4_unicode_ci NOT NULL, - `motd` text COLLATE utf8mb4_unicode_ci NOT NULL, - `visible` tinyint(1) NOT NULL, - `order` int(11) NOT NULL, - `private` tinyint(1) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Dumping data for table `ms_rooms` --- - -INSERT INTO `ms_rooms` (`room_id`, `title`, `motd`, `visible`, `order`, `private`) VALUES -(10, 'Example', 'Example Room', 1, 0, 0), -(0, 'All', 'View all of the servers currently being hosted.', 1, 1, 1); - --- -------------------------------------------------------- - --- --- Table structure for table `ms_servers` --- - -CREATE TABLE `ms_servers` ( - `sid` int(11) NOT NULL, - `name` text COLLATE utf8mb4_unicode_ci NOT NULL, - `ip` text COLLATE utf8mb4_unicode_ci NOT NULL, - `port` int(11) NOT NULL, - `version` text COLLATE utf8mb4_unicode_ci NOT NULL, - `timestamp` int(11) NOT NULL, - `room` int(11) NOT NULL, - `key` text COLLATE utf8mb4_unicode_ci NOT NULL, - `room_override` int(11) NOT NULL, - `upnow` tinyint(1) NOT NULL, - `permanent` tinyint(1) NOT NULL, - `delisted` tinyint(1) NOT NULL, - `sticky` int(11) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- -------------------------------------------------------- - --- --- Table structure for table `ms_versions` --- - -CREATE TABLE `ms_versions` ( - `mod_id` int(11) NOT NULL, - `mod_version` int(11) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Dumping data for table `ms_versions` --- - -INSERT INTO `ms_versions` (`mod_id`, `mod_version`) VALUES -(12, 25); - --- -------------------------------------------------------- - --- --- Table structure for table `user` --- - -CREATE TABLE `user` ( - `userid` int(11) NOT NULL, - `username` text COLLATE utf8mb4_unicode_ci NOT NULL, - `live_authkey` blob NOT NULL, - `live_publickey` blob NOT NULL, - `salt` blob NOT NULL, - `password` blob NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -COMMIT; - -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; -/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; -/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/tools/srb2msns/elements/srb2ms.RDF b/tools/srb2msns/elements/srb2ms.RDF deleted file mode 100644 index 46b3c81f0..000000000 --- a/tools/srb2msns/elements/srb2ms.RDF +++ /dev/null @@ -1,36 +0,0 @@ - - - - - -]> - - -The SRB2MS Element Set namespace providing access -to its content by means of an RDF Schema -Logan Arias -The SRB2MS Element Set namespace provides -URIs for the SRB2MS Elements. Entries are declared using RDF Schema language -to support RDF applications. -English - - -Address -The IPv4 address of the server item. - - - - -Port -The Port number of the server item. - - - - -Version -Version number of the server item. - - - - diff --git a/tools/wadconv/Makefile b/tools/wadconv/Makefile deleted file mode 100644 index d11fbf6ce..000000000 --- a/tools/wadconv/Makefile +++ /dev/null @@ -1,140 +0,0 @@ -#!/usr/bin/env make -f - -## wadconv: SRB2 WAD Converter. -## Copyright (C) 2011 by Callum Dickinson. -# -## 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 2 -## 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. - -# Program name. -PRONAME = wadconv -# Program version. -PROVER = 1.0.0 - -# Program default options. -CPPFLAGS += -DPRONAME="$(PRONAME)" -DPROVER="$(PROVER)" - -# Source files and directory. -SRC = wadconv.c - -# Required libraries. -LIB = -lwad - -# -## Variables that shouldn't be edited unless -## you know what you are doing start here. -# - -# Makefile pretty text output variables. -PRCC = CC -PRINSTALL=INSTALL -PRCLEAN = CLEAN - -# Library name prefix. -LIBPFX = lib - -# Library installation directory. -PREFIX ?= /usr/local -LIBDIR := $(PREFIX)/lib -INCLUDE := $(PREFIX)/include - -# Variables created during compilation. -OBJ = $(SRC:.c=.o) -DEP = $(PRONAME).d -ifdef MINGW -BIN = $(PRONAME).exe -else -BIN = $(PRONAME) -endif - -# Compilation programs. -ECHO := echo -RM := rm -rf -FIND := find -GREP := grep -INSTALLX:= install -m 755 -FOR := for -SED := sed -CC := $(CROSS_COMPILE)$(CC) - -# Shell programs. -SHECHO := $(ECHO) -SHFIND := $(FIND) -SHGREP := $(GREP) -SHINSTALL:= $(INSTALL) -SHSED := $(SED) -SHCC := $(CC) - -# Quiet compiling programs during pretty text output. -NULL := /dev/null 2>&1 -ECHO := @$(ECHO) -ifndef V -RM := @$(RM) -LDCONFIG:= @$(LDCONFIG) -FIND := @$(FIND) -GREP := @$(GREP) -INSTALL := @$(INSTALL) -MKDIR := @$(MKDIR) -FOR := @$(FOR) -SED := @$(SED) -CC := @$(CC) -endif - -# Compiler default flags. -ifdef DEBUG -CFLAGS += -g -O0 -Wall -else -CFLAGS += -O3 -endif - -# Linker flags. -#LDFLAGS += - -# -## Makefile targets. -# - -all: $(DEP) $(BIN) - -$(DEP): $(SRC) -ifndef V - $(ECHO) " $(PRCC)$@" -endif - -$(RM) $@ - $(FOR) f in $(SRC); do \ - $(SHCC) $(CPPFLAGS) $(CFLAGS) -MM $$f >> $@; \ - done --include $@ - -%.o: %.c -ifndef V - $(ECHO) " $(PRCC)$@" -endif - $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ - -$(BIN): $(OBJ) -ifndef V - $(ECHO) " $(PRCC)$@" -endif - $(CC) $(LDFLAGS) -o $@ $(OBJ) $(LIB) - -install: all -ifndef V - $(SHECHO) " $(PRINSTALL)$(BIN)" -endif - $(INSTALLX) $(BIN) $(INSTALLDIR) - -clean: -ifndef V - $(ECHO) " $(PRCLEAN)$(BIN) $(OBJ) $(DEP)" -endif - -$(RM) $(BIN) $(OBJ) $(DEP) - -.PHONY : all install clean diff --git a/tools/wadconv/wadconv.c b/tools/wadconv/wadconv.c deleted file mode 100644 index 4e9565118..000000000 --- a/tools/wadconv/wadconv.c +++ /dev/null @@ -1,282 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// SRB2 WAD Converter -// -// 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 2 -// 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. -//----------------------------------------------------------------------------- -/// \file wadconv.c -/// \brief Converts wads made for version 2.0 to 2.1. - -#include -#include -#include -#include -#include "wad.h" - -// -// Texture definition. -// Each texture is composed of one or more patches, -// with patches being lumps stored in the WAD. -// The lumps are referenced by number, and patched -// into the rectangular texture space using origin -// and possibly other attributes. -// -typedef struct -{ - wad_int16_t originx, originy; - wad_int16_t patch, stepdir, colormap; -} mappatch_t; - -// -// Texture definition. -// An SRB2 wall texture is a list of patches -// which are to be combined in a predefined order. -// -typedef struct -{ - char name[8]; - wad_int32_t masked; - wad_int16_t width; - wad_int16_t height; - wad_int32_t columndirectory; // FIXTHIS: OBSOLETE - wad_int16_t patchcount; - mappatch_t patches[1]; -} maptexture_t; - -// A single patch from a texture definition, -// basically a rectangular area within -// the texture rectangle. -typedef struct -{ - // Block origin (always UL), which has already accounted for the internal origin of the patch. - wad_uint16_t originx, originy; - lump_t *patch; -} texpatch_t; - -// A maptexturedef_t describes a rectangular texture, -// which is composed of one or more mappatch_t structures -// that arrange graphic patches. -typedef struct -{ - // Keep name for switch changing, etc. - char name[8]; - wad_int16_t width, height; - - // All the patches[patchcount] are drawn back to front into the cached texture. - wad_uint16_t patchcount; - texpatch_t patches[1]; -} texture_t; - -static void ConvertTextures(wad_t *wad) -{ - wad_uint32_t i, j; - lump_t *l; - // PNAMES lump. - char pname[9]; - char *pnamesdata; - lump_t *pnames, **patchlookup; - wad_uint32_t numpatches; - // TEXTURE lump. - lump_t *texturex = NULL; - texture_t **textures; - texpatch_t *patch; - maptexture_t *mtexture; - mappatch_t *mpatch; - wad_uint32_t *directory, *maptex, numtextures, offset; - size_t maxoffset; - // TX_START. - lump_t *tx_start; - - // PNAMES. - if (!(pnames = WAD_CacheLumpInWADByName(wad, "PNAMES"))) - { - printf("error caching lump: %s\n", WAD_Error()); - exit(EXIT_FAILURE); - } - - pnamesdata = pnames->data + 4; - - memcpy(&numpatches, pnames->data, sizeof(wad_uint32_t)); - numpatches = WAD_INT32_Endianness(numpatches); - - if (!(patchlookup = malloc(sizeof(*patchlookup) * numpatches))) - { - printf("unable to allocate patchlookup array for wad %s\n", WAD_BaseName(wad->filename)); - exit(EXIT_FAILURE); - } - - pname[8] = '\0'; - for (i = 0; i < numpatches; i++) - { - strncpy(pname, pnamesdata+i*8, 8); - patchlookup[i] = WAD_LumpInWADByName(wad, pname); - } - - WAD_UncacheLump(pnames); - - // TEXTURE. - - for (i = 1; (texturex = WAD_LumpInWADByName(wad, WAD_VA("TEXTURE%i", i))); i++) - if (texturex) - break; - - texturex = WAD_CacheLump(texturex); - maptex = (wad_uint32_t *)texturex->data; - numtextures = WAD_INT32_Endianness(*maptex); - maxoffset = WAD_LumpSize(texturex); - directory = maptex + 1; - textures = malloc(sizeof(*textures) * numtextures); - - for (i = 0; i < numtextures; i++, directory++) - { - memcpy(&offset, directory, sizeof(wad_uint32_t)); - offset = WAD_INT32_Endianness(offset); - - if (offset > maxoffset) - { - printf("bad texture directory for wad %s\n", WAD_BaseName(wad->filename)); - exit(EXIT_FAILURE); - } - - mtexture = (maptexture_t *)((wad_uint8_t *)maptex + offset); - textures[i] = malloc(sizeof(texture_t) + (sizeof(texpatch_t) * (WAD_INT16_Endianness(mtexture->patchcount) - 1))); - - memcpy(textures[i]->name, mtexture->name, sizeof(textures[i]->name)); - textures[i]->width = WAD_INT16_Endianness(mtexture->width); - textures[i]->height = WAD_INT16_Endianness(mtexture->height); - textures[i]->patchcount = WAD_INT16_Endianness(mtexture->patchcount); - - mpatch = &mtexture->patches[0]; - patch = &textures[i]->patches[0]; - - for (j = 0; j < textures[i]->patchcount; j++, mpatch++, patch++) - { - patch->originx = WAD_INT16_Endianness(mpatch->originx); - patch->originy = WAD_INT16_Endianness(mpatch->originy); - patch->patch = patchlookup[WAD_INT16_Endianness(mpatch->patch)]; - if (!patch->patch) - printf("missing patch in texture %s in wad %s\n", textures[i]->name, wad->filename); - } - } - - WAD_UncacheLump(texturex); - - if (!(tx_start = WAD_LumpInWADByName(wad, "TX_START"))) - { - if (WAD_LumpInWADByName(wad, "P_END")) - tx_start = WAD_AddLumpInWADByNum(wad, WAD_LumpNumByName("P_END") + 1, "TX_START", NULL); - else - tx_start = WAD_AddLump(wad, NULL, "TX_START", NULL); - - if (!tx_start) - { - printf("unable to find TX_START in %s\n", wad->filename); - exit(EXIT_FAILURE); - } - } - WAD_RemoveLumpInWADByName(wad, "TX_END"); - - for (i = 0, l = WAD_LumpInWADByNum(wad, WAD_LumpNum(tx_start) + 1); i < numtextures; i++, directory++) - { - if (textures[i]->patchcount == 1 && !strncmp(textures[i]->name, textures[i]->patches[0].patch->name, 8)) - WAD_MoveLump(textures[i]->patches[0].patch, l); - else - { - FILE *socfile; - char *soc, *socname = textures[i]->name; - - for (j = 0; j < textures[i]->patchcount; j++) - { - if (!strncmp(textures[i]->name, textures[i]->patches[j].patch->name, 8)) - { - wad_int32_t k; - char socname1[5]; - - socname = malloc(sizeof(*socname) * 9); - - socname1[4] = '\0'; - strncpy(socname1, textures[i]->name, 4); - - for (k = 0 ;; k++) - if (!WAD_LumpInWADByName(wad, WAD_VA((k > 9) ? "%sSC%i" : "%sSC0%i", socname1, k))) - break; - - sprintf(socname, (k > 9) ? "%sSC%i" : "%sSC0%i", socname1, k); - break; - } - } - - soc = WAD_VA("%s%s", socname, ".lmp"); - - remove(soc); - socfile = fopen(soc, "wb"); - - fprintf(socfile, "TEXTURE %s\n", textures[i]->name); - fprintf(socfile, "WIDTH = %i\n", textures[i]->width); - fprintf(socfile, "HEIGHT = %i\n", textures[i]->height); - fprintf(socfile, "NUMPATCHES = %i\n\n", textures[i]->patchcount); - - for (j = 0; j < textures[i]->patchcount; j++) - { - fprintf(socfile, "PATCH %s\n", textures[i]->patches[j].patch->name); - fprintf(socfile, "X = %i\n", textures[i]->patches[j].originx); - fprintf(socfile, "Y = %i\n\n", textures[i]->patches[j].originy); - } - - fclose(socfile); - - WAD_AddLump(wad, l, socname, soc); - remove(soc); - } - } - WAD_AddLump(wad, l, "TX_END", NULL); - - WAD_RemoveLump(pnames); - WAD_RemoveLump(texturex); -} - -int main(int argc, char **argv) -{ - wad_t *w; - wad_uint32_t i; - - if (argc < 2) - { - puts("Usage: wadconv [filename]"); - puts("Example: wadconv wadfile.wad"); - return EXIT_FAILURE; - } - - // Open the WAD files. - for (i = 1; i < (unsigned)argc; i++) - { - if (!WAD_OpenWAD(argv[i])) - { - printf("Loading WAD failed: %s\n", WAD_Error()); - return EXIT_FAILURE; - } - } - - for (i = 0; i < wad_numwads; i = WAD_WADLoopAdvance(i)) - { - w = WAD_WADByNum(i); - // Convert textures. - printf("Converting textures for wad %s...\n", WAD_BaseName(w->filename)); - ConvertTextures(w); - } - - for (i = 0; i < wad_numwads; i = WAD_WADLoopAdvance(i)) - WAD_SaveCloseWADByNum(i); - - puts("Finished."); - return EXIT_SUCCESS; -} diff --git a/tools/wadzip/err.c b/tools/wadzip/err.c deleted file mode 100644 index 37393bfcb..000000000 --- a/tools/wadzip/err.c +++ /dev/null @@ -1,121 +0,0 @@ -#if defined (__WIN32) || defined (WIN32) -#define NEED_ERR -#define LACK_PROGNAME -#define NEED_ENDIAN_STUBS -#define LACK_SYSTYPES -#endif - -#ifdef NEED_ERR - -/* - * Implementation of the err/errx/verr/verrx/warn/warnx/vwarn/vwarnx - * functions from BSD. - * - * This file is public-domain; anyone may deal in it without restriction. - * - * Written by Graue on January 16, 2006. - */ - -/* -err/warn family of functions cheat sheet: - -Print: - last component of program name - [ if fmt is non-NULL - ": " - the formatted error message - ] - [ if function name does not end in x - ": " - strerror(errno) - ] - newline - -Then if function name has "err" in it, quit with exit code `eval'. - -BSD's -x versions actually print ": " at the end if passed NULL, so I -duplicate that behavior. Passing these functions NULL is kind of useless -though. -*/ - -#include -#include -#include -#include -#include - -#ifdef LACK_PROGNAME -char *__progname = "wadzip"; -#else -extern char *__progname; -#endif - -#define progname __progname - -void vwarn(const char *fmt, va_list args) -{ - fputs(progname, stderr); - if (fmt != NULL) - { - fputs(": ", stderr); - vfprintf(stderr, fmt, args); - } - fputs(": ", stderr); - fputs(strerror(errno), stderr); - putc('\n', stderr); -} - -void vwarnx(const char *fmt, va_list args) -{ - fputs(progname, stderr); - fputs(": ", stderr); - if (fmt != NULL) - vfprintf(stderr, fmt, args); - putc('\n', stderr); -} - -void verr(int eval, const char *fmt, va_list args) -{ - vwarn(fmt, args); - exit(eval); -} - -void verrx(int eval, const char *fmt, va_list args) -{ - vwarnx(fmt, args); - exit(eval); -} - -void warn(const char *fmt, ...) -{ - va_list argptr; - va_start(argptr, fmt); - vwarn(fmt, argptr); - va_end(argptr); -} - -void warnx(const char *fmt, ...) -{ - va_list argptr; - va_start(argptr, fmt); - vwarnx(fmt, argptr); - va_end(argptr); -} - -void err(int eval, const char *fmt, ...) -{ - va_list argptr; - va_start(argptr, fmt); - verr(eval, fmt, argptr); - /* NOTREACHED, so don't worry about va_end() */ -} - -void errx(int eval, const char *fmt, ...) -{ - va_list argptr; - va_start(argptr, fmt); - verrx(eval, fmt, argptr); - /* NOTREACHED, so don't worry about va_end() */ -} - -#endif diff --git a/tools/wadzip/err.h b/tools/wadzip/err.h deleted file mode 100644 index 5b9380379..000000000 --- a/tools/wadzip/err.h +++ /dev/null @@ -1,26 +0,0 @@ -#if defined (__WIN32) || defined (WIN32) -#define NEED_ERR -#endif - -#ifndef NEED_ERR -#include /* system version of this file */ -#else - -#ifndef _ERR_H -#define _ERR_H - -#include - -void err (int eval, const char *fmt, ...); -void errx (int eval, const char *fmt, ...); -void verr (int eval, const char *fmt, va_list args); -void verrx (int eval, const char *fmt, va_list args); - -void warn ( const char *fmt, ...); -void warnx( const char *fmt, ...); -void vwarn ( const char *fmt, va_list args); -void vwarnx( const char *fmt, va_list args); - -#endif - -#endif diff --git a/tools/wadzip/lzf.h b/tools/wadzip/lzf.h deleted file mode 100644 index 8538609ab..000000000 --- a/tools/wadzip/lzf.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2000-2005 Marc Alexander Lehmann - * - * Redistribution and use in source and binary forms, with or without modifica- - * tion, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- - * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- - * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Alternatively, the contents of this file may be used under the terms of - * the GNU General Public License version 2 (the "GPL"), in which case the - * provisions of the GPL are applicable instead of the above. If you wish to - * allow the use of your version of this file only under the terms of the - * GPL and not to allow others to use your version of this file under the - * BSD license, indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by the GPL. If - * you do not delete the provisions above, a recipient may use your version - * of this file under either the BSD or the GPL. - */ - -#ifndef LZF_H -#define LZF_H - -/*********************************************************************** -** -** lzf -- an extremely fast/free compression/decompression-method -** http://liblzf.plan9.de/ -** -** This algorithm is believed to be patent-free. -** -***********************************************************************/ - -#define LZF_VERSION 0x0105 /* 1.5 */ - -/* - * Compress in_len bytes stored at the memory block starting at - * in_data and write the result to out_data, up to a maximum length - * of out_len bytes. - * - * If the output buffer is not large enough or any error occurs - * return 0, otherwise return the number of bytes used (which might - * be considerably larger than in_len, so it makes sense to always - * use out_len == in_len - 1), to ensure _some_ compression, and store - * the data uncompressed otherwise. - * - * lzf_compress might use different algorithms on different systems and - * even diferent runs, thus might result in different compressed strings - * depending on the phase of the moon or similar factors. However, all - * these strings are architecture-independent and will result in the - * original data when decompressed using lzf_decompress. - * - * The buffers must not be overlapping. - * - * If the option LZF_STATE_ARG is enabled, an extra argument must be - * supplied which is not reflected in this header file. Refer to lzfP.h - * and lzf_c.c. - * - */ -unsigned int -lzf_compress (const void *const in_data, unsigned int in_len, - void *out_data, unsigned int out_len); - -/* - * Decompress data compressed with some version of the lzf_compress - * function and stored at location in_data and length in_len. The result - * will be stored at out_data up to a maximum of out_len characters. - * - * If the output buffer is not large enough to hold the decompressed - * data, a 0 is returned and errno is set to E2BIG. Otherwise the number - * of decompressed bytes (i.e. the original length of the data) is - * returned. - * - * If an error in the compressed data is detected, a zero is returned and - * errno is set to EINVAL. - * - * This function is very fast, about as fast as a copying loop. - */ -unsigned int -lzf_decompress (const void *const in_data, unsigned int in_len, - void *out_data, unsigned int out_len); - -#endif - diff --git a/tools/wadzip/lzfP.h b/tools/wadzip/lzfP.h deleted file mode 100644 index 4d5a21e3c..000000000 --- a/tools/wadzip/lzfP.h +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (c) 2000-2005 Marc Alexander Lehmann - * - * Redistribution and use in source and binary forms, with or without modifica- - * tion, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- - * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- - * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Alternatively, the contents of this file may be used under the terms of - * the GNU General Public License version 2 (the "GPL"), in which case the - * provisions of the GPL are applicable instead of the above. If you wish to - * allow the use of your version of this file only under the terms of the - * GPL and not to allow others to use your version of this file under the - * BSD license, indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by the GPL. If - * you do not delete the provisions above, a recipient may use your version - * of this file under either the BSD or the GPL. - */ - -#ifndef LZFP_h -#define LZFP_h - -#define STANDALONE 1 /* at the moment, this is ok. */ - -#ifndef STANDALONE -# include "lzf.h" -#endif - -/* - * Size of hashtable is (1 << HLOG) * sizeof (char *) - * decompression is independent of the hash table size - * the difference between 15 and 14 is very small - * for small blocks (and 14 is usually a bit faster). - * For a low-memory/faster configuration, use HLOG == 13; - * For best compression, use 15 or 16 (or more). - */ -#ifndef HLOG -# define HLOG 15 -#endif - -/* - * Sacrifice very little compression quality in favour of compression speed. - * This gives almost the same compression as the default code, and is - * (very roughly) 15% faster. This is the preferable mode of operation. - */ - -#ifndef VERY_FAST -# define VERY_FAST 1 -#endif - -/* - * Sacrifice some more compression quality in favour of compression speed. - * (roughly 1-2% worse compression for large blocks and - * 9-10% for small, redundant, blocks and >>20% better speed in both cases) - * In short: when in need for speed, enable this for binary data, - * possibly disable this for text data. - */ -#ifndef ULTRA_FAST -# define ULTRA_FAST 0 -#endif - -/* - * Unconditionally aligning does not cost very much, so do it if unsure - */ -#ifndef STRICT_ALIGN -# define STRICT_ALIGN !(defined(__i386) || defined (__amd64)) -#endif - -/* - * Use string functions to copy memory. - * this is usually a loss, even with glibc's optimized memcpy - */ -#ifndef USE_MEMCPY -# define USE_MEMCPY 0 -#endif - -/* - * You may choose to pre-set the hash table (might be faster on some - * modern cpus and large (>>64k) blocks) - */ -#ifndef INIT_HTAB -# define INIT_HTAB 0 -#endif - -/* - * Avoid assigning values to errno variable? for some embedding purposes - * (linux kernel for example), this is neccessary. NOTE: this breaks - * the documentation in lzf.h. - */ -#ifndef AVOID_ERRNO -# define AVOID_ERRNO 0 -#endif - -/* - * Wether to pass the LZF_STATE variable as argument, or allocate it - * on the stack. For small-stack environments, define this to 1. - * NOTE: this breaks the prototype in lzf.h. - */ -#ifndef LZF_STATE_ARG -# define LZF_STATE_ARG 0 -#endif - -/* - * Wether to add extra checks for input validity in lzf_decompress - * and return EINVAL if the input stream has been corrupted. This - * only shields against overflowing the input buffer and will not - * detect most corrupted streams. - * This check is not normally noticable on modern hardware - * (<1% slowdown), but might slow down older cpus considerably. - */ -#ifndef CHECK_INPUT -# define CHECK_INPUT 1 -#endif - -/*****************************************************************************/ -/* nothing should be changed below */ - -typedef unsigned char u8; - -typedef const u8 *LZF_STATE[1 << (HLOG)]; - -#if !STRICT_ALIGN -/* for unaligned accesses we need a 16 bit datatype. */ -# include -# if USHRT_MAX == 65535 - typedef unsigned short u16; -# elif UINT_MAX == 65535 - typedef unsigned int u16; -# else -# undef STRICT_ALIGN -# define STRICT_ALIGN 1 -# endif -#endif - -#if ULTRA_FAST -# if defined(VERY_FAST) -# undef VERY_FAST -# endif -#endif - -#if USE_MEMCPY || INIT_HTAB -# ifdef __cplusplus -# include -# else -# include -# endif -#endif - -#endif - diff --git a/tools/wadzip/lzf_c.c b/tools/wadzip/lzf_c.c deleted file mode 100644 index b9b9ef991..000000000 --- a/tools/wadzip/lzf_c.c +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c) 2000-2005 Marc Alexander Lehmann - * - * Redistribution and use in source and binary forms, with or without modifica- - * tion, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- - * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- - * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Alternatively, the contents of this file may be used under the terms of - * the GNU General Public License version 2 (the "GPL"), in which case the - * provisions of the GPL are applicable instead of the above. If you wish to - * allow the use of your version of this file only under the terms of the - * GPL and not to allow others to use your version of this file under the - * BSD license, indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by the GPL. If - * you do not delete the provisions above, a recipient may use your version - * of this file under either the BSD or the GPL. - */ - -#include "lzfP.h" - -#define HSIZE (1 << (HLOG)) - -/* - * don't play with this unless you benchmark! - * decompression is not dependent on the hash function - * the hashing function might seem strange, just believe me - * it works ;) - */ -#ifndef FRST -# define FRST(p) (((p[0]) << 8) | p[1]) -# define NEXT(v,p) (((v) << 8) | p[2]) -# define IDX(h) ((((h ^ (h << 5)) >> (3*8 - HLOG)) - h*5) & (HSIZE - 1)) -#endif -/* - * IDX works because it is very similar to a multiplicative hash, e.g. - * ((h * 57321 >> (3*8 - HLOG)) & (HSIZE - 1)) - * the latter is also quite fast on newer CPUs, and sligthly better - * - * the next one is also quite good, albeit slow ;) - * (int)(cos(h & 0xffffff) * 1e6) - */ - -#if 0 -/* original lzv-like hash function, much worse and thus slower */ -# define FRST(p) (p[0] << 5) ^ p[1] -# define NEXT(v,p) ((v) << 5) ^ p[2] -# define IDX(h) ((h) & (HSIZE - 1)) -#endif - -#define MAX_LIT (1 << 5) -#define MAX_OFF (1 << 13) -#define MAX_REF ((1 << 8) + (1 << 3)) - -/* - * compressed format - * - * 000LLLLL ; literal - * LLLooooo oooooooo ; backref L - * 111ooooo LLLLLLLL oooooooo ; backref L+7 - * - */ - -unsigned int -lzf_compress (const void *const in_data, unsigned int in_len, - void *out_data, unsigned int out_len -#if LZF_STATE_ARG - , LZF_STATE *htab -#endif - ) -{ -#if !LZF_STATE_ARG - LZF_STATE htab; -#endif - const u8 **hslot; - const u8 *ip = (const u8 *)in_data; - u8 *op = (u8 *)out_data; - const u8 *in_end = ip + in_len; - u8 *out_end = op + out_len; - const u8 *ref; - - unsigned int hval = FRST (ip); - unsigned long off; - int lit = 0; - -#if INIT_HTAB -# if USE_MEMCPY - memset (htab, 0, sizeof (htab)); -# else - for (hslot = htab; hslot < htab + HSIZE; hslot++) - *hslot++ = ip; -# endif -#endif - - for (;;) - { - if (ip < in_end - 2) - { - hval = NEXT (hval, ip); - hslot = htab + IDX (hval); - ref = *hslot; *hslot = ip; - - if (1 -#if INIT_HTAB && !USE_MEMCPY - && ref < ip /* the next test will actually take care of this, but this is faster */ -#endif - && (off = ip - ref - 1) < MAX_OFF - && ip + 4 < in_end - && ref > (u8 *)in_data -#if STRICT_ALIGN - && ref[0] == ip[0] - && ref[1] == ip[1] - && ref[2] == ip[2] -#else - && *(u16 *)ref == *(u16 *)ip - && ref[2] == ip[2] -#endif - ) - { - /* match found at *ref++ */ - unsigned int len = 2; - unsigned int maxlen = in_end - ip - len; - maxlen = maxlen > MAX_REF ? MAX_REF : maxlen; - - if (op + lit + 1 + 3 >= out_end) - return 0; - - do - len++; - while (len < maxlen && ref[len] == ip[len]); - - if (lit) - { - *op++ = lit - 1; - lit = -lit; - do - *op++ = ip[lit]; - while (++lit); - } - - len -= 2; - ip++; - - if (len < 7) - { - *op++ = (off >> 8) + (len << 5); - } - else - { - *op++ = (off >> 8) + ( 7 << 5); - *op++ = len - 7; - } - - *op++ = off; - -#if ULTRA_FAST || VERY_FAST - ip += len; -#if VERY_FAST && !ULTRA_FAST - --ip; -#endif - hval = FRST (ip); - - hval = NEXT (hval, ip); - htab[IDX (hval)] = ip; - ip++; - -#if VERY_FAST && !ULTRA_FAST - hval = NEXT (hval, ip); - htab[IDX (hval)] = ip; - ip++; -#endif -#else - do - { - hval = NEXT (hval, ip); - htab[IDX (hval)] = ip; - ip++; - } - while (len--); -#endif - continue; - } - } - else if (ip == in_end) - break; - - /* one more literal byte we must copy */ - lit++; - ip++; - - if (lit == MAX_LIT) - { - if (op + 1 + MAX_LIT >= out_end) - return 0; - - *op++ = MAX_LIT - 1; -#if USE_MEMCPY - memcpy (op, ip - MAX_LIT, MAX_LIT); - op += MAX_LIT; - lit = 0; -#else - lit = -lit; - do - *op++ = ip[lit]; - while (++lit); -#endif - } - } - - if (lit) - { - if (op + lit + 1 >= out_end) - return 0; - - *op++ = lit - 1; - lit = -lit; - do - *op++ = ip[lit]; - while (++lit); - } - - return op - (u8 *) out_data; -} diff --git a/tools/wadzip/lzf_d.c b/tools/wadzip/lzf_d.c deleted file mode 100644 index 73a1a80b6..000000000 --- a/tools/wadzip/lzf_d.c +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2000-2005 Marc Alexander Lehmann - * - * Redistribution and use in source and binary forms, with or without modifica- - * tion, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- - * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- - * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Alternatively, the contents of this file may be used under the terms of - * the GNU General Public License version 2 (the "GPL"), in which case the - * provisions of the GPL are applicable instead of the above. If you wish to - * allow the use of your version of this file only under the terms of the - * GPL and not to allow others to use your version of this file under the - * BSD license, indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by the GPL. If - * you do not delete the provisions above, a recipient may use your version - * of this file under either the BSD or the GPL. - */ - -#include "lzfP.h" - -#if AVOID_ERRNO -# define SET_ERRNO(n) -#else -# include -# define SET_ERRNO(n) errno = (n) -#endif - -unsigned int -lzf_decompress (const void *const in_data, unsigned int in_len, - void *out_data, unsigned int out_len) -{ - u8 const *ip = (const u8 *)in_data; - u8 *op = (u8 *)out_data; - u8 const *const in_end = ip + in_len; - u8 *const out_end = op + out_len; - - do - { - unsigned int ctrl = *ip++; - - if (ctrl < (1 << 5)) /* literal run */ - { - ctrl++; - - if (op + ctrl > out_end) - { - SET_ERRNO (E2BIG); - return 0; - } - -#if CHECK_INPUT - if (ip + ctrl > in_end) - { - SET_ERRNO (EINVAL); - return 0; - } -#endif - -#if USE_MEMCPY - memcpy (op, ip, ctrl); - op += ctrl; - ip += ctrl; -#else - do - *op++ = *ip++; - while (--ctrl); -#endif - } - else /* back reference */ - { - unsigned int len = ctrl >> 5; - - u8 *ref = op - ((ctrl & 0x1f) << 8) - 1; - -#if CHECK_INPUT - if (ip >= in_end) - { - SET_ERRNO (EINVAL); - return 0; - } -#endif - if (len == 7) - { - len += *ip++; -#if CHECK_INPUT - if (ip >= in_end) - { - SET_ERRNO (EINVAL); - return 0; - } -#endif - } - - ref -= *ip++; - - if (op + len + 2 > out_end) - { - SET_ERRNO (E2BIG); - return 0; - } - - if (ref < (u8 *)out_data) - { - SET_ERRNO (EINVAL); - return 0; - } - - *op++ = *ref++; - *op++ = *ref++; - - do - *op++ = *ref++; - while (--len); - } - } - while (ip < in_end); - - return op - (u8 *)out_data; -} - diff --git a/tools/wadzip/wadzip.c b/tools/wadzip/wadzip.c deleted file mode 100644 index c8dae9b61..000000000 --- a/tools/wadzip/wadzip.c +++ /dev/null @@ -1,311 +0,0 @@ -/* - * Wad compressor/decompressor by Graue - * Written January 23, 2007 - * - * This file is in the public domain; use it without any restrictions. - */ - -#include -#include -#ifndef _MSC_VER -#include -#else -typedef unsigned int uint32_t; -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -#endif -#include -#include -#include "err.h" -#include "lzf.h" -#include "xm.h" - -/* Note: Define WORDS_BIGENDIAN if that is the case on the target CPU. */ - -#define MINCOMPRESS 1024 // Don't bother compressing lumps smaller than this. - -#define SWAP16(n) ((((n)&0xff)<<8) | ((n)>>8)) -#define SWAP32(n) \ -( \ - ((((n)&0xff) <<24) \ - | ((((n)>>8)&0xff)<<16) \ - | ((((n)>>16)&0xff)<<8) \ - | ((n)>>24) \ -) -#ifdef WORDS_BIGENDIAN -#define conv16le SWAP16 -#define conv32le SWAP32 -#else -#define conv16le(n) (n) -#define conv32le(n) (n) -#endif -#define READFUNC(name, type, conv) \ -static type name(FILE *fp) \ -{ \ - type val; \ - if (fread(&val, sizeof val, 1, fp) < 1) \ - { \ - if (ferror(fp)) \ - err(1, "error reading input file"); \ - errx(1, "premature end of input file"); \ - } \ - val = conv(val); \ - return val; \ -} -READFUNC(read32le, uint32_t, conv32le) - -#define WRITEFUNC(name, type, conv) \ -static void name(FILE *fp, type val) \ -{ \ - val = conv(val); \ - if (fwrite(&val, sizeof (type), 1, fp) < 1) \ - err(1, "error writing output file"); \ -} -WRITEFUNC(write32le, uint32_t, conv32le) - -#define ID_IWAD 0x44415749 -#define ID_PWAD 0x44415750 -#define ID_ZWAD 0x4441575a // 'ZWAD' for lzf-compressed wad - -typedef struct -{ - char name[8]; - uint32_t len; - void *data; -} lump_t; - -typedef struct -{ - uint32_t id; - uint32_t numlumps; - lump_t *lumps; -} wad_t; - -extern char *__progname; - -static void usage(void) -{ - fprintf(stderr, "usage: %s [cd] infile outfile\n", __progname); - exit(EXIT_FAILURE); -} - -#define fileoffset_t long -#define myseek fseek -#define mytell ftell - -static void readlumpdata(lump_t *lump, uint32_t csize, int compressed, FILE *fp) -{ - uint8_t *cbuf; - uint8_t *ubuf; - uint32_t usize; - unsigned int retval; - - cbuf = xm(1, csize); - if (fread(cbuf, csize, 1, fp) < 1) - err(1, "cannot read lump from input file"); - - if (!compressed) - { - lump->len = csize; - lump->data = cbuf; - return; - } - - usize = conv32le(*(uint32_t *)cbuf); - if (usize == 0) - { - lump->len = csize - 4; - lump->data = cbuf + 4; // XXX cannot be freed later - return; - } - - ubuf = xm(1, usize); - retval = lzf_decompress(cbuf + 4, csize - 4, ubuf, usize); - if (retval == 0) - { - if (errno == E2BIG) - errx(1, "decompressed data bigger than advertised"); - if (errno == EINVAL) - errx(1, "invalid compressed (lzf) data"); - else - err(1, "unknown error from lzf"); - } - else if (retval < usize) - errx(1, "decompressed data smaller than advertised"); - lump->len = usize; - lump->data = ubuf; - free(cbuf); - return; -} - -static wad_t *readwad(const char *fname) -{ - wad_t *wad; - FILE *fp; - int inputcompressed; - fileoffset_t dirstart; - uint32_t ix; - - fp = fopen(fname, "rb"); - if (fp == NULL) err(1, "%s", fname); - - wad = xm(sizeof *wad, 1); - - // Read wad id. If it is ZWAD, prepare to read compressed lumps. - wad->id = read32le(fp); - inputcompressed = wad->id == ID_ZWAD; - - // Read number of lumps, and prepare space for that many. - wad->numlumps = read32le(fp); - wad->lumps = xm(sizeof wad->lumps[0], wad->numlumps); - - // Read offset to directory. - dirstart = (fileoffset_t)read32le(fp); - - for (ix = 0; ix < wad->numlumps; ix++) - { - fileoffset_t lumpofs; - uint32_t lumpsize; // The compressed size, if it is compressed. - - if (myseek(fp, dirstart + (16*ix), SEEK_SET) == -1) - { - err(1, "cannot seek input file to dir entry %lu", - (unsigned long)ix); - } - lumpofs = (fileoffset_t)read32le(fp); - lumpsize = read32le(fp); - if (fread(wad->lumps[ix].name, 1, 8, fp) < 8) - err(1, "cannot read lump %lu name", (unsigned long)ix); - - // Don't try to seek to zero-length lumps. - // Their offset is meaningless. - if (lumpsize == 0) - { - wad->lumps[ix].len = 0; - continue; - } - - if (myseek(fp, lumpofs, SEEK_SET) == -1) - err(1, "cannot seek to lump %lu", (unsigned long)ix); - readlumpdata(&wad->lumps[ix], lumpsize, inputcompressed, fp); - } - - if (fclose(fp) == EOF) - warn("error closing input file %s", fname); - return wad; -} - -void writewad(const wad_t *wad, const char *fname, int compress) -{ - uint32_t *lumpofs; // Each lump's offset in the file. - uint32_t *disksize; // Each lump's disk size (compressed if applicable). - uint32_t dirstart; - uint32_t ix; - FILE *fp; - - lumpofs = xm(sizeof lumpofs[0], wad->numlumps); - disksize = xm(sizeof disksize[0], wad->numlumps); - - fp = fopen(fname, "wb"); - if (fp == NULL) err(1, "%s", fname); - - // Write header. - write32le(fp, compress ? ID_ZWAD : ID_PWAD); - write32le(fp, wad->numlumps); - write32le(fp, 0); // Directory table comes later. - - for (ix = 0; ix < wad->numlumps; ix++) - { - uint8_t *cbuf; - uint32_t csize; - - lumpofs[ix] = (uint32_t)mytell(fp); - if (!compress) - { - cbuf = wad->lumps[ix].data; - csize = wad->lumps[ix].len; - } - else - { - unsigned int retval; - - csize = wad->lumps[ix].len + 4; - cbuf = xm(1, csize); - if (wad->lumps[ix].len < MINCOMPRESS - || (retval = lzf_compress(wad->lumps[ix].data, - wad->lumps[ix].len, cbuf + 4, - csize - 5)) == 0) - { - // Store uncompressed. - memcpy(cbuf + 4, wad->lumps[ix].data, - wad->lumps[ix].len); - *(uint32_t *)cbuf = 0; - } - else - { - // Compression succeeded. - // Store uncompressed size, and set compressed - // size properly. - *(uint32_t *)cbuf = - conv32le(wad->lumps[ix].len); - csize = retval + 4; - } - } - - if (!csize) - ; // inu: 0 length markers aren't to be written - else if (fwrite(cbuf, csize, 1, fp) < 1) - { - err(1, "cannot write lump %lu to %s", (unsigned long)ix, - fname); - } - - if (compress) - free(cbuf); - disksize[ix] = csize; - } - - dirstart = (uint32_t)mytell(fp); - if (myseek(fp, 8L, SEEK_SET) == -1) - err(1, "cannot reseek %s to write directory start", fname); - write32le(fp, dirstart); - if (myseek(fp, dirstart, SEEK_SET) == -1) - err(1, "cannot reseek %s to write actual directory", fname); - - for (ix = 0; ix < wad->numlumps; ix++) - { - // Write the lump's directory entry. - write32le(fp, lumpofs[ix]); - write32le(fp, disksize[ix]); - if (fwrite(wad->lumps[ix].name, 1, 8, fp) < 8) - { - err(1, "cannot write lump %lu's name", - (unsigned long)ix); - } - } - - if (fclose(fp) == EOF) - warn("error closing output file %s", fname); -} - -int main(int argc, char *argv[]) -{ - const char *infile, *outfile; - wad_t *wad; - int compress; - - if (argc != 4 || strlen(argv[1]) != 1) - usage(); - - /* c to compress, d to decompress */ - if (argv[1][0] == 'c') compress = 1; - else if (argv[1][0] == 'd') compress = 0; - else usage(); - - infile = argv[2]; - outfile = argv[3]; - - wad = readwad(infile); - writewad(wad, outfile, compress); - return 0; -} diff --git a/tools/wadzip/wadzip.dsp b/tools/wadzip/wadzip.dsp deleted file mode 100644 index 85f1f99ad..000000000 --- a/tools/wadzip/wadzip.dsp +++ /dev/null @@ -1,104 +0,0 @@ -# Microsoft Developer Studio Project File - Name="wadzip" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=wadzip - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "wadzip.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "wadzip.mak" CFG="wadzip - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "wadzip - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "wadzip - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "wadzip - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 - -!ELSEIF "$(CFG)" == "wadzip - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept - -!ENDIF - -# Begin Target - -# Name "wadzip - Win32 Release" -# Name "wadzip - Win32 Debug" -# Begin Source File - -SOURCE=.\err.c -# End Source File -# Begin Source File - -SOURCE=.\lzf_c.c -# End Source File -# Begin Source File - -SOURCE=.\lzf_d.c -# End Source File -# Begin Source File - -SOURCE=.\wadzip.c -# End Source File -# Begin Source File - -SOURCE=.\xm.c -# End Source File -# End Target -# End Project diff --git a/tools/wadzip/wadzip.dsw b/tools/wadzip/wadzip.dsw deleted file mode 100644 index c4bd785a2..000000000 --- a/tools/wadzip/wadzip.dsw +++ /dev/null @@ -1,29 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "wadzip"=.\wadzip.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - diff --git a/tools/wadzip/wadzip.txt b/tools/wadzip/wadzip.txt deleted file mode 100644 index 24d05d0f0..000000000 --- a/tools/wadzip/wadzip.txt +++ /dev/null @@ -1,30 +0,0 @@ -Compressed wad format: - -Just like a normal wad, except: - -1. The header id at the very beginning says "ZWAD" -instead of PWAD or IWAD. - -2. The first four bytes of each lump are (little -endian) the uncompressed size. If this is zero, -the lump is not compressed, and you can subtract -four from the size given in the wadfile directory. - -3. Unless those first four bytes give a value of -0, the lump is compressed with liblzf after that. - - - -To compile this program, just compiling all its -source files should work, that is: - gcc *.c -o wadzip - -[On a big-endian CPU, add "-DWORDS_BIGENDIAN" to -that command line.] - -Visual C++ should also work, as well as gcc. - -Compress a wad: - wadzip c original.wad compressed.wad -Decompress a wad (restoring the original): - wadzip d compressed.wad original.wad diff --git a/tools/wadzip/xm.c b/tools/wadzip/xm.c deleted file mode 100644 index f388bab9e..000000000 --- a/tools/wadzip/xm.c +++ /dev/null @@ -1,76 +0,0 @@ -/* Fail-proof memory allocation by Graue ; public domain */ - -#include -#include -#include "err.h" - -/* MinGW (for example) appears to lack SIZE_T_MAX. */ -#ifndef SIZE_T_MAX -#define SIZE_T_MAX ULONG_MAX -#endif - -/* - * The usual xmalloc and xrealloc type routines, for allocating memory - * and bombing out if it fails. - * - * xm and xr here take two values: size and nmemb, like fread/fwrite. - * The idea is to be able to check for overflow, to prevent some weird - * crashes and security problems that can arise if you multiply size - * and nmemb and they overflow. - */ - -/* FIXME: use %zu (size_t) in these format arguments if library is C99 */ - -/* - * Multiply size and number of elements, bombing out if overflow would - * occur. - - * Note: In the case where size*nmemb is exactly equal to SIZE_T_MAX, - * this function considers that an overflow, even though it isn't - * really. But it's not likely the program will get that much memory, - * anyway. - */ -static size_t sizmul(size_t size, size_t nmemb) -{ - if (SIZE_T_MAX / size <= nmemb) - { - errx(1, "allocating %lu objects of size %lu " - "would overflow", (unsigned long)nmemb, - (unsigned long)size); - } - return size * nmemb; /* won't overflow */ -} - -static void nomem(size_t size, size_t nmemb) -{ - err(1, "cannot allocate %lu objects of size %lu " - "(total %lu bytes)", (unsigned long)nmemb, - (unsigned long)size, (unsigned long)(nmemb*size)); -} - -void *xm(size_t size, size_t nmemb) -{ - const size_t bytes = sizmul(size, nmemb); - void *p; - - p = malloc(bytes); - if (p == NULL) nomem(size, nmemb); - return p; -} - -void *xr(void *p, size_t size, size_t nmemb) -{ - const size_t bytes = sizmul(size, nmemb); - - p = realloc(p, bytes); - if (p == NULL) nomem(size, nmemb); - return p; -} - -/* expand array */ -void *xpnd(void *p, int nit, int *sit, size_t sz) -{ - if (nit < *sit) return p; - else if (*sit > 0) return xr(p, sz, (*sit *= 2)); - else return xm(sz, (*sit = 10)); -} diff --git a/tools/wadzip/xm.h b/tools/wadzip/xm.h deleted file mode 100644 index d57f8479b..000000000 --- a/tools/wadzip/xm.h +++ /dev/null @@ -1,4 +0,0 @@ -void *xm(size_t size, size_t nmemb); -void *xr(void *p, size_t size, size_t nmemb); -void *xpnd(void *p, int nit, int *sit, size_t sz); -#define XPND(p, num, spc) (p = xpnd(p, num, &spc, sizeof *p))