function __construct($password = NULL, $host = "127.0.0.1", $port = 11234) { $this->socket = stream_socket_client("udp://" . $host . ":" . $port, $errorno, $errorstr); if (!$this->socket) { die("Failed to connect, Error #{$errorno}: {$errorstr}"); } fwrite($this->socket, bencode(array("q" => "ping"))); // Try to ping it $returndata = fread($this->socket, $this->buffersize); if ($returndata != "d1:q4:ponge") { die("Looks like {$host}:{$port} isn't a cjdns admin port"); } $this->password = $password; $page = 0; while (True) { $request = array("q" => "Admin_availableFunctions", "args" => array("page" => $page)); fwrite($this->socket, bencode($request)); $result = bdecode(fread($this->socket, $this->buffersize)); foreach ($result['availableFunctions'] as $function => $description) { $this->functions[$function] = $description; } if (isset($result['more'])) { $page++; } else { break; } } }
/** * Bencode snippet from http://paste.lisp.org/display/17178 */ function bencode($element) { $out = ""; if (is_numeric($element) && $element == intval($element)) { $out = 'i' . $element . 'e'; } else { if (is_string($element)) { $out = strlen($element) . ':' . $element; } else { if (is_array($element) || is_object($element) && ($element = get_object_vars($element))) { ksort($element); if (is_string(key($element))) { $out = 'd'; foreach ($element as $key => $val) { $out .= bencode($key) . bencode($val); } $out .= 'e'; } else { $out = 'l'; foreach ($element as $val) { $out .= bencode($val); } $out .= 'e'; } } } } return $out; }
function bencode(&$d) { if (is_array($d)) { $ret = "d"; ksort($d, SORT_STRING); foreach ($d as $key => $value) { if (is_array($d)) { // skip the isDct element, only if it's set by us if ($key == "isDct") { continue; } $ret .= strlen($key) . ":" . $key; } if (is_int($value) || is_float($value)) { $ret .= "i{$value}e"; } else { if (is_string($value)) { $ret .= strlen($value) . ":" . $value; } else { $ret .= bencode($value); } } } return $ret . "e"; } elseif (is_string($d)) { // fallback if we're given a single bencoded string or int return strlen($d) . ":" . $d; } elseif (is_int($d) || is_float($d)) { return "i{$d}e"; } else { return null; } }
static function Encode($data, $tempChar = null) { $res = bencode($data, $tempChar); if ($res === null) { throw new EBEncode(null, 'Cannot encode bencoded data of type ' . gettype($data) . '.'); } return $res; }
function msg_die($msg) { if (DBG_LOG) { dbg_log(' ', '!die-' . clean_filename($msg)); } $output = bencode(array('min interval' => (int) 1800, 'failure reason' => (string) $msg, 'warning message' => (string) $msg)); die($output); }
function error_exit($msg = '') { if (DBG_LOG) { dbg_log(' ', '!err-' . clean_filename($msg)); } silent_exit(); echo bencode(array('failure reason' => str_compact($msg))); tracker_exit(); }
} stderr($language["ERROR"], $language["ERR_MOVING_TORR"]); } // try to chmod new moved file, on some server chmod without this could result 600, seems to be php bug @chmod($TORRENTSDIR . "/" . $hash . ".btf", 0766); // gold/silver torrent do_sqlquery("UPDATE {$TABLE_PREFIX}files SET gold='{$gold}' WHERE info_hash=\"{$hash}\""); // if ($announce!=$BASEURL."/announce.php") if (!in_array($announce, $TRACKER_ANNOUNCEURLS)) { require_once "./include/getscrape.php"; scrape($announce, $hash); $status = 2; write_log("Uploaded new torrent {$filename} - EXT ({$hash})", "add"); } else { if ($DHT_PRIVATE) { $alltorrent = bencode($array); $fd = fopen($TORRENTSDIR . "/" . $hash . ".btf", "rb+"); fwrite($fd, $alltorrent); fclose($fd); } // with pid system active or private flag (dht disabled), tell the user to download the new torrent write_log("Uploaded new torrent {$filename} ({$hash})", "add"); $status = 1; } // Announce new Uploaded torrents in ShoutBoX start global $BASEURL; do_sqlquery("INSERT INTO {$TABLE_PREFIX}chat (uid, time, name, text) VALUES (0," . time() . ", 'System','[color=red]NEW TORRENT[/color]: [url={$BASEURL}/index.php?page=torrent-details&id={$hash}]" . $filename . "[/url]')"); // Announce new Uploaded torrents in ShoutBoX ends } else { err_msg($language["ERROR"], $language["ERR_ALREADY_EXIST"]); unlink($_FILES["torrent"]["tmp_name"]);
$hashes[] = urldecode(substr($request_var, 10)); } } if (count($hashes[0]) == 0) { bt_message('Please supply an info_hash', BITTORRENT_MESSAGE_ERROR); } foreach ($hashes as $info_hash) { $info_hash; $valid = db_result(db_query("SELECT nid FROM {bt_torrents} WHERE info_hash = %b", $info_hash)); if ($valid) { if (variable_get('bt_tracker_scrape_scope', 0) == 0) { $response['files'][$info_hash] = db_fetch_array(db_query("SELECT bt.seeders AS complete, bt.leechers AS incomplete, bt.downloaded FROM {bt_torrents} bt WHERE bt.info_hash = %b", $info_hash)); } else { $response['files'][$info_hash]['complete'] = db_result(db_query("SELECT COUNT(btau.ip) FROM {bt_tracker_active_users} btau WHERE btau.bytes_left = 0 AND btau.info_hash = %b", $info_hash)); $response['files'][$info_hash]['incomplete'] = db_result(db_query("SELECT COUNT(btau.ip) FROM {bt_tracker_active_users} btau WHERE (NOT btau.bytes_left = 0) AND btau.info_hash = %b", $info_hash)); $response['files'][$info_hash]['completed'] = db_result(db_query("SELECT bt.downloaded FROM {bt_torrents} bt WHERE bt.info_hash = %b", $info_hash)); } $struct = strip_excess(bdecode(db_result(db_query('SELECT metadata FROM {bt_torrents} WHERE info_hash = %b', $info_hash)))); $response['files'][$info_hash]['name'] = $struct['info']['name']; } } if (count($response['files']) == 0) { bt_message('Invalid info hash(s)', BITTORRENT_MESSAGE_ERROR); } $response['flags'] = array(); $response['flags']['min_request_interval'] = variable_get('bt_tracker_scrape_interval', 900); bencode_response_raw(bencode($response)); } else { // Let the client know that the tracker is offline. bt_message('Tracker is Offline', BITTORRENT_MESSAGE_ERROR); }
} // Retrieve peers $peers = $compact_mode ? '' : array(); $sel_peer_id = $compact_mode || $no_peer_id_mode ? '' : ', peer_id '; $sql = "SELECT ip, port {$sel_peer_id}\r\n\tFROM " . BT_TRACKER_TABLE . "\r\n\tWHERE torrent_id = {$torrent_id}\r\n\t\tAND expire_time > {$current_time}\r\n\tORDER BY RAND()\r\n\tLIMIT {$numwant}"; if (!($result = $db->sql_query($sql))) { error_exit('DB error', __FILE__, __LINE__, 'db'); } if ($rowset = @$db->sql_fetchrowset($result)) { if ($compact_mode) { foreach ($rowset as $i => $peer) { $peers .= pack('Nn', ip2long(decode_ip($peer['ip'])), $peer['port']); } } else { if ($no_peer_id_mode) { foreach ($rowset as $i => $peer) { $peers[] = array('ip' => decode_ip($peer['ip']), 'port' => intval($peer['port'])); } } else { foreach ($rowset as $i => $peer) { $peers[] = array('ip' => decode_ip($peer['ip']), 'port' => intval($peer['port']), 'peer id' => $peer['peer_id']); } } } } // Return data to client $output['interval'] = intval($announce_interval); //$output['private'] = intval(1); $output['peers'] = $peers; echo bencode($output); send_data_to_client();
function dummy_exit($interval = 1800) { $output = bencode(array('interval' => (int) $interval, 'min interval' => (int) $interval, 'peers' => (string) DUMMY_PEER)); die($output); }
} else { @ini_set('memory_limit', '512M'); @ini_set('max_execution_time', @ini_get('max_execution_time') + 1200); $torrents_count = (int) get_count(BB_BT_TORRENTS, 'attach_id'); $loops = (int) ceil($torrents_count / C_TORRENTS_PER_ONCE); $not_exist = array(); $attach_dir = get_attachments_dir() . '/'; for ($i = 0; $i < $loops; $i++) { $start = $i * C_TORRENTS_PER_ONCE; $offset = C_TORRENTS_PER_ONCE; $sql = "SELECT\n\t\t\t\ttor.attach_id, tor.topic_id, ad.physical_filename\n\t\t\tFROM " . BB_BT_TORRENTS . " tor\n\t\t\tLEFT JOIN " . BB_ATTACHMENTS_DESC . " ad ON(ad.attach_id = tor.attach_id)\n\t\t\tORDER BY tor.attach_id\n\t\t\tLIMIT {$start}, {$offset}"; $torrents = DB()->fetch_rowset($sql); DB()->sql_freeresult(); foreach ($torrents as $torrent) { $filename = $attach_dir . $torrent['physical_filename']; if (!file_exists($filename)) { $not_exist[] = '<a href="viewtopic.php?t=' . $torrent['topic_id'] . '">' . $filename . '</a>'; } else { $tor = bdecode_file($filename); $info = !empty($tor['info']) ? $tor['info'] : array(); $info_hash = pack('H*', sha1(bencode($info))); $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); DB()->query("UPDATE " . BB_BT_TORRENTS . "\n\t\t\t\t\t\tSET info_hash = '{$info_hash_sql}'\n\t\t\t\t\t\tWHERE attach_id = {$torrent['attach_id']}"); } } } print_ok("Completed"); if (!empty($not_exist)) { print_ok("These torrents doesn't exist in filesystem: " . implode(', ', array_unique($not_exist))); } }
function convert_torrent($torrent) { $topic_data = array("topic_id" => $torrent['topic_id'], "forum_id" => $torrent['category'], "topic_title" => $torrent['name'], "topic_poster" => $torrent['owner'], "topic_time" => $torrent['added'], "topic_views" => $torrent['views'], "topic_type" => $torrent['sticky'] == 'yes' ? 1 : 0, "topic_first_post_id" => $torrent['id'], "topic_last_post_id" => $torrent['id'], "topic_attachment" => 1, "topic_dl_type" => 1, "topic_last_post_time" => $torrent['added']); tp_add_topic($topic_data); $post_text = stripslashes(prepare_message(addslashes(unprepare_message($torrent['descr'])), true, true)); $post_data = array("posts" => array("post_id" => $torrent['post_id'], "topic_id" => $torrent['topic_id'], "forum_id" => $torrent['category'], "poster_id" => $torrent['owner'], "post_time" => $torrent['added'], "post_attachment" => 1), "posts_text" => array("post_id" => $torrent['post_id'], "post_text" => $post_text), "posts_search" => array("post_id" => $torrent['post_id'], "search_words" => $torrent['search_text'])); tp_add_post($post_data); $attach_data = array("attachments" => array("attach_id" => $torrent['attach_id'], "post_id" => $torrent['post_id'], "user_id_1" => $torrent['owner']), "attachments_desc" => array("attach_id" => $torrent['attach_id'], "physical_filename" => $torrent['id'] . ".torrent", "real_filename" => $torrent['filename'], "extension" => "torrent", "mimetype" => "application/x-bittorrent", "filesize" => @filesize(get_attachments_dir() . '/' . $torrent['id'] . ".torrent"), "filetime" => $torrent['added'], "tracker_status" => 1)); tp_add_attach($attach_data); //Torrents if (BDECODE) { $filename = get_attachments_dir() . '/' . $torrent['id'] . ".torrent"; if (!file_exists($filename)) { return; } if (!function_exists('bdecode_file')) { include_once './includes/functions_torrent.php'; } $tor = bdecode_file($filename); $info = $tor['info'] ? $tor['info'] : array(); $info_hash = pack('H*', sha1(bencode($info))); $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); } else { $info_hash_sql = hex2bin($torrent['info_hash']); } $torrent_data = array("info_hash" => $info_hash_sql, "post_id" => $torrent['post_id'], "poster_id" => $torrent['owner'], "topic_id" => $torrent['topic_id'], "forum_id" => $torrent['category'], "attach_id" => $torrent['attach_id'], "size" => $torrent['size'], "reg_time" => $torrent['added'], "complete_count" => $torrent['times_completed'], "seeder_last_seen" => $torrent['lastseed']); $columns = $values = array(); foreach ($torrent_data as $column => $value) { $columns[] = $column; $values[] = "'" . DB()->escape($value) . "'"; } $sql_columns = implode(', ', $columns); $sql_values = implode(', ', $values); DB()->query("INSERT IGNORE INTO " . BB_BT_TORRENTS . " ({$sql_columns}) VALUES({$sql_values});"); return; }
function bencode($var) { if (is_int($var)) { return 'i' . $var . 'e'; } else { if (is_float($var)) { return 'i' . sprintf('%.0f', $var) . 'e'; } else { if (is_array($var)) { if (count($var) == 0) { return 'de'; } else { $assoc = false; foreach ($var as $key => $val) { if (!is_int($key) && !is_float($var)) { $assoc = true; break; } } if ($assoc) { ksort($var, SORT_REGULAR); $ret = 'd'; foreach ($var as $key => $val) { $ret .= bencode($key) . bencode($val); } return $ret . 'e'; } else { $ret = 'l'; foreach ($var as $val) { $ret .= bencode($val); } return $ret . 'e'; } } } else { return strlen($var) . ':' . $var; } } } }
function send_torrent_with_passkey($filename) { global $attachment, $auth_pages, $userdata, $bb_cfg, $tr_cfg, $lang; if (!$bb_cfg['bt_add_auth_key'] || $attachment['extension'] !== TORRENT_EXT || !($size = @filesize($filename))) { return; } $post_id = $poster_id = $passkey_val = ''; $user_id = $userdata['user_id']; $attach_id = $attachment['attach_id']; if (!($passkey_key = $bb_cfg['passkey_key'])) { bb_die('Could not add passkey (wrong config $bb_cfg[\'passkey_key\'])'); } // Get $post_id & $poster_id foreach ($auth_pages as $rid => $row) { if ($row['attach_id'] == $attach_id) { $post_id = $row['post_id']; $poster_id = $row['user_id_1']; break; } } // Get $topic_id $topic_id_sql = 'SELECT topic_id FROM ' . BB_POSTS . ' WHERE post_id = ' . (int) $post_id; if (!($topic_id_result = DB()->sql_query($topic_id_sql))) { bb_die('Could not query post information'); } $topic_id_row = DB()->sql_fetchrow($topic_id_result); $topic_id = $topic_id_row['topic_id']; if (!$attachment['tracker_status']) { bb_die($lang['PASSKEY_ERR_TOR_NOT_REG']); } if (bf($userdata['user_opt'], 'user_opt', 'dis_passkey') && !IS_GUEST) { bb_die('Could not add passkey'); } if ($bt_userdata = get_bt_userdata($user_id)) { $passkey_val = $bt_userdata['auth_key']; } if (!$passkey_val) { if (!($passkey_val = generate_passkey($user_id))) { bb_simple_die('Could not generate passkey'); } elseif ($bb_cfg['ocelot']['enabled']) { ocelot_update_tracker('add_user', array('id' => $user_id, 'passkey' => $passkey_val)); } } // Ratio limits $min_ratio = $bb_cfg['bt_min_ratio_allow_dl_tor']; if ($min_ratio && $user_id != $poster_id && ($user_ratio = get_bt_ratio($bt_userdata)) !== null) { if ($user_ratio < $min_ratio && $post_id) { $dl = DB()->fetch_row("\n\t\t\t\tSELECT dl.user_status\n\t\t\t\tFROM " . BB_POSTS . " p\n\t\t\t\tLEFT JOIN " . BB_BT_DLSTATUS . " dl ON dl.topic_id = p.topic_id AND dl.user_id = {$user_id}\n\t\t\t\tWHERE p.post_id = {$post_id}\n\t\t\t\tLIMIT 1\n\t\t\t"); if (!isset($dl['user_status']) || $dl['user_status'] != DL_STATUS_COMPLETE) { bb_die(sprintf($lang['BT_LOW_RATIO_FOR_DL'], round($user_ratio, 2), "search.php?dlu={$user_id}&dlc=1")); } } } // Announce URL $ann_url = $bb_cfg['bt_announce_url']; if (!($tor = bdecode_file($filename))) { bb_die('This is not a bencoded file'); } $announce = $bb_cfg['ocelot']['enabled'] ? strval($bb_cfg['ocelot']['url'] . $passkey_val . "/announce") : strval($ann_url . "?{$passkey_key}={$passkey_val}"); // Replace original announce url with tracker default if ($bb_cfg['bt_replace_ann_url'] || !isset($tor['announce'])) { $tor['announce'] = $announce; } // Delete all additional urls if ($bb_cfg['bt_del_addit_ann_urls'] || $bb_cfg['bt_disable_dht']) { unset($tor['announce-list']); } elseif (isset($tor['announce-list'])) { $tor['announce-list'] = array_merge($tor['announce-list'], array(array($announce))); } // Add retracker if (isset($tr_cfg['retracker']) && $tr_cfg['retracker']) { if (bf($userdata['user_opt'], 'user_opt', 'user_retracker') || IS_GUEST) { if (!isset($tor['announce-list'])) { $tor['announce-list'] = array(array($announce), array($tr_cfg['retracker_host'])); } else { $tor['announce-list'] = array_merge($tor['announce-list'], array(array($tr_cfg['retracker_host']))); } } } // Add publisher & topic url $publisher_name = $bb_cfg['server_name']; $publisher_url = make_url(TOPIC_URL . $topic_id); $tor['publisher'] = strval($publisher_name); unset($tor['publisher.utf-8']); $tor['publisher-url'] = strval($publisher_url); unset($tor['publisher-url.utf-8']); $tor['comment'] = strval($publisher_url); unset($tor['comment.utf-8']); // Send torrent $output = bencode($tor); $dl_fname = $bb_cfg['torrent_name_style'] ? '[' . $bb_cfg['server_name'] . '].t' . $topic_id . '.torrent' : clean_filename(basename($attachment['real_filename'])); if (!empty($_COOKIE['explain'])) { $out = "attach path: {$filename}<br /><br />"; $tor['info']['pieces'] = '[...] ' . strlen($tor['info']['pieces']) . ' bytes'; $out .= print_r($tor, true); bb_die("<pre>{$out}</pre>"); } header("Content-Type: application/x-bittorrent; name=\"{$dl_fname}\""); header("Content-Disposition: attachment; filename=\"{$dl_fname}\""); bb_exit($output); }