Hacker Backdoor script? [closed] - php

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I found this script attached to a modified index page. This looks like some kind of backdoor. and who is this SAPE ?
<?php
class SAPE_base {
var $_version = '1.0.8';
var $_verbose = false;
var $_charset = '';
var $_sape_charset = '';
var $_server_list = array('dispenser-01.sape.ru', 'dispenser-02.sape.ru');
var $_cache_lifetime = 3600;
var $_cache_reloadtime = 600;
var $_error = '';
var $_host = '';
var $_request_uri = '';
var $_multi_site = false;
var $_fetch_remote_type = '';
var $_socket_timeout = 6;
var $_force_show_code = false;
var $_is_our_bot = false;
var $_debug = false;
var $_ignore_case = false;
var $_db_file = '';
var $_use_server_array = false;
var $_force_update_db = false;
function SAPE_base($options = null) {
$host = '';
if (is_array($options)) {
if (isset($options['host'])) {
$host = $options['host'];
}
}
elseif (strlen($options)) {
$host = $options;
$options = array();
}
else {
$options = array();
}
if (isset($options['use_server_array']) && $options['use_server_array'] == true) {
$this->_use_server_array = true;
}
if (strlen($host)) {
$this->_host = $host;
}
else {
$this->_host = $_SERVER['HTTP_HOST'];
}
$this->_host = preg_replace('/^http:\/\//', '', $this->_host);
$this->_host = preg_replace('/^www\./', '', $this->_host);
if (isset($options['request_uri']) && strlen($options['request_uri'])) {
$this->_request_uri = $options['request_uri'];
}
elseif ($this->_use_server_array === false) {
$this->_request_uri = getenv('REQUEST_URI');
}
if (strlen($this->_request_uri) == 0) {
$this->_request_uri = $_SERVER['REQUEST_URI'];
}
if (isset($options['multi_site']) && $options['multi_site'] == true) {
$this->_multi_site = true;
}
if (isset($options['debug']) && $options['debug'] == true) {
$this->_debug = true;
}
if (isset($_COOKIE['sape_cookie']) && ($_COOKIE['sape_cookie'] == _SAPE_USER)) {
$this->_is_our_bot = true;
if (isset($_COOKIE['sape_debug']) && ($_COOKIE['sape_debug'] == 1)) {
$this->_debug = true;
$this->_options = $options;
$this->_server_request_uri = $this->_request_uri = $_SERVER['REQUEST_URI'];
$this->_getenv_request_uri = getenv('REQUEST_URI');
$this->_SAPE_USER = _SAPE_USER;
}
if (isset($_COOKIE['sape_updatedb']) && ($_COOKIE['sape_updatedb'] == 1)) {
$this->_force_update_db = true;
}
}
else {
$this->_is_our_bot = false;
}
if (isset($options['verbose']) && $options['verbose'] == true || $this->_debug) {
$this->_verbose = true;
}
if (isset($options['charset']) && strlen($options['charset'])) {
$this->_charset = $options['charset'];
}
else {
$this->_charset = 'windows-1251';
}
if (isset($options['fetch_remote_type']) && strlen($options['fetch_remote_type'])) {
$this->_fetch_remote_type = $options['fetch_remote_type'];
}
if (isset($options['socket_timeout']) && is_numeric($options['socket_timeout']) && $options['socket_timeout'] > 0) {
$this->_socket_timeout = $options['socket_timeout'];
}
if (isset($options['force_show_code']) && $options['force_show_code'] == true) {
$this->_force_show_code = true;
}
if (!defined('_SAPE_USER')) {
return $this->raise_error('Не задана константа _SAPE_USER');
}
if (isset($options['ignore_case']) && $options['ignore_case'] == true) {
$this->_ignore_case = true;
$this->_request_uri = strtolower($this->_request_uri);
}
}
function fetch_remote_file($host, $path) {
$user_agent = $this->_user_agent . ' ' . $this->_version;
#ini_set('allow_url_fopen', 1);
#ini_set('default_socket_timeout', $this->_socket_timeout);
#ini_set('user_agent', $user_agent);
if (
$this->_fetch_remote_type == 'file_get_contents'
||
(
$this->_fetch_remote_type == ''
&&
function_exists('file_get_contents')
&&
ini_get('allow_url_fopen') == 1
)
) {
$this->_fetch_remote_type = 'file_get_contents';
if ($data = #file_get_contents('http://' . $host . $path)) {
return $data;
}
}
elseif (
$this->_fetch_remote_type == 'curl'
||
(
$this->_fetch_remote_type == ''
&&
function_exists('curl_init')
)
) {
$this->_fetch_remote_type = 'curl';
if ($ch = #curl_init()) {
#curl_setopt($ch, CURLOPT_URL, 'http://' . $host . $path);
#curl_setopt($ch, CURLOPT_HEADER, false);
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
#curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->_socket_timeout);
#curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
if ($data = #curl_exec($ch)) {
return $data;
}
#curl_close($ch);
}
}
else {
$this->_fetch_remote_type = 'socket';
$buff = '';
$fp = #fsockopen($host, 80, $errno, $errstr, $this->_socket_timeout);
if ($fp) {
#fputs($fp, "GET {$path} HTTP/1.0\r\nHost: {$host}\r\n");
#fputs($fp, "User-Agent: {$user_agent}\r\n\r\n");
while (!#feof($fp)) {
$buff .= #fgets($fp, 128);
}
#fclose($fp);
$page = explode("\r\n\r\n", $buff);
return $page[1];
}
}
return $this->raise_error('Не могу подключиться к серверу: ' . $host . $path . ', type: ' . $this->_fetch_remote_type);
}
function _read($filename) {
$fp = #fopen($filename, 'rb');
#flock($fp, LOCK_SH);
if ($fp) {
clearstatcache();
$length = #filesize($filename);
$mqr = #get_magic_quotes_runtime();
#set_magic_quotes_runtime(0);
if ($length) {
$data = #fread($fp, $length);
}
else {
$data = '';
}
#set_magic_quotes_runtime($mqr);
#flock($fp, LOCK_UN);
#fclose($fp);
return $data;
}
return $this->raise_error('Не могу считать данные из файла: ' . $filename);
}
function _write($filename, $data) {
$fp = #fopen($filename, 'ab');
if ($fp) {
if (flock($fp, LOCK_EX | LOCK_NB)) {
$length = strlen($data);
ftruncate($fp, 0);
#fwrite($fp, $data, $length);
#flock($fp, LOCK_UN);
#fclose($fp);
if (md5($this->_read($filename)) != md5($data)) {
#unlink($filename);
return $this->raise_error('Нарушена целостность данных при записи в файл: ' . $filename);
}
}
else {
return false;
}
return true;
}
return $this->raise_error('Не могу записать данные в файл: ' . $filename);
}
function raise_error($e) {
$this->_error = '<p style="color: red; font-weight: bold;">SAPE ERROR: ' . $e . '</p>';
if ($this->_verbose == true) {
print $this->_error;
}
return false;
}
function load_data() {
$this->_db_file = $this->_get_db_file();
if (!is_file($this->_db_file)) {
if (#touch($this->_db_file)) {
#chmod($this->_db_file, 0666);
}
else {
return $this->raise_error('Нет файла ' . $this->_db_file . '. Создать не удалось. Выставите права 777 на папку.');
}
}
if (!is_writable($this->_db_file)) {
return $this->raise_error('Нет доступа на запись к файлу: ' . $this->_db_file . '! Выставите права 777 на папку.');
}
#clearstatcache();
$data = $this->_read($this->_db_file);
if (
$this->_force_update_db
|| (
!$this->_is_our_bot
&&
(
filemtime($this->_db_file) < (time() - $this->_cache_lifetime)
||
filesize($this->_db_file) == 0
||
#unserialize($data) == false
)
)
) {
#touch($this->_db_file, (time() - $this->_cache_lifetime + $this->_cache_reloadtime));
$path = $this->_get_dispenser_path();
if (strlen($this->_charset)) {
$path .= '&charset=' . $this->_charset;
}
foreach ($this->_server_list as $i => $server) {
if ($data = $this->fetch_remote_file($server, $path)) {
if (substr($data, 0, 12) == 'FATAL ERROR:') {
$this->raise_error($data);
}
else {
$hash = #unserialize($data);
if ($hash != false) {
$hash['__sape_charset__'] = $this->_charset;
$hash['__last_update__'] = time();
$hash['__multi_site__'] = $this->_multi_site;
$hash['__fetch_remote_type__'] = $this->_fetch_remote_type;
$hash['__ignore_case__'] = $this->_ignore_case;
$hash['__php_version__'] = phpversion();
$hash['__server_software__'] = $_SERVER['SERVER_SOFTWARE'];
$data_new = #serialize($hash);
if ($data_new) {
$data = $data_new;
}
$this->_write($this->_db_file, $data);
break;
}
}
}
}
}
if (strlen(session_id())) {
$session = session_name() . '=' . session_id();
$this->_request_uri = str_replace(array('?' . $session, '&' . $session), '', $this->_request_uri);
}
$this->set_data(#unserialize($data));
}
}
class SAPE_client extends SAPE_base {
var $_links_delimiter = '';
var $_links = array();
var $_links_page = array();
var $_user_agent = 'SAPE_Client PHP';
function SAPE_client($options = null) {
parent::SAPE_base($options);
$this->load_data();
}
function return_links($n = null, $offset = 0) {
if (is_array($this->_links_page)) {
$total_page_links = count($this->_links_page);
if (!is_numeric($n) || $n > $total_page_links) {
$n = $total_page_links;
}
$links = array();
for ($i = 1; $i <= $n; $i++) {
if ($offset > 0 && $i <= $offset) {
array_shift($this->_links_page);
}
else {
$links[] = array_shift($this->_links_page);
}
}
$html = join($this->_links_delimiter, $links);
if (
strlen($this->_charset) > 0
&&
strlen($this->_sape_charset) > 0
&&
$this->_sape_charset != $this->_charset
&&
function_exists('iconv')
) {
$new_html = #iconv($this->_sape_charset, $this->_charset, $html);
if ($new_html) {
$html = $new_html;
}
}
if ($this->_is_our_bot) {
$html = '<sape_noindex>' . $html . '</sape_noindex>';
}
}
else {
$html = $this->_links_page;
}
if ($this->_debug) {
$html .= print_r($this, true);
}
return $html;
}
function _get_db_file() {
if ($this->_multi_site) {
return dirname(__FILE__) . '/' . $this->_host . '.links.db';
}
else {
return dirname(__FILE__) . '/links.db';
}
}
function _get_dispenser_path() {
return '/code.php?user=' . _SAPE_USER . '&host=' . $this->_host;
}
function set_data($data) {
if ($this->_ignore_case) {
$this->_links = array_change_key_case($data);
}
else {
$this->_links = $data;
}
if (isset($this->_links['__sape_delimiter__'])) {
$this->_links_delimiter = $this->_links['__sape_delimiter__'];
}
if (isset($this->_links['__sape_charset__'])) {
$this->_sape_charset = $this->_links['__sape_charset__'];
}
else {
$this->_sape_charset = '';
}
if (#array_key_exists($this->_request_uri, $this->_links) && is_array($this->_links[$this->_request_uri])) {
$this->_links_page = $this->_links[$this->_request_uri];
}
else {
if (isset($this->_links['__sape_new_url__']) && strlen($this->_links['__sape_new_url__'])) {
if ($this->_is_our_bot || $this->_force_show_code) {
$this->_links_page = $this->_links['__sape_new_url__'];
}
}
}
}
}
class SAPE_context extends SAPE_base {
var $_words = array();
var $_words_page = array();
var $_user_agent = 'SAPE_Context PHP';
var $_filter_tags = array('a', 'textarea', 'select', 'script', 'style', 'label', 'noscript', 'noindex', 'button');
function SAPE_context($options = null) {
parent::SAPE_base($options);
$this->load_data();
}
function replace_in_text_segment($text) {
$debug = '';
if ($this->_debug) {
$debug .= "<!-- argument for replace_in_text_segment: \r\n" . base64_encode($text) . "\r\n -->";
}
if (count($this->_words_page) > 0) {
$source_sentence = array();
if ($this->_debug) {
$debug .= '<!-- sentences for replace: ';
}
foreach ($this->_words_page as $n => $sentence) {
//Заменяем все сущности на символы
$special_chars = array(
'&' => '&',
'"' => '"',
''' => '\'',
'<' => '<',
'>' => '>'
);
$sentence = strip_tags($sentence);
foreach ($special_chars as $from => $to) {
str_replace($from, $to, $sentence);
}
$sentence = htmlspecialchars($sentence);
$sentence = preg_quote($sentence, '/');
$replace_array = array();
if (preg_match_all('/(&[#a-zA-Z0-9]{2,6};)/isU', $sentence, $out)) {
for ($i = 0; $i < count($out[1]); $i++) {
$unspec = $special_chars[$out[1][$i]];
$real = $out[1][$i];
$replace_array[$unspec] = $real;
}
}
foreach ($replace_array as $unspec => $real) {
$sentence = str_replace($real, '((' . $real . ')|(' . $unspec . '))', $sentence);
}
$source_sentences[$n] = str_replace(' ', '((\s)|( ))+', $sentence);
if ($this->_debug) {
$debug .= $source_sentences[$n] . "\r\n\r\n";
}
}
if ($this->_debug) {
$debug .= '-->';
}
$first_part = true;
if (count($source_sentences) > 0) {
$content = '';
$open_tags = array();
$close_tag = '';
$part = strtok(' ' . $text, '<');
while ($part !== false) {
if (preg_match('/(?si)^(\/?[a-z0-9]+)/', $part, $matches)) {
$tag_name = strtolower($matches[1]);
if (substr($tag_name, 0, 1) == '/') {
$close_tag = substr($tag_name, 1);
if ($this->_debug) {
$debug .= '<!-- close_tag: ' . $close_tag . ' -->';
}
}
else {
$close_tag = '';
if ($this->_debug) {
$debug .= '<!-- open_tag: ' . $tag_name . ' -->';
}
}
$cnt_tags = count($open_tags);
if (($cnt_tags > 0) && ($open_tags[$cnt_tags - 1] == $close_tag)) {
array_pop($open_tags);
if ($this->_debug) {
$debug .= '<!-- ' . $tag_name . ' - deleted from open_tags -->';
}
if ($cnt_tags - 1 == 0) {
if ($this->_debug) {
$debug .= '<!-- start replacement -->';
}
}
}
if (count($open_tags) == 0) {
if (!in_array($tag_name, $this->_filter_tags)) {
$split_parts = explode('>', $part, 2);
if (count($split_parts) == 2) {
foreach ($source_sentences as $n => $sentence) {
if (preg_match('/' . $sentence . '/', $split_parts[1]) == 1) {
$split_parts[1] = preg_replace('/' . $sentence . '/', str_replace('$', '\$', $this->_words_page[$n]), $split_parts[1], 1);
if ($this->_debug) {
$debug .= '<!-- ' . $sentence . ' --- ' . $this->_words_page[$n] . ' replaced -->';
}
unset($source_sentences[$n]);
unset($this->_words_page[$n]);
}
}
$part = $split_parts[0] . '>' . $split_parts[1];
unset($split_parts);
}
}
else {
$open_tags[] = $tag_name;
if ($this->_debug) {
$debug .= '<!-- ' . $tag_name . ' - added to open_tags, stop replacement -->';
}
}
}
}
else {
foreach ($source_sentences as $n => $sentence) {
if (preg_match('/' . $sentence . '/', $part) == 1) {
$part = preg_replace('/' . $sentence . '/', str_replace('$', '\$', $this->_words_page[$n]), $part, 1);
if ($this->_debug) {
$debug .= '<!-- ' . $sentence . ' --- ' . $this->_words_page[$n] . ' replaced -->';
}
unset($source_sentences[$n]);
unset($this->_words_page[$n]);
}
}
}
if ($this->_debug) {
$content .= $debug;
$debug = '';
}
if ($first_part) {
$content .= $part;
$first_part = false;
}
else {
$content .= $debug . '<' . $part;
}
unset($part);
$part = strtok('<');
}
$text = ltrim($content);
unset($content);
}
}
else {
if ($this->_debug) {
$debug .= '<!-- No word`s for page -->';
}
}
if ($this->_debug) {
$debug .= '<!-- END: work of replace_in_text_segment() -->';
}
if ($this->_is_our_bot || $this->_force_show_code || $this->_debug) {
$text = '<sape_index>' . $text . '</sape_index>';
if (isset($this->_words['__sape_new_url__']) && strlen($this->_words['__sape_new_url__'])) {
$text .= $this->_words['__sape_new_url__'];
}
}
if ($this->_debug) {
if (count($this->_words_page) > 0) {
$text .= '<!-- Not replaced: ' . "\r\n";
foreach ($this->_words_page as $n => $value) {
$text .= $value . "\r\n\r\n";
}
$text .= '-->';
}
$text .= $debug;
}
return $text;
}
function replace_in_page(&$buffer) {
if (count($this->_words_page) > 0) {
$split_content = preg_split('/(?smi)(<\/?sape_index>)/', $buffer, -1);
$cnt_parts = count($split_content);
if ($cnt_parts > 1) {
//Если есть хоть одна пара sape_index, то начинаем работу
if ($cnt_parts >= 3) {
for ($i = 1; $i < $cnt_parts; $i = $i + 2) {
$split_content[$i] = $this->replace_in_text_segment($split_content[$i]);
}
}
$buffer = implode('', $split_content);
if ($this->_debug) {
$buffer .= '<!-- Split by Sape_index cnt_parts=' . $cnt_parts . '-->';
}
}
else {
$split_content = preg_split('/(?smi)(<\/?body[^>]*>)/', $buffer, -1, PREG_SPLIT_DELIM_CAPTURE);
if (count($split_content) == 5) {
$split_content[0] = $split_content[0] . $split_content[1];
$split_content[1] = $this->replace_in_text_segment($split_content[2]);
$split_content[2] = $split_content[3] . $split_content[4];
unset($split_content[3]);
unset($split_content[4]);
$buffer = $split_content[0] . $split_content[1] . $split_content[2];
if ($this->_debug) {
$buffer .= '<!-- Split by BODY -->';
}
}
else {
if ($this->_debug) {
$buffer .= '<!-- Can`t split by BODY -->';
}
}
}
}
else {
if (!$this->_is_our_bot && !$this->_force_show_code && !$this->_debug) {
$buffer = preg_replace('/(?smi)(<\/?sape_index>)/', '', $buffer);
}
else {
if (isset($this->_words['__sape_new_url__']) && strlen($this->_words['__sape_new_url__'])) {
$buffer .= $this->_words['__sape_new_url__'];
}
}
if ($this->_debug) {
$buffer .= '<!-- No word`s for page -->';
}
}
return $buffer;
}
function _get_db_file() {
if ($this->_multi_site) {
return dirname(__FILE__) . '/' . $this->_host . '.words.db';
}
else {
return dirname(__FILE__) . '/words.db';
}
}
function _get_dispenser_path() {
return '/code_context.php?user=' . _SAPE_USER . '&host=' . $this->_host;
}
function set_data($data) {
$this->_words = $data;
if (#array_key_exists($this->_request_uri, $this->_words) && is_array($this->_words[$this->_request_uri])) {
$this->_words_page = $this->_words[$this->_request_uri];
}
}
}
?>

Sape is apparently link exchange service used by a Russian-speaking botnet owner.
This backdoor appears to use the sape API to download XML and use bots to create a "context" that probably clicks links to generate illicit revenue.
From a bad Google transition of sape.ru:
Sape system increases revenue and reduces the consumption of
webmasters optimizers. Venues are beginning to sell the place, not
only from the main pages, but also internal. How many pages on the
site? Let each revenue. Optimizers are buying cheap internal pages and
save on moving projects.

My Russian isn't very good, but sape.ru looks like some kind of link exchange service. And in answer to your question "Who is SAPE":
[david#archtower ~]$ whois sape.ru
% By submitting a query to RIPN's Whois Service
% you agree to abide by the following terms of use:
% http://www.ripn.net/about/servpol.html#3.2 (in Russian)
% http://www.ripn.net/about/en/servpol.html#3.2 (in English).
domain: SAPE.RU
nserver: ns1.q0.ru.
nserver: ns2.q0.ru.
nserver: ns3.q0.ru.
state: REGISTERED, DELEGATED, VERIFIED
org: LTD Sape
registrar: R01-REG-RIPN
admin-contact: https://partner.r01.ru/contact_admin.khtml
created: 2006.06.20
paid-till: 2013.06.20
free-date: 2013.07.21
source: TCI
Last updated on 2012.06.19 19:28:42 MSK
[david#archtower ~]$

Looks like it's something to automatically visit ads referral links at first glance.

Related

PHP retrieve footnotes of pages on DOCX

i'm trying to convert DOCX to html, after search on google i can find this simple library as this convertor from https://github.com/xylude/Docx-to-HTML/blob/master/docx_reader.php , but that couldn't detect footnote on pages and i'm trying to add that to this library,
how can i detect styled text or simple text is/are footnote? that have special style?
<?php
class Docx_reader {
private $fileData = false;
private $errors = array();
private $styles = array();
public function __construct() {
}
private function load($file) {
if (file_exists($file)) {
$zip = new ZipArchive();
$openedZip = $zip->open($file);
if ($openedZip === true) {
//attempt to load styles:
if (($styleIndex = $zip->locateName('word/styles.xml')) !== false) {
$stylesXml = $zip->getFromIndex($styleIndex);
$xml = simplexml_load_string($stylesXml);
$namespaces = $xml->getNamespaces(true);
$children = $xml->children($namespaces['w']);
foreach ($children->style as $s) {
$attr = $s->attributes('w', true);
if (isset($attr['styleId'])) {
$tags = array();
$attrs = array();
foreach (get_object_vars($s->rPr) as $tag => $style) {
$att = $style->attributes('w', true);
switch ($tag) {
case "b":
$tags[] = 'strong';
break;
case "i":
$tags[] = 'em';
break;
case "color":
//echo (String) $att['val'];
$attrs[] = 'color:#' . $att['val'];
break;
case "sz":
$attrs[] = 'font-size:' . $att['val'] . 'px';
break;
}
}
$styles[(String)$attr['styleId']] = array('tags' => $tags, 'attrs' => $attrs);
}
}
$this->styles = $styles;
}
if (($index = $zip->locateName('word/document.xml')) !== false) {
// If found, read it to the string
$data = $zip->getFromIndex($index);
// Close archive file
$zip->close();
return $data;
}
$zip->close();
}
}
} else {
$this->errors[] = 'File does not exist.';
}
}
public function setFile($path) {
$this->fileData = $this->load($path);
}
public function to_plain_text() {
if ($this->fileData) {
return strip_tags($this->fileData);
} else {
return false;
}
}
public function to_html() {
if ($this->fileData) {
$xml = simplexml_load_string($this->fileData);
$namespaces = $xml->getNamespaces(true);
$children = $xml->children($namespaces['w']);
$html = '<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title></title><style>span.block { display: block; }</style></head><body>';
foreach ($children->body->p as $p) {
$style = '';
$startTags = array();
$startAttrs = array();
if($p->pPr->pStyle) {
$objectAttrs = $p->pPr->pStyle->attributes('w',true);
$objectStyle = (String) $objectAttrs['val'];
if(isset($this->styles[$objectStyle])) {
$startTags = $this->styles[$objectStyle]['tags'];
$startAttrs = $this->styles[$objectStyle]['attrs'];
}
}
if ($p->pPr->spacing) {
$att = $p->pPr->spacing->attributes('w', true);
if (isset($att['before'])) {
$style.='padding-top:' . ($att['before'] / 10) . 'px;';
}
if (isset($att['after'])) {
$style.='padding-bottom:' . ($att['after'] / 10) . 'px;';
}
}
$html.='<span class="block" style="' . $style . '">';
$li = false;
if ($p->pPr->numPr) {
$li = true;
$html.='<li>';
}
foreach ($p->r as $part) {
//echo $part->t;
$tags = $startTags;
$attrs = $startAttrs;
foreach (get_object_vars($part->pPr) as $k => $v) {
if ($k = 'numPr') {
$tags[] = 'li';
}
}
foreach (get_object_vars($part->rPr) as $tag => $style) {
//print_r($style->attributes());
$att = $style->attributes('w', true);
switch ($tag) {
case "b":
$tags[] = 'strong';
break;
case "i":
$tags[] = 'em';
break;
case "color":
//echo (String) $att['val'];
$attrs[] = 'color:#' . $att['val'];
break;
case "sz":
$attrs[] = 'font-size:' . $att['val'] . 'px';
break;
}
}
$openTags = '';
$closeTags = '';
foreach ($tags as $tag) {
$openTags.='<' . $tag . '>';
$closeTags.='</' . $tag . '>';
}
$html.='<span style="' . implode(';', $attrs) . '">' . $openTags . $part->t . $closeTags . '</span>';
}
if ($li) {
$html.='</li>';
}
$html.="</span>";
}
//Trying to weed out non-utf8 stuff from the file:
$regex = <<<'END'
/
(
(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
| [\xC0-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
){1,100} # ...one or more times
)
| . # anything else
/x
END;
preg_replace($regex, '$1', $html);
return $html . '</body></html>';
exit();
}
}
public function get_errors() {
return $this->errors;
}
private function getStyles() {
}
}

Write single element of array to fwrite file

I'm trying to return an array from MyArray function and use [0] to write2file and use [1] to populate pushover(myArray($jason)). I have tried fwrite($myfile, echo $txt[0]); but this fails and only writes the word 'Array' to the file instead of contents of array. I've looked at print_r and implode but no luck.
write2file(myArray($json));
compare2files('old_version.txt', 'new_version.txt');
if (compare2files('old_version.txt', 'new_version.txt') == 'false') {
pushover(implode("\n",myArray($json)[1]));
rename("new_version.txt", "old_version.txt");
}
function write2file($txt) {
$myfile = fopen("new_version.txt", "w") or die("Unable to open file!");
fwrite($myfile, implode("\n",$txt[0]));
fclose($myfile);
}
function compare2files($file1, $file2) {
$file3 = file_get_contents($file1);
$file4 = file_get_contents($file2);
if (strcmp($file3, $file4) !== 0) {
return 'false';
}
}
function myArray($arry) {
$selected = array(5,6,7,10,12,15,17,18,22,24);
foreach($arry as $key => $value) {
if (in_array($key, $selected) || empty($selected)) {
$result .= $value['name']. chr(10);
$xTime .= $value['name']. chr(10);
$length = count($value["color"]);
for ($i = 0; $i < $length; $i++) {
if($value['time'][$i] != "") {
if(preg_match('/#ff0000/', $value['color'][$i])) {
$value['color'][$i] = 'RED';
}
if(preg_match('/#ffff00/', $value['color'][$i])) {
$value['color'][$i] = 'YELLOW';
}
if(preg_match('/#006600/', $value['color'][$i])) {
$value['color'][$i] = 'GREEN (Mini Disaster)';
}
if(preg_match('/#9933cc/', $value['color'][$i])) {
$value['color'][$i] = 'PURPLE (Trauma ByPass)';
}
if(preg_match('/#ff6600/', $value['color'][$i])) {
$value['color'][$i] = 'ORANGE (ReRoute)';
}
$xTime .= ' ' . $value["color"][$i] . ' - ' . $value["time"][$i] . chr(10);
$xColor .= ' ' . $value["color"][$i] . chr(10);
$results[0] = $xTime;
$results[1] = $xColor;
}
}
}
}
return $results;
}

Torrent with Laravel using Laratracker

I am implementing the laratracker , a bittorrent tracker built in laravel, but unable to start the download. Only one peer appears to be seeding, Sometimes it is saying "Connecting to peers" and remains at it is. The code which i am using is :
<?php
namespace App\Http\Controllers\Announce;
use App\Helpers\BencodeHelper;
use App\Models\Peer;
use App\Models\PeerTorrent;
use App\Models\Torrent;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
class AnnounceController extends Controller
{
const __INTERVAL = 1000;
const __TIMEOUT = 120;
const __INTERVAL_MIN = 60;
const __MAX_PPR = 20;
public function announce(Request $request)
{
Log::info($request->fullUrl());
$status = 200;
$content = "";
$passkey = Input::get('passkey');
$peer_id = Input::get('peer_id');
$port = Input::get('port');
$info_hash = Input::get('info_hash');
$downloaded = Input::get('uploaded') ? intval(Input::get('uploaded')) : 0;
$uploaded = Input::get('uploaded') ? intval(Input::get('uploaded')) : 0;
$left = Input::get('left') ? intval(Input::get('left')) : 0;
$compact = Input::get('compact') ? intval(Input::get('compact')) : 0;
$no_peer_id = Input::get('no_peer_id') ? intval(Input::get('no_peer_id')) : 0;
$ipAddress = '';
// Check for X-Forwarded-For headers and use those if found
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && ('' !== trim($_SERVER['HTTP_X_FORWARDED_FOR']))) {
$ipAddress = (trim($_SERVER['HTTP_X_FORWARDED_FOR']));
} else {
if (isset($_SERVER['REMOTE_ADDR']) && ('' !== trim($_SERVER['REMOTE_ADDR']))) {
$ipAddress = (trim($_SERVER['REMOTE_ADDR']));
}
}
$port = $_SERVER['REMOTE_PORT'];
/*if(!$port || !ctype_digit($port) || intval($port) < 1 || intval($port) > 65535)
{
$content = BencodeHelper::track("Invalid client port.");
$status = 401;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
if ($port == 999 && substr($peer_id, 0, 10) == '-TO0001-XX') {
die("d8:completei0e10:incompletei0e8:intervali600e12:min intervali60e5:peersld2:ip12:72.14.194.184:port3:999ed2:ip11:72.14.194.14:port3:999ed2:ip12:72.14.194.654:port3:999eee");
}*/
if (!$passkey) {
$content = BencodeHelper::track("Missing passkey.");
$status = 401;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
$torrent = Torrent::getByInfoHash(sha1($info_hash));
if (!$torrent || $torrent == null) {
$content = "Torrent not registered with this tracker.";
$status = 404;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
$user = User::has('passkeys', '=', $passkey)->get();
if ($user == null) {
$content = BencodeHelper::track("Invalid passkey.");
$status = 401;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
$peer = Peer::getByHashAndPasskey(bin2hex($peer_id), $passkey);
if ($peer == null) {
$peer = Peer::create([
'hash' => bin2hex($peer_id),
'user_agent' => $_SERVER['HTTP_USER_AGENT'],
'ip_address' => $ipAddress,
'passkey' => $passkey,
'port' => $port
]);
}
if (!$info_hash || strlen($info_hash) != 20) {
$content = BencodeHelper::track("Invalid info_hash.");
$status = 401;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
$peer_torrent = PeerTorrent::getByPeerAndTorrent($peer, $torrent);
if ($peer_torrent == null) {
$peer_torrent = PeerTorrent::create([
'peer_id' => $peer->id,
'torrent_id' => $torrent->id,
'uploaded' => $uploaded,
'downloaded' => $downloaded,
'left' => $left,
'stopped' => false
]);
} else {
$peer_torrent->uploaded = $uploaded;
$peer_torrent->downloaded = $downloaded;
$peer_torrent->left = $left;
$peer_torrent->save();
}
$seeders = $torrent->getSeedersCount();
$leechers = $torrent->getLeechersCount();
$resp = "";
if ($compact != 1) {
$resp = "d" . $this->benc_str("interval") . "i" . AnnounceController::__INTERVAL . "e" . $this->benc_str("peers") . "l";
} else {
$resp = "d" . $this->benc_str("interval") . "i" . AnnounceController::__INTERVAL . "e" . $this->benc_str("min interval") . "i" . 300 . "e5:" . "peers";
}
$peer = array();
$peer_num = 0;
foreach ($torrent->getPeersArray() as $row) {
if ($compact != 1) {
if ($row["peer_id"] === $peer->hash) {
continue;
}
$resp .= "d" . $this->benc_str("ip") . $this->benc_str($row['ip']);
if ($no_peer_id == 0) {
$resp .= $this->benc_str("peer id") . $this->benc_str($row["peer_id"]);
}
$resp .= $this->benc_str("port") . "i" . $row["port"] . "e" . "e";
} else {
$peer_ip = explode('.', $row["ip"]);
$peer_ip = pack("C*", $peer_ip[0], $peer_ip[1], $peer_ip[2], $peer_ip[3]);
$peer_port = pack("n*", (int)$row["port"]);
$time = intval((time() % 7680) / 60);
if ($left == 0) {
$time += 128;
}
$time = pack("C", $time);
$peer[] = $time . $peer_ip . $peer_port;
$peer_num++;
}
}
if ($compact != 1) {
$resp .= "ee";
} else {
$o = "";
for ($i = 0; $i < $peer_num; $i++) {
$o .= substr($peer[$i], 1, 6);
}
$resp .= strlen($o) . ':' . $o . 'e';
}
$this->benc_resp_raw($resp);
}
public function benc_resp($d)
{
return $this->benc_resp_raw($this->benc(array('type' => 'dictionary', 'value' => $d)));
}
public function benc_resp_raw($x)
{
header("Content-Type: text/plain");
header("Pragma: no-cache");
if ($_SERVER['HTTP_ACCEPT_ENCODING'] == 'gzip') {
header("Content-Encoding: gzip");
echo gzencode($x, 9, FORCE_GZIP);
} else {
echo $x;
}
}
function benc($obj)
{
if (!is_array($obj) || !isset($obj["type"]) || !isset($obj["value"]))
return;
$c = $obj["value"];
switch ($obj["type"]) {
case "string":
return $this->benc_str($c);
case "integer":
return $this->benc_int($c);
case "list":
return $this->benc_list($c);
case "dictionary":
return $this->benc_dict($c);
default:
return;
}
}
public function benc_str($s)
{
return strlen($s) . ":$s";
}
public function benc_int($i)
{
return "i" . $i . "e";
}
public function benc_list($a)
{
$s = "l";
foreach ($a as $e) {
$s .= $this->benc($e);
}
$s .= "e";
return $s;
}
public function benc_dict($d)
{
$s = "d";
$keys = array_keys($d);
sort($keys);
foreach ($keys as $k) {
$v = $d[$k];
$s .= $this->benc_str($k);
$s .= $this->benc($v);
}
$s .= "e";
return $s;
}
public function hex2bin($hex)
{
$r = '';
for ($i = 0; $i < strlen($hex); $i += 2) {
$r .= chr(hexdec($hex{$i} . $hex{($i + 1)}));
}
return $r;
}
}
<?php
Not sure what to add or modify to the code to get it working . Help appreciated for the solution .

My Php Script Error

i have a script named remauth.php
it connects to phpbb database and use some information of users.
its code:
<?php
// standard phpBB setup
if ($_SERVER['REMOTE_ADDR'] == "127.0.0.1" || $_SERVER['REMOTE_ADDR'] == "94.23.147.71" || $_SERVER['REMOTE_ADDR'] == "188.226.149.35")
{
unset($_SERVER['REMOTE_ADDR']);
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_REAL_IP'];
}
if ($_SERVER['HTTP_X_FORWARDED_FOR'] == "127.0.0.1" || $_SERVER['HTTP_X_FORWARDED_FOR'] == "94.23.147.71" || $_SERVER['HTTP_X_FORWARDED_FOR'] == "188.226.149.35")
{
unset($_SERVER['HTTP_X_FORWARDED_FOR']);
}
function get_ip_address()
{
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key)
{
if (array_key_exists($key, $_SERVER) === true)
{
foreach (explode(',', $_SERVER[$key]) as $ip)
{
if ($_SERVER[$key] == "127.0.0.1" || $_SERVER[$key] == "94.23.147.71" || $_SERVER[$key] == "188.226.149.35")
{
unset($_SERVER[$key]);
}
if (valid_ip($ip) !== false)
{
return $ip;
}
}
}
}
}
get_ip_address();
$acm_type = "memcache";
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
define('IN_PHPBB', true);
define('IN_CHECK_BAN', 1);
define('IN_LOGIN', 1);
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);
//include_once($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
if (!function_exists('group_memberships'))
{
include_once($phpbb_root_path . 'includes/functions_user.'.$phpEx);
}
function valid_ip($ip)
{
return (!preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $ip)) ? FALSE : TRUE;
}
$user->session_begin();
$auth->acl($user->data);
$canPlay = false;
function isGroup($userid)
{
$groups = group_memberships(false, $userid);
$return = false;
foreach ($groups as $grouprec)
{
if ($grouprec['group_id'] == 2 || $grouprec['group_id'] == 3 || $grouprec['group_id'] == 4 || $grouprec['group_id'] == 5 || $grouprec['group_id'] == 8 || $grouprec['group_id'] == 9 || $grouprec['group_id'] == 10)
{
$return = true;
}
}
return $return;
}
function get_profile_fields($user_id)
{
global $db;
$sql = 'SELECT *
FROM ' . PROFILE_FIELDS_DATA_TABLE . '
WHERE ' . $db->sql_in_set('user_id', array_map('intval', $user_id));
$result = $db->sql_query($sql);
$field_data = array();
while ($row = $db->sql_fetchrow($result))
{
$field_data[$row['user_id']] = $row;
}
$db->sql_freeresult($result);
$user_fields = array();
$fields = array('can_has_servers', 'can_play', 'can_play_expire', 'can_play_reason');
foreach ($fields as $used_ident)
{
foreach ($field_data as $user_id => $row)
{
$user_fields[$user_id][$used_ident]['value'] = $row['pf_' . $used_ident];
}
}
return $user_fields;
}
function check_ban($user_id = false, $user_ips = false, $user_email = false, $return = false)
{
global $config, $db;
$banned = false;
$cache_ttl = 3600;
$where_sql = array();
$sql = 'SELECT ban_ip, ban_userid, ban_email, ban_exclude, ban_give_reason, ban_end
FROM ' . BANLIST_TABLE . '
WHERE ';
// determine which entries to check, only return those
if ($user_email === false)
{
$where_sql[] = "ban_email = ''";
}
if ($user_ips === false)
{
$where_sql[] = "(ban_ip = '' OR ban_exclude = 1)";
}
if ($user_id === false)
{
$where_sql[] = '(ban_userid = 0 OR ban_exclude = 1)';
}
else
{
$cache_ttl = ($user_id == ANONYMOUS) ? 3600 : 0;
$_sql = '(ban_userid = ' . $user_id;
if ($user_email !== false)
{
$_sql .= " OR ban_email <> ''";
}
if ($user_ips !== false)
{
$_sql .= " OR ban_ip <> ''";
}
$_sql .= ')';
$where_sql[] = $_sql;
}
$sql .= (sizeof($where_sql)) ? implode(' AND ', $where_sql) : '';
$result = $db->sql_query($sql, $cache_ttl);
$ban_triggered_by = 'user';
while ($row = $db->sql_fetchrow($result))
{
if ($row['ban_end'] && $row['ban_end'] < time())
{
continue;
}
$ip_banned = false;
if (!empty($row['ban_ip']))
{
if (!is_array($user_ips))
{
$ip_banned = preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ips);
}
else
{
foreach ($user_ips as $user_ip)
{
if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ip))
{
$ip_banned = true;
break;
}
}
}
}
if ((!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id) ||
$ip_banned ||
(!empty($row['ban_email']) && preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_email'], '#')) . '$#i', $user_email)))
{
if (!empty($row['ban_exclude']))
{
$banned = false;
break;
}
else
{
$banned = true;
$ban_row = $row;
if (!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id)
{
$ban_triggered_by = 'user';
}
else if ($ip_banned)
{
$ban_triggered_by = 'ip';
}
else
{
$ban_triggered_by = 'email';
}
// don't break. Check if there is an exclude rule for this user
}
}
}
$db->sql_freeresult($result);
if ($banned && !$return)
{
global $template;
// if the session is empty we need to create a valid one...
if (empty($this->session_id))
{
// this seems to be no longer needed? - #14971
//$this->session_create(ANONYMOUS);
}
// initiate environment ... since it won't be set at this stage
$this->setup();
// logout the user, banned users are unable to use the normal 'logout' link
if ($this->data['user_id'] != ANONYMOUS)
{
$this->session_kill();
}
// we show a login box here to allow founders accessing the board if banned by IP
if (defined('IN_LOGIN') && $this->data['user_id'] == ANONYMOUS)
{
global $phpEx;
$this->setup('ucp');
$this->data['is_registered'] = $this->data['is_bot'] = false;
// Set as a precaution to allow login_box() handling this case correctly as well as this function not being executed again.
define('IN_CHECK_BAN', 1);
login_box("index.$phpEx");
// The false here is needed, else the user is able to circumvent the ban.
$this->session_kill(false);
}
// ok, we catch the case of an empty session id for the anonymous user...
// this can happen if the user is logging in, banned by username and the login_box() being called "again".
if (empty($this->session_id) && defined('IN_CHECK_BAN'))
{
$this->session_create(ANONYMOUS);
}
// determine which message to output
$till_date = ($ban_row['ban_end']) ? $this->format_date($ban_row['ban_end']) : '';
$message = ($ban_row['ban_end']) ? 'BOARD_BAN_TIME' : 'BOARD_BAN_PERM';
$message = sprintf($this->lang[$message], $till_date, '', '');
$message .= ($ban_row['ban_give_reason']) ? '<br /><br />' . sprintf($this->lang['BOARD_BAN_REASON'], $ban_row['ban_give_reason']) : '';
$message .= '<br /><br /><em>' . $this->lang['BAN_TRIGGERED_BY_' . strtoupper($ban_triggered_by)] . '</em>';
// to circumvent session_begin returning a valid value and the check_ban() not called on second page view, we kill the session again
$this->session_kill(false);
// a very special case... we are within the cron script which is not supposed to print out the ban message... show blank page
if (defined('IN_CRON'))
{
garbage_collection();
exit_handler();
exit;
}
trigger_error($message);
}
return ($banned && $ban_row['ban_give_reason']) ? $ban_row['ban_give_reason'] : $banned;
}
// session stuff will not be needed as this occurs from a non-client session, but we need $user->setup it seems
if (empty($user->lang))
{
$user->setup();
}
$user->add_lang('ucp');
// get variables
/* $data = request_var('data', '', true);
if (!isset($_GET['username']))
{ */
$data = file_get_contents('php://input');
$data = explode('&&', $data);
$username = trim(htmlspecialchars(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $data[0]), ENT_COMPAT, 'UTF-8'));
$password = trim(htmlspecialchars(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $data[1]), ENT_COMPAT, 'UTF-8'));
/* }
else
{
$username = $_GET['username'];
$password = $_GET['password'];
} */
// perform login from $auth. we don't want autologon, viewonline nor admin access for the session
$result = $auth->login($username, $password, false, false, false);
if ($result['status'] == LOGIN_SUCCESS)
{
$userID = $user->data['user_id'];
$user_id = array($userID);
$canhave = get_profile_fields($user_id);
if ($canhave[$userID]['can_play_expire']['value'] <= time())
{
$canhave[$userID]['can_play']['value'] = 1;
}
if ($canhave[$userID]['can_play']['value'] == 1 || $canhave[$userID]['can_play']['value'] == 0 || $canhave[$userID]['can_play']['value'] == "")
{
$canPlay = true;
if (true || isGroup($user->data['user_id']))
{
$canPlay = true;
$keysql = "UPDATE phpbb_sessions SET session_onlineplay = 1, session_realip = '".htmlspecialchars(get_ip_address(), ENT_QUOTES)."' WHERE session_id = '".$user->session_id."';";
$keyresult = $db->sql_query($keysql);
$db->sql_freeresult($keyresult);
}
else
{
$result['status'] = 'nope';
$result['error_msg'] = 'triobit is currently down for maintenance.';
}
}
else
{
$result['status'] = 'nope';
//$result['error_msg'] = 'User is not allowed to play';
$result['error_msg'] = 'Online playing privileges revoked';
if ($canhave[$userID]['can_play_reason']['value'])
{
$result['error_msg'] .= ' - ' . str_replace('#', '#', $canhave[$userID]['can_play_reason']['value']);
}
if ($canhave[$userID]['can_play_expire']['value'])
{
$result['error_msg'] .= ' (will expire in ' . duration($canhave[$userID]['can_play_expire']['value'] - time()) . ')';
}
}
$banReason = check_ban($userID, '', '', 1);
if ($banReason != "")
{
$result['status'] = 'nope';
$result['error_msg'] = 'User is banned';
$canPlay = false;
}
}
// start buffering (to allow kill)
ob_start();
// output the results
echo (($result['status'] == LOGIN_SUCCESS) ? 'ok' : 'fail') . '#';
echo (($result['error_msg']) ? ((isset($user->lang[$result['error_msg']])) ? $user->lang[$result['error_msg']] : $result['error_msg']) : 'Success.') . '#';
echo (($result['status'] == LOGIN_SUCCESS) ? $user->data['user_id'] : '1') . '#';
echo (($result['status'] == LOGIN_SUCCESS) ? $user->data['username'] : 'Anonymous') . '#';
echo (($result['status'] == LOGIN_SUCCESS) ? $user->data['user_email'] : 'anonymous#example.com') . '#';
echo (($result['status'] == LOGIN_SUCCESS) ? $user->session_id : '0') . '#';
//Deleted, used for login verify now
// kill the session
if (!$canPlay)
{
$user->session_kill(false);
}
// and flush the contents
ob_end_flush();
exit;
function format_duration($seconds) {
$periods = array(
'centuries' => 3155692600,
'decades' => 315569260,
'years' => 31556926,
'months' => 2629743,
'weeks' => 604800,
'days' => 86400,
'hours' => 3600,
'minutes' => 60,
'seconds' => 1
);
$durations = array();
foreach ($periods as $period => $seconds_in_period) {
if ($seconds >= $seconds_in_period) {
$durations[$period] = floor($seconds / $seconds_in_period);
$seconds -= $durations[$period] * $seconds_in_period;
}
}
return $durations;
}
function duration($seconds) {
$data = format_duration($seconds);
$data2 = array();
foreach ($data as $unit => $amount)
{
$data2[] = $amount . ' ' . $unit;
}
return implode(', ', $data2);
}
?>
and its error
Notice: Undefined index: HTTP_X_FORWARDED_FOR in C:\xnp\htdocs\remauth.php on line 9
Notice: Undefined index: HTTP_X_FORWARDED_FOR in C:\xnp\htdocs\remauth.php on line 9
Notice: Undefined index: HTTP_X_FORWARDED_FOR in C:\xnp\htdocs\remauth.php on line 9
help me please.
Use HTTP_HOST instead of HTTP_X_FORWARDED_FOR
if ($_SERVER['HTTP_HOST'] == "127.0.0.1" || $_SERVER['HTTP_HOST'] == "94.23.147.71" || $_SERVER['HTTP_HOST'] == "188.226.149.35")
{
unset($_SERVER['HTTP_HOST']);
}
function get_ip_address()
{
foreach (array('HTTP_CLIENT_IP', 'HTTP_HOST', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key)
{
if (array_key_exists($key, $_SERVER) === true)
{
foreach (explode(',', $_SERVER[$key]) as $ip)
{
if ($_SERVER[$key] == "127.0.0.1" || $_SERVER[$key] == "94.23.147.71" || $_SERVER[$key] == "188.226.149.35")
{
unset($_SERVER[$key]);
}
if (valid_ip($ip) !== false)
{
return $ip;
}
}
}
}
}
get_ip_address();
$acm_type = "memcache";
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
define('IN_PHPBB', true);
define('IN_CHECK_BAN', 1);
define('IN_LOGIN', 1);
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);
//include_once($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
if (!function_exists('group_memberships'))
{
include_once($phpbb_root_path . 'includes/functions_user.'.$phpEx);
}
function valid_ip($ip)
{
return (!preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $ip)) ? FALSE : TRUE;
}
$user->session_begin();
$auth->acl($user->data);
$canPlay = false;
function isGroup($userid)
{
$groups = group_memberships(false, $userid);
$return = false;
foreach ($groups as $grouprec)
{
if ($grouprec['group_id'] == 2 || $grouprec['group_id'] == 3 || $grouprec['group_id'] == 4 || $grouprec['group_id'] == 5 || $grouprec['group_id'] == 8 || $grouprec['group_id'] == 9 || $grouprec['group_id'] == 10)
{
$return = true;
}
}
return $return;
}
function get_profile_fields($user_id)
{
global $db;
$sql = 'SELECT *
FROM ' . PROFILE_FIELDS_DATA_TABLE . '
WHERE ' . $db->sql_in_set('user_id', array_map('intval', $user_id));
$result = $db->sql_query($sql);
$field_data = array();
while ($row = $db->sql_fetchrow($result))
{
$field_data[$row['user_id']] = $row;
}
$db->sql_freeresult($result);
$user_fields = array();
$fields = array('can_has_servers', 'can_play', 'can_play_expire', 'can_play_reason');
foreach ($fields as $used_ident)
{
foreach ($field_data as $user_id => $row)
{
$user_fields[$user_id][$used_ident]['value'] = $row['pf_' . $used_ident];
}
}
return $user_fields;
}
function check_ban($user_id = false, $user_ips = false, $user_email = false, $return = false)
{
global $config, $db;
$banned = false;
$cache_ttl = 3600;
$where_sql = array();
$sql = 'SELECT ban_ip, ban_userid, ban_email, ban_exclude, ban_give_reason, ban_end
FROM ' . BANLIST_TABLE . '
WHERE ';
// determine which entries to check, only return those
if ($user_email === false)
{
$where_sql[] = "ban_email = ''";
}
if ($user_ips === false)
{
$where_sql[] = "(ban_ip = '' OR ban_exclude = 1)";
}
if ($user_id === false)
{
$where_sql[] = '(ban_userid = 0 OR ban_exclude = 1)';
}
else
{
$cache_ttl = ($user_id == ANONYMOUS) ? 3600 : 0;
$_sql = '(ban_userid = ' . $user_id;
if ($user_email !== false)
{
$_sql .= " OR ban_email <> ''";
}
if ($user_ips !== false)
{
$_sql .= " OR ban_ip <> ''";
}
$_sql .= ')';
$where_sql[] = $_sql;
}
$sql .= (sizeof($where_sql)) ? implode(' AND ', $where_sql) : '';
$result = $db->sql_query($sql, $cache_ttl);
$ban_triggered_by = 'user';
while ($row = $db->sql_fetchrow($result))
{
if ($row['ban_end'] && $row['ban_end'] < time())
{
continue;
}
$ip_banned = false;
if (!empty($row['ban_ip']))
{
if (!is_array($user_ips))
{
$ip_banned = preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ips);
}
else
{
foreach ($user_ips as $user_ip)
{
if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ip))
{
$ip_banned = true;
break;
}
}
}
}
if ((!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id) ||
$ip_banned ||
(!empty($row['ban_email']) && preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_email'], '#')) . '$#i', $user_email)))
{
if (!empty($row['ban_exclude']))
{
$banned = false;
break;
}
else
{
$banned = true;
$ban_row = $row;
if (!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id)
{
$ban_triggered_by = 'user';
}
else if ($ip_banned)
{
$ban_triggered_by = 'ip';
}
else
{
$ban_triggered_by = 'email';
}
// don't break. Check if there is an exclude rule for this user
}
}
}
$db->sql_freeresult($result);
if ($banned && !$return)
{
global $template;
// if the session is empty we need to create a valid one...
if (empty($this->session_id))
{
// this seems to be no longer needed? - #14971
//$this->session_create(ANONYMOUS);
}
// initiate environment ... since it won't be set at this stage
$this->setup();
// logout the user, banned users are unable to use the normal 'logout' link
if ($this->data['user_id'] != ANONYMOUS)
{
$this->session_kill();
}
// we show a login box here to allow founders accessing the board if banned by IP
if (defined('IN_LOGIN') && $this->data['user_id'] == ANONYMOUS)
{
global $phpEx;
$this->setup('ucp');
$this->data['is_registered'] = $this->data['is_bot'] = false;
// Set as a precaution to allow login_box() handling this case correctly as well as this function not being executed again.
define('IN_CHECK_BAN', 1);
login_box("index.$phpEx");
// The false here is needed, else the user is able to circumvent the ban.
$this->session_kill(false);
}
// ok, we catch the case of an empty session id for the anonymous user...
// this can happen if the user is logging in, banned by username and the login_box() being called "again".
if (empty($this->session_id) && defined('IN_CHECK_BAN'))
{
$this->session_create(ANONYMOUS);
}
// determine which message to output
$till_date = ($ban_row['ban_end']) ? $this->format_date($ban_row['ban_end']) : '';
$message = ($ban_row['ban_end']) ? 'BOARD_BAN_TIME' : 'BOARD_BAN_PERM';
$message = sprintf($this->lang[$message], $till_date, '', '');
$message .= ($ban_row['ban_give_reason']) ? '<br /><br />' . sprintf($this->lang['BOARD_BAN_REASON'], $ban_row['ban_give_reason']) : '';
$message .= '<br /><br /><em>' . $this->lang['BAN_TRIGGERED_BY_' . strtoupper($ban_triggered_by)] . '</em>';
// to circumvent session_begin returning a valid value and the check_ban() not called on second page view, we kill the session again
$this->session_kill(false);
// a very special case... we are within the cron script which is not supposed to print out the ban message... show blank page
if (defined('IN_CRON'))
{
garbage_collection();
exit_handler();
exit;
}
trigger_error($message);
}
return ($banned && $ban_row['ban_give_reason']) ? $ban_row['ban_give_reason'] : $banned;
}
// session stuff will not be needed as this occurs from a non-client session, but we need $user->setup it seems
if (empty($user->lang))
{
$user->setup();
}
$user->add_lang('ucp');
// get variables
/* $data = request_var('data', '', true);
if (!isset($_GET['username']))
{ */
$data = file_get_contents('php://input');
$data = explode('&&', $data);
$username = trim(htmlspecialchars(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $data[0]), ENT_COMPAT, 'UTF-8'));
$password = trim(htmlspecialchars(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $data[1]), ENT_COMPAT, 'UTF-8'));
/* }
else
{
$username = $_GET['username'];
$password = $_GET['password'];
} */
// perform login from $auth. we don't want autologon, viewonline nor admin access for the session
$result = $auth->login($username, $password, false, false, false);
if ($result['status'] == LOGIN_SUCCESS)
{
$userID = $user->data['user_id'];
$user_id = array($userID);
$canhave = get_profile_fields($user_id);
if ($canhave[$userID]['can_play_expire']['value'] <= time())
{
$canhave[$userID]['can_play']['value'] = 1;
}
if ($canhave[$userID]['can_play']['value'] == 1 || $canhave[$userID]['can_play']['value'] == 0 || $canhave[$userID]['can_play']['value'] == "")
{
$canPlay = true;
if (true || isGroup($user->data['user_id']))
{
$canPlay = true;
$keysql = "UPDATE phpbb_sessions SET session_onlineplay = 1, session_realip = '".htmlspecialchars(get_ip_address(), ENT_QUOTES)."' WHERE session_id = '".$user->session_id."';";
$keyresult = $db->sql_query($keysql);
$db->sql_freeresult($keyresult);
}
else
{
$result['status'] = 'nope';
$result['error_msg'] = 'triobit is currently down for maintenance.';
}
}
else
{
$result['status'] = 'nope';
//$result['error_msg'] = 'User is not allowed to play';
$result['error_msg'] = 'Online playing privileges revoked';
if ($canhave[$userID]['can_play_reason']['value'])
{
$result['error_msg'] .= ' - ' . str_replace('#', '#', $canhave[$userID]['can_play_reason']['value']);
}
if ($canhave[$userID]['can_play_expire']['value'])
{
$result['error_msg'] .= ' (will expire in ' . duration($canhave[$userID]['can_play_expire']['value'] - time()) . ')';
}
}
$banReason = check_ban($userID, '', '', 1);
if ($banReason != "")
{
$result['status'] = 'nope';
$result['error_msg'] = 'User is banned';
$canPlay = false;
}
}
// start buffering (to allow kill)
ob_start();
// output the results
echo (($result['status'] == LOGIN_SUCCESS) ? 'ok' : 'fail') . '#';
echo (($result['error_msg']) ? ((isset($user->lang[$result['error_msg']])) ? $user->lang[$result['error_msg']] : $result['error_msg']) : 'Success.') . '#';
echo (($result['status'] == LOGIN_SUCCESS) ? $user->data['user_id'] : '1') . '#';
echo (($result['status'] == LOGIN_SUCCESS) ? $user->data['username'] : 'Anonymous') . '#';
echo (($result['status'] == LOGIN_SUCCESS) ? $user->data['user_email'] : 'anonymous#example.com') . '#';
echo (($result['status'] == LOGIN_SUCCESS) ? $user->session_id : '0') . '#';
//Deleted, used for login verify now
// kill the session
if (!$canPlay)
{
$user->session_kill(false);
}
// and flush the contents
ob_end_flush();
exit;
function format_duration($seconds) {
$periods = array(
'centuries' => 3155692600,
'decades' => 315569260,
'years' => 31556926,
'months' => 2629743,
'weeks' => 604800,
'days' => 86400,
'hours' => 3600,
'minutes' => 60,
'seconds' => 1
);
$durations = array();
foreach ($periods as $period => $seconds_in_period) {
if ($seconds >= $seconds_in_period) {
$durations[$period] = floor($seconds / $seconds_in_period);
$seconds -= $durations[$period] * $seconds_in_period;
}
}
return $durations;
}
function duration($seconds) {
$data = format_duration($seconds);
$data2 = array();
foreach ($data as $unit => $amount)
{
$data2[] = $amount . ' ' . $unit;
}
return implode(', ', $data2);
}

BitTorrent: Download not starting

I am trying to implement a bittorrent tracker in Laravel. However, I am stuck at the moment as the download won't start. There is one peer which it appears to be seeding and I am 100% sure that it is connectable. But, when I run a second client on a different machine, the download won't start. It is stuck at "Connecting to peers" (uTorrent).
From the tracker I am sending the following response when the client makes an announce:
d8:intervali1000e12:min intervali300e5:peers18:�ؤ�i�ؑ�XÚJU�6e
In the downloading client I have the following data:
Here's my announce code:
<?php
namespace App\Http\Controllers\Announce;
use App\Helpers\BencodeHelper;
use App\Models\Peer;
use App\Models\PeerTorrent;
use App\Models\Torrent;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
class AnnounceController extends Controller
{
const __INTERVAL = 1000;
const __TIMEOUT = 120;
const __INTERVAL_MIN = 60;
const __MAX_PPR = 20;
public function announce(Request $request)
{
Log::info($request->fullUrl());
$status = 200;
$content = "";
$passkey = Input::get('passkey');
$peer_id = Input::get('peer_id');
$port = Input::get('port');
$info_hash = Input::get('info_hash');
$downloaded = Input::get('uploaded') ? intval(Input::get('uploaded')) : 0;
$uploaded = Input::get('uploaded') ? intval(Input::get('uploaded')) : 0;
$left = Input::get('left') ? intval(Input::get('left')) : 0;
$compact = Input::get('compact') ? intval(Input::get('compact')) : 0;
$no_peer_id = Input::get('no_peer_id') ? intval(Input::get('no_peer_id')) : 0;
$ipAddress = '';
// Check for X-Forwarded-For headers and use those if found
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && ('' !== trim($_SERVER['HTTP_X_FORWARDED_FOR']))) {
$ipAddress = (trim($_SERVER['HTTP_X_FORWARDED_FOR']));
} else {
if (isset($_SERVER['REMOTE_ADDR']) && ('' !== trim($_SERVER['REMOTE_ADDR']))) {
$ipAddress = (trim($_SERVER['REMOTE_ADDR']));
}
}
$port = $_SERVER['REMOTE_PORT'];
/*if(!$port || !ctype_digit($port) || intval($port) < 1 || intval($port) > 65535)
{
$content = BencodeHelper::track("Invalid client port.");
$status = 401;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
if ($port == 999 && substr($peer_id, 0, 10) == '-TO0001-XX') {
die("d8:completei0e10:incompletei0e8:intervali600e12:min intervali60e5:peersld2:ip12:72.14.194.184:port3:999ed2:ip11:72.14.194.14:port3:999ed2:ip12:72.14.194.654:port3:999eee");
}*/
if (!$passkey) {
$content = BencodeHelper::track("Missing passkey.");
$status = 401;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
$torrent = Torrent::getByInfoHash(sha1($info_hash));
if (!$torrent || $torrent == null) {
$content = "Torrent not registered with this tracker.";
$status = 404;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
$user = User::has('passkeys', '=', $passkey)->get();
if ($user == null) {
$content = BencodeHelper::track("Invalid passkey.");
$status = 401;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
$peer = Peer::getByHashAndPasskey(bin2hex($peer_id), $passkey);
if ($peer == null) {
$peer = Peer::create([
'hash' => bin2hex($peer_id),
'user_agent' => $_SERVER['HTTP_USER_AGENT'],
'ip_address' => $ipAddress,
'passkey' => $passkey,
'port' => $port
]);
}
if (!$info_hash || strlen($info_hash) != 20) {
$content = BencodeHelper::track("Invalid info_hash.");
$status = 401;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
$peer_torrent = PeerTorrent::getByPeerAndTorrent($peer, $torrent);
if ($peer_torrent == null) {
$peer_torrent = PeerTorrent::create([
'peer_id' => $peer->id,
'torrent_id' => $torrent->id,
'uploaded' => $uploaded,
'downloaded' => $downloaded,
'left' => $left,
'stopped' => false
]);
} else {
$peer_torrent->uploaded = $uploaded;
$peer_torrent->downloaded = $downloaded;
$peer_torrent->left = $left;
$peer_torrent->save();
}
$seeders = $torrent->getSeedersCount();
$leechers = $torrent->getLeechersCount();
$resp = "";
if ($compact != 1) {
$resp = "d" . $this->benc_str("interval") . "i" . AnnounceController::__INTERVAL . "e" . $this->benc_str("peers") . "l";
} else {
$resp = "d" . $this->benc_str("interval") . "i" . AnnounceController::__INTERVAL . "e" . $this->benc_str("min interval") . "i" . 300 . "e5:" . "peers";
}
$peer = array();
$peer_num = 0;
foreach ($torrent->getPeersArray() as $row) {
if ($compact != 1) {
if ($row["peer_id"] === $peer->hash) {
continue;
}
$resp .= "d" . $this->benc_str("ip") . $this->benc_str($row['ip']);
if ($no_peer_id == 0) {
$resp .= $this->benc_str("peer id") . $this->benc_str($row["peer_id"]);
}
$resp .= $this->benc_str("port") . "i" . $row["port"] . "e" . "e";
} else {
$peer_ip = explode('.', $row["ip"]);
$peer_ip = pack("C*", $peer_ip[0], $peer_ip[1], $peer_ip[2], $peer_ip[3]);
$peer_port = pack("n*", (int)$row["port"]);
$time = intval((time() % 7680) / 60);
if ($left == 0) {
$time += 128;
}
$time = pack("C", $time);
$peer[] = $time . $peer_ip . $peer_port;
$peer_num++;
}
}
if ($compact != 1) {
$resp .= "ee";
} else {
$o = "";
for ($i = 0; $i < $peer_num; $i++) {
$o .= substr($peer[$i], 1, 6);
}
$resp .= strlen($o) . ':' . $o . 'e';
}
$this->benc_resp_raw($resp);
}
public function benc_resp($d)
{
return $this->benc_resp_raw($this->benc(array('type' => 'dictionary', 'value' => $d)));
}
public function benc_resp_raw($x)
{
header("Content-Type: text/plain");
header("Pragma: no-cache");
if ($_SERVER['HTTP_ACCEPT_ENCODING'] == 'gzip') {
header("Content-Encoding: gzip");
echo gzencode($x, 9, FORCE_GZIP);
} else {
echo $x;
}
}
function benc($obj)
{
if (!is_array($obj) || !isset($obj["type"]) || !isset($obj["value"]))
return;
$c = $obj["value"];
switch ($obj["type"]) {
case "string":
return $this->benc_str($c);
case "integer":
return $this->benc_int($c);
case "list":
return $this->benc_list($c);
case "dictionary":
return $this->benc_dict($c);
default:
return;
}
}
public function benc_str($s)
{
return strlen($s) . ":$s";
}
public function benc_int($i)
{
return "i" . $i . "e";
}
public function benc_list($a)
{
$s = "l";
foreach ($a as $e) {
$s .= $this->benc($e);
}
$s .= "e";
return $s;
}
public function benc_dict($d)
{
$s = "d";
$keys = array_keys($d);
sort($keys);
foreach ($keys as $k) {
$v = $d[$k];
$s .= $this->benc_str($k);
$s .= $this->benc($v);
}
$s .= "e";
return $s;
}
public function hex2bin($hex)
{
$r = '';
for ($i = 0; $i < strlen($hex); $i += 2) {
$r .= chr(hexdec($hex{$i} . $hex{($i + 1)}));
}
return $r;
}
}
I am not quite sure what am I missing here.
Maybe it's because you constantly set
->header('Content-Type', $value);
without ever setting $value? So the "Announce-Response" is malformed?
$port = $_SERVER['REMOTE_PORT'];
I think the problem is that the tracker instead of register the port that the connecting peer sends in the announce string, the tracker register the remote port that the peer is connecting from.
That is almost certainly the wrong port to use.

Categories