Th3-822

[rapidleech][u] mega.co.nz_member.php

Dec 3rd, 2014
934
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 31.42 KB | None | 0 0
  1. <?php
  2. ######## Account Info ########
  3. /* Warning: Login uses a lot of CPU, make sure to upload at least 1 file in your account with this plugin for saving account data before adding it here.*/
  4. $upload_acc['mega_co_nz']['user'] = ''; //Set your email
  5. $upload_acc['mega_co_nz']['pass'] = ''; //Set your password
  6. ########################
  7.  
  8. $chunk_UL = false; // Set to true to upload only 1 encrypted chunk per request to mega. (Switch to true when you are getting many Data sending errors)
  9. $calcMacEachChunk = true; // Set to false for get the file's cbc-mac after upload. (Sv will read the file 2 times & too high cpu usage in short time)
  10.  
  11. $_GET['proxy'] = isset($_GET['proxy']) ? $_GET['proxy'] : '';
  12. $not_done = true;
  13. $T8 = array('seqno' => mt_rand(), 'sid' => '');
  14.  
  15. echo "<center>Mega.co.nz plugin by <b>Th3-822</b></center><br />\n"; // Please, do not remove or change this line contents. - Th3-822
  16. if (!extension_loaded('mcrypt') || !in_array('rijndael-128', mcrypt_list_algorithms(), true)) html_error("Mcrypt module isn't installed or it doesn't have support for the needed encryption.");
  17.  
  18. // OpenSSL is Much Faster (Only Works Since 5.4)
  19. if (version_compare(PHP_VERSION, '5.4.0', '>=') && extension_loaded('openssl') && in_array('aes-128-cbc', openssl_get_cipher_methods(), true)) {
  20.     function aes_cbc_encrypt($data, $key) {
  21.         $data = str_pad($data, 16 * ceil(strlen($data) / 16), "\0"); // OpenSSL needs this padded.
  22.         return openssl_encrypt($data, 'aes-128-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  23.     }
  24.     function aes_cbc_decrypt($data, $key) {
  25.         $data = str_pad($data, 16 * ceil(strlen($data) / 16), "\0"); // OpenSSL needs this padded.
  26.         return openssl_decrypt($data, 'aes-128-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  27.     }
  28. } else {
  29.     function aes_cbc_encrypt($data, $key) {
  30.         return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  31.     }
  32.     function aes_cbc_decrypt($data, $key) {
  33.         return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  34.     }
  35. }
  36.  
  37. if (!empty($upload_acc['mega_co_nz']['user']) && !empty($upload_acc['mega_co_nz']['pass'])) {
  38.     $default_acc = true;
  39.     $_REQUEST['T8']['up_login'] = $upload_acc['mega_co_nz']['user'];
  40.     $_REQUEST['T8']['up_pass'] = $upload_acc['mega_co_nz']['pass'];
  41.     $_REQUEST['action'] = 'Th3-822';
  42.     echo "<center><b>Using Default Login.</b></center><br />\n";
  43. } else $default_acc = false;
  44.  
  45. if (empty($_REQUEST['action']) || $_REQUEST['action'] != 'Th3-822') {
  46.     echo "<table border='0' style='width:270px;' cellspacing='0' align='center'>
  47.     <form method='POST'>
  48.     <input type='hidden' name='action' value='Th3-822' />
  49.     <tr><td style='white-space:nowrap;'>&nbsp;Email*</td><td>&nbsp;<input type='text' name='T8[up_login]' value='' style='width:160px;' /></td></tr>
  50.     <tr><td style='white-space:nowrap;'>&nbsp;Password*</td><td>&nbsp;<input type='password' name='T8[up_pass]' value='' style='width:160px;' /></td></tr>\n";
  51.     echo "<tr><td colspan='2' align='center'><br /><input type='submit' value='Upload' /></td></tr>\n";
  52.     echo "<tr><td colspan='2' align='center'><small>*You can set it as default in <b>".basename(__FILE__)."</b></small></td></tr>\n";
  53.     echo "</table>\n</form>\n";
  54.     echo "<p style='text-align:center'>Login step may last <b>1 minute or more with high CPU usage</b>, longer passwords will increase that time.<br /><small>After a correct login, session will be stored for skip the login step.</small></p>";
  55.     echo "<script type='text/javascript'>self.resizeTo(700,350);</script>\n"; //Resize upload window
  56. } else {
  57.     $login = $not_done = false;
  58.     $domain = 'mega.co.nz';
  59.  
  60.     // Login
  61.     echo "<table style='width:600px;margin:auto;'>\n<tr><td align='center'>\n<div id='login' width='100%' align='center'>Login to $domain</div>\n";
  62.  
  63.     if (!empty($_REQUEST['T8']['up_login']) && !empty($_REQUEST['T8']['up_pass'])) SavedLogin($_REQUEST['T8']['up_login'], $_REQUEST['T8']['up_pass']);
  64.     else html_error('Login Error: Email or Password empty.');
  65.  
  66.     // Retrive upload ID
  67.     echo "<script type='text/javascript'>document.getElementById('login').style.display='none';</script>\n<div id='info' width='100%' align='center'>Retrive upload url</div>\n";
  68.  
  69.     $ul_url = apiReq(array('a' => 'u', 's' => $fsize));
  70.     if (is_numeric($ul_url[0])) check_errors($ul_url[0], 'Error getting upload url');
  71.     $up_url = $ul_url[0]['p'];
  72.  
  73.     $ul_key = array();
  74.     for ($i = 0; $i < 6; $i++) $ul_key[] = get_rand(3);
  75.  
  76.     // Uploading
  77.     echo "<script type='text/javascript'>document.getElementById('info').style.display='none';</script>\n";
  78.  
  79.     $mac_str = '';
  80.     $upfiles = T8_mega_upload($up_url, $ul_key, $lfile, $lname, $mac_str);
  81.  
  82.     // Upload Finished
  83.     echo "<script type='text/javascript'>document.getElementById('progressblock').style.display='none';</script>\n";
  84.  
  85.     is_page($upfiles);
  86.  
  87.     if ($calcMacEachChunk) {
  88.         $file_mac = str_to_a32($mac_str);
  89.         mcrypt_generic_deinit($m_td1);
  90.         mcrypt_module_close($m_td1);
  91.         mcrypt_generic_deinit($m_td2);
  92.         mcrypt_module_close($m_td2);
  93.     } else $file_mac = FileMac($lfile, $fsize, a32_to_str(array_slice($ul_key, 0, 4)), a32_to_str(array($ul_key[4], $ul_key[5], $ul_key[4], $ul_key[5])));
  94.  
  95.     $body = substr($upfiles, strpos($upfiles, "\r\n\r\n") + 4);
  96.     if (is_numeric($body)) check_errors($body, 'Upload Error');
  97.  
  98.     $meta_mac = array($file_mac[0] ^ $file_mac[1], $file_mac[2] ^ $file_mac[3]);
  99.     $attributes = array('n' => basename($lname));
  100.     $enc_attributes = enc_attr($attributes, array_slice($ul_key, 0, 4));
  101.     $key = array($ul_key[0] ^ $ul_key[4], $ul_key[1] ^ $ul_key[5], $ul_key[2] ^ $meta_mac[0], $ul_key[3] ^ $meta_mac[1], $ul_key[4], $ul_key[5], $meta_mac[0], $meta_mac[1]);
  102.  
  103.     $file = apiReq(array('a' => 'p', 't' => $T8['root_id'], 'n' => array(array('h' => $body, 't' => 0, 'a' => base64url_encode($enc_attributes), 'k' => a32_to_base64(encrypt_key($key, $T8['master_key']))))));
  104.     if (is_numeric($file[0])) check_errors($file[0], 'Save file error');
  105.  
  106.     $public_handle = apiReq(array('a' => 'l', 'n' => $file[0]['f'][0]['h']));
  107.     if (is_numeric($public_handle[0])) check_errors($public_handle[0], 'Error getting public fileid');
  108.     $key = substr($file[0]['f'][0]['k'], strpos($file[0]['f'][0]['k'], ':'));
  109.     $decrypted_key = a32_to_base64(decrypt_key(base64_to_a32($key), $T8['master_key']));
  110.  
  111.     $download_link = "https://$domain/#!{$public_handle[0]}!$decrypted_key";
  112. }
  113.  
  114. // secure_rand() function from: http://www.zimuel.it/en/strong-cryptography-in-php/
  115. function secure_rand($length) {
  116.     if (function_exists('openssl_random_pseudo_bytes')) {
  117.         $rnd = openssl_random_pseudo_bytes($length, $strong);
  118.         if ($strong === TRUE) return $rnd;
  119.     }
  120.     $sha = $rnd = '';
  121.     if (file_exists('/dev/urandom')) {
  122.         $fp = fopen('/dev/urandom', 'rb');
  123.         if ($fp) {
  124.             if (function_exists('stream_set_read_buffer')) stream_set_read_buffer($fp, 0);
  125.             $sha = fread($fp, $length);
  126.             fclose($fp);
  127.         }
  128.     }
  129.     for ($i=0; $i<$length; $i++) {
  130.         $sha = hash('sha256',$sha.mt_rand());
  131.         $char = mt_rand(0,62);
  132.         $rnd .= chr(hexdec($sha[$char].$sha[$char+1]));
  133.     }
  134.     return $rnd;
  135. }
  136.  
  137. function get_rand($bytes) {
  138.     return hexdec(bin2hex(secure_rand($bytes)));
  139. }
  140. function Get_Reply($content) {
  141.     if (!function_exists('json_decode')) html_error('Error: Please enable JSON in php.');
  142.     if (($pos = strpos($content, "\r\n\r\n")) > 0) $content = substr($content, $pos + 4);
  143.     $cb_pos = strpos($content, '{');
  144.     $sb_pos = strpos($content, '[');
  145.     if ($cb_pos === false && $sb_pos === false) html_error('Json start braces not found.');
  146.     $sb = ($cb_pos === false || $sb_pos < $cb_pos) ? true : false;
  147.     $content = substr($content, strpos($content, ($sb ? '[' : '{')));$content = substr($content, 0, strrpos($content, ($sb ? ']' : '}')) + 1);
  148.     if (empty($content)) html_error('No json content.');
  149.     $rply = json_decode($content, true);
  150.     if (!$rply || count($rply) == 0) html_error('Error reading json.');
  151.     return $rply;
  152. }
  153. function apiReq($atrr) {
  154.     $try = 0;
  155.     do {
  156.         if ($try > 0) sleep(mt_rand(2,3));
  157.         $ret = doApiReq($atrr);
  158.         $try++;
  159.     } while ($try < 6 && $ret[0] == -3);
  160.     return $ret;
  161. }
  162. function doApiReq($atrr) {
  163.     global $T8;
  164.     $domain = 'g.api.mega.co.nz';//$domain = 'eu.api.mega.co.nz';
  165.     if (!function_exists('json_encode')) html_error('Error: Please enable JSON in php.');
  166.     $cURL = $GLOBALS['options']['use_curl'] && extension_loaded('curl') && function_exists('curl_init') && function_exists('curl_exec') ? true : false;
  167.     $chttps = false;
  168.     if ($cURL) {
  169.         $cV = curl_version();
  170.         if (in_array('https', $cV['protocols'], true)) $chttps = true;
  171.     }
  172.     if (!extension_loaded('openssl') && !$chttps) html_error('You need to install/enable PHP\'s OpenSSL extension to support HTTPS connections.');
  173.     elseif (!$chttps) $cURL = false;
  174.  
  175.     $sid = (!empty($T8['sid']) ? '&sid=' . $T8['sid'] : '');
  176.     $post = json_encode($atrr);
  177.     $referer = "https://mega.co.nz/\r\nContent-Type: application/json";
  178.     if ($cURL) $page = cURL("https://$domain/cs?id=" . ($T8['seqno']++) . $sid, 0, "[$post]", $referer);
  179.     else {
  180.         global $pauth;
  181.         $page = geturl($domain, 443, '/cs?id=' . ($T8['seqno']++) . $sid, $referer, 0, "[$post]", 0, 0, 0, 0, 'https');
  182.         is_page($page);
  183.     }
  184.     list ($header, $page) = array_map('trim', explode("\r\n\r\n", $page, 2));
  185.     if (is_numeric($page)) return array(intval($page));
  186.     if (in_array(intval(substr($header, 9, 3)), array(500, 503))) return array(-3); //  500 Server Too Busy
  187.     return Get_Reply($page);
  188. }
  189. function check_errors($err, $prefix = 'Error') {
  190.     $isLogin = (stripos($prefix, 'login') !== false);
  191.     switch ($err) {
  192.         default: $msg = '*No message for this error*';break;
  193.         case -1: $msg = 'An internal error has occurred';break;
  194.         case -2: $msg = 'You have passed invalid arguments to this command, your rapidleech is outdated?';break;
  195.         case -3: $msg = 'A temporary congestion or server malfunction prevented your request from being processed';break;
  196.         case -4: $msg = 'You have exceeded your command weight per time quota. Please wait a few seconds, then try again';break;
  197.         case -5: $msg = 'The upload has failed';break;
  198.         case -6: $msg = 'Too many concurrent IP addresses are accessing this upload target URL';break;
  199.         case -7: $msg = 'The upload file packet is out of range or not starting and ending on a chunk boundary';break;
  200.         case -8: $msg = 'The upload target URL you are trying to access has expired. Please request a fresh one';break;
  201.         case -9: $msg = ($isLogin ? 'Email/Password incorrect' : 'Resource not found or deleted');break;
  202.         case -11: $msg = 'Access violation';break;
  203.         case -13: $msg = ($isLogin ? 'Account not Activated yet' : 'Trying to access an incomplete file');break;
  204.         case -14: $msg = 'A decryption operation failed';break;
  205.         case -15: $msg = 'Invalid or expired user session, please relogin';break;
  206.         case -16: $msg = 'User blocked';break;
  207.         case -17: $msg = 'Request over quota';break;
  208.         case -18: $msg = 'Resource temporarily not available, please try again later';break;
  209.     }
  210.     html_error("$prefix: [$err] $msg.");
  211. }
  212.  
  213. // Using some functions from: http://julien-marchand.fr/blog/using-the-mega-api-with-php-examples/
  214. function base64url_encode($data) {
  215.     return strtr(rtrim(base64_encode($data), '='), '+/', '-_');//return strtr(base64_encode($data), '+/=', '-_,');
  216. }
  217. function base64url_decode($data) {
  218.     if (($s = (2 - strlen($data) * 3) % 4) < 2) $data .= substr(',,', $s);
  219.     return base64_decode(strtr($data, '-_,', '+/='));
  220. }
  221. function a32_to_str($hex) {
  222.     return call_user_func_array('pack', array_merge(array('N*'), $hex));
  223. }
  224. function a32_to_base64($a) {
  225.     return base64url_encode(a32_to_str($a));
  226. }
  227. function str_to_a32($b) {
  228.     // Add padding, we need a string with a length multiple of 4
  229.     $b = str_pad($b, 4 * ceil(strlen($b) / 4), "\0");
  230.     return array_values(unpack('N*', $b));
  231. }
  232. function base64_to_a32($s) {
  233.     return str_to_a32(base64url_decode($s));
  234. }
  235. function aes_cbc_encrypt_a32($data, $key) {
  236.     return str_to_a32(aes_cbc_encrypt(a32_to_str($data), a32_to_str($key)));
  237. }
  238. function aes_cbc_decrypt_a32($data, $key) {
  239.     return str_to_a32(aes_cbc_decrypt(a32_to_str($data), a32_to_str($key)));
  240. }
  241. function enc_attr($attr, $key) {
  242.     $attr = 'MEGA' . json_encode($attr);
  243.     return aes_cbc_encrypt($attr, a32_to_str($key));
  244. }
  245. function stringhash($s, $aeskey) {
  246.     $s32 = str_to_a32($s);
  247.     $h32 = array(0, 0, 0, 0);
  248.     for ($i = 0; $i < count($s32); $i++) $h32[$i % 4] ^= $s32[$i];
  249.     for ($i = 0; $i < 0x4000; $i++) $h32 = aes_cbc_encrypt_a32($h32, $aeskey);
  250.     return a32_to_base64(array($h32[0], $h32[2]));
  251. }
  252. function prepare_key($a) {
  253.     $pkey = array(0x93C467E3, 0x7DB0C7A4, 0xD1BE3F81, 0x0152CB56);
  254.     $count_a = count($a);
  255.     for ($r = 0; $r < 0x10000; $r++) {
  256.         for ($j = 0; $j < $count_a; $j += 4) {
  257.             $key = array(0, 0, 0, 0);
  258.             for ($i = 0; $i < 4; $i++) if ($i + $j < $count_a) $key[$i] = $a[$i + $j];
  259.             $pkey = aes_cbc_encrypt_a32($pkey, $key);
  260.         }
  261.     }
  262.     return $pkey;
  263. }
  264. function encrypt_key($a, $key) {
  265.     $x = array();
  266.     for ($i = 0; $i < count($a); $i += 4) $x = array_merge($x, aes_cbc_encrypt_a32(array_slice($a, $i, 4), $key));
  267.     return $x;
  268. }
  269. function decrypt_key($a, $key) {
  270.     $x = array();
  271.     for ($i = 0; $i < count($a); $i += 4) $x = array_merge($x, aes_cbc_decrypt_a32(array_slice($a, $i, 4), $key));
  272.     return $x;
  273. }
  274. function mpi2bc($s) {
  275.     $s = bin2hex(substr($s, 2));
  276.     $len = strlen($s);
  277.     $n = 0;
  278.     for ($i = 0; $i < $len; $i++) $n = bcadd($n, bcmul(hexdec($s[$i]), bcpow(16, $len - $i - 1)));
  279.     return $n;
  280. }
  281. function bin2int($str) {
  282.     $result = 0;
  283.     $n = strlen($str);
  284.     do {
  285.         $result = bcadd(bcmul($result, 256), ord($str[--$n]));
  286.     } while ($n > 0);
  287.     return $result;
  288. }
  289. function int2bin($num) {
  290.     $result = '';
  291.     do {
  292.         $result .= chr(bcmod($num, 256));
  293.         $num = bcdiv($num, 256);
  294.     } while (bccomp($num, 0));
  295.     return $result;
  296. }
  297. function bitOr($num1, $num2, $start_pos) {
  298.     $start_byte = intval($start_pos / 8);
  299.     $start_bit = $start_pos % 8;
  300.     $tmp1 = int2bin($num1);
  301.     $num2 = bcmul($num2, 1 << $start_bit);
  302.     $tmp2 = int2bin($num2);
  303.     if ($start_byte < strlen($tmp1)) {
  304.         $tmp2 |= substr($tmp1, $start_byte);
  305.         $tmp1 = substr($tmp1, 0, $start_byte) . $tmp2;
  306.     } else $tmp1 = str_pad($tmp1, $start_byte, "\0") . $tmp2;
  307.     return bin2int($tmp1);
  308. }
  309. function bitLen($num) {
  310.     $tmp = int2bin($num);
  311.     $bit_len = strlen($tmp) * 8;
  312.     $tmp = ord($tmp[strlen($tmp) - 1]);
  313.     if (!$tmp) $bit_len -= 8;
  314.     else while (!($tmp & 0x80)) {
  315.         $bit_len--;
  316.         $tmp <<= 1;
  317.     }
  318.     return $bit_len;
  319. }
  320. function rsa_decrypt($enc_data, $p, $q, $d) {
  321.     $enc_data = int2bin($enc_data);
  322.     $exp = $d;
  323.     $modulus = bcmul($p, $q);
  324.     $data_len = strlen($enc_data);
  325.     $chunk_len = bitLen($modulus) - 1;
  326.     $block_len = intval(ceil($chunk_len / 8));
  327.     $curr_pos = 0;
  328.     $bit_pos = 0;
  329.     $plain_data = 0;
  330.     while ($curr_pos < $data_len) {
  331.         $tmp = bin2int(substr($enc_data, $curr_pos, $block_len));
  332.         $tmp = bcpowmod($tmp, $exp, $modulus);
  333.         $plain_data = bitOr($plain_data, $tmp, $bit_pos);
  334.         $bit_pos += $chunk_len;
  335.         $curr_pos += $block_len;
  336.     }
  337.     return int2bin($plain_data);
  338. }
  339.  
  340. function getRootNode($files = 0) {
  341.     global $T8;
  342.     if (empty($files) || !is_array($files) || count($files) < 1) $files = apiReq(array('a' => 'f', 'c' => 1));
  343.     if (is_numeric($files[0])) check_errors($files[0], 'Cannot get Root folder ID');
  344.     foreach ($files[0]['f'] as $file) if ($file['t'] == 2) {
  345.         $T8['root_id'] = $file['h'];
  346.         break;
  347.     }
  348.     if (empty($T8['root_id'])) html_error('Root folder ID not found.');
  349. }
  350.  
  351. function getNextChunkLength($len) {
  352.     if ($len < 131072) return 131072;
  353.     elseif ($len < 262144) return 262144;
  354.     elseif ($len < 393216) return 393216;
  355.     elseif ($len < 524288) return 524288;
  356.     elseif ($len < 655360) return 655360;
  357.     elseif ($len < 786432) return 786432;
  358.     elseif ($len < 917504) return 917504;
  359.     else return 1048576;
  360. }
  361.  
  362. function calcChunkMac($data, $key, $iv) {
  363.     global $m_td1, $m_td2;
  364.     $size = strlen($data);
  365.     if ($size % 16 > 0) {
  366.         $data .= str_repeat("\0", (16 - $size % 16));
  367.         $size = strlen($data);
  368.     }
  369.  
  370.     $init = mcrypt_generic_init($m_td2, $key, $iv);
  371.     if ($init === false || $init < 0) html_error('Cannot init mcrypt');
  372.  
  373.     $size -= 16;
  374.     if ($size > 0) mcrypt_generic($m_td2, substr($data, 0, $size));
  375.     return mcrypt_generic($m_td1, mcrypt_generic($m_td2, substr($data, $size)));
  376. }
  377.  
  378. function FileMac($file, $fsize, $key, $iv) {
  379.     $fs = fopen($file, 'rb');
  380.     $csize = 131072;
  381.     $_data = '';
  382.     $readed = 0;
  383.     $m_td1 = mcrypt_module_open('rijndael-128', '', 'cbc', '');
  384.     $m_td2 = mcrypt_module_open('rijndael-128', '', 'cbc', '');
  385.     $init = mcrypt_generic_init($m_td1, $key, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  386.     if ($init === false || $init < 0) html_error('Cannot init mcrypt');
  387.     echo "\n<script type='text/javascript'>document.getElementById('T8').innerHTML = 'CBC-MAC File: 0 %';document.getElementById('T8').style.display = 'block';</script>";
  388.     while (!feof($fs)) {
  389.         $data = fread($fs, $csize);
  390.         if ($data === false) {
  391.             fclose($fs);
  392.             html_error(lang(112));
  393.         }
  394.         if ($_data !== '') {
  395.             $data = $_data . $data;
  396.             $_data = '';
  397.         }
  398.         if (strlen($data) < $csize && !feof($fs)) {
  399.             $_data .= $data;
  400.             continue;
  401.         }
  402.         if (strlen($data) > $csize) {
  403.             $_data .= substr($data, $csize);
  404.             $data = substr($data, 0, $csize);
  405.         }
  406.  
  407.         $readed += $size = strlen($data);
  408.         if ($size % 16 > 0) {
  409.             $data .= str_repeat("\0", (16 - $size % 16));
  410.             $size = strlen($data);
  411.         }
  412.  
  413.         $init = mcrypt_generic_init($m_td2, $key, $iv);
  414.         if ($init === false || $init < 0) html_error('Cannot init mcrypt');
  415.  
  416.         $size -= 16;
  417.         if ($size > 0) mcrypt_generic($m_td2, substr($data, 0, $size));
  418.         $mac_str = mcrypt_generic($m_td1, mcrypt_generic($m_td2, substr($data, $size)));
  419.  
  420.         if ($csize < 1048576) $csize = getNextChunkLength($csize);
  421.         echo "\n<script type='text/javascript'>document.getElementById('T8').innerHTML = 'CBC-MAC File: ".($readed < $fsize ? round($readed / $fsize * 100, 2) : '100')." %';</script>";
  422.         flush();
  423.     }
  424.     echo "\n<script type='text/javascript'>document.getElementById('T8').innerHTML = 'CBC-MAC File: 100 %';document.getElementById('T8').style.display = 'none';</script>";
  425.     mcrypt_generic_deinit($m_td1);
  426.     mcrypt_module_close($m_td1);
  427.     mcrypt_generic_deinit($m_td2);
  428.     mcrypt_module_close($m_td2);
  429.     fclose($fs);
  430.     return str_to_a32($mac_str);
  431. }
  432.  
  433. function Login($user, $pass) {
  434.     global $T8;
  435.     if (!extension_loaded('bcmath')) html_error('This plugin needs BCMath extension for login.');
  436.     $password_aes = prepare_key(str_to_a32($pass));
  437.     $T8['user_handle'] = stringhash($user, $password_aes);
  438.     $res = apiReq(array('a' => 'us', 'user' => $user, 'uh' => $T8['user_handle']));
  439.     if (is_numeric($res[0])) check_errors($res[0], 'Cannot login');
  440.     $T8['master_key'] = decrypt_key(base64_to_a32($res[0]['k']), $password_aes);
  441.     $privk = a32_to_str(decrypt_key(base64_to_a32($res[0]['privk']), $T8['master_key']));
  442.     $rsa_priv_key = array(0, 0, 0, 0);
  443.     for ($i = 0; $i < 4; $i++) {
  444.         $l = ((ord($privk[0]) * 256 + ord($privk[1]) + 7) / 8) + 2;
  445.         $rsa_priv_key[$i] = mpi2bc(substr($privk, 0, $l));
  446.         $privk = substr($privk, $l);
  447.     }
  448.     $T8['sid'] = rsa_decrypt(mpi2bc(base64url_decode($res[0]['csid'])), $rsa_priv_key[0], $rsa_priv_key[1], $rsa_priv_key[2]);
  449.     $T8['sid'] = base64url_encode(substr(strrev($T8['sid']), 0, 43));
  450.     getRootNode();
  451.     t8ArrToCookieArr($rsa_priv_key);
  452.  
  453.     $quota = apiReq(array('a' => 'uq', 'strg' => 1));
  454.     if (!is_array($quota[0])) check_errors($quota[0], 'Cannot get disk quota');
  455.     SaveCookies($user, $pass); // Update cookies file.
  456.     $cookie = '';
  457.     if (($quota[0]['mstrg'] - $quota[0]['cstrg']) < $GLOBALS['fsize']) html_error('Insufficient Free Space in Account for Upload this File.');
  458. }
  459.  
  460. function IWillNameItLater($cookie, $decrypt=true) {
  461.     if (!is_array($cookie)) {
  462.         if (!empty($cookie)) return $decrypt ? decrypt(urldecode($cookie)) : urlencode(encrypt($cookie));
  463.         return '';
  464.     }
  465.     if (count($cookie) < 1) return $cookie;
  466.     $keys = array_keys($cookie);
  467.     $values = array_values($cookie);
  468.     $keys = $decrypt ? array_map('decrypt', array_map('urldecode', $keys)) : array_map('urlencode', array_map('encrypt', $keys));
  469.     $values = $decrypt ? array_map('decrypt', array_map('urldecode', $values)) : array_map('urlencode', array_map('encrypt', $values));
  470.     return array_combine($keys, $values);
  471. }
  472.  
  473. function SavedLogin($user, $pass) {
  474.     global $T8, $cookie, $secretkey;
  475.     if (!defined('DOWNLOAD_DIR')) {
  476.         global $options;
  477.         if (substr($options['download_dir'], -1) != '/') $options['download_dir'] .= '/';
  478.         define('DOWNLOAD_DIR', (substr($options['download_dir'], 0, 6) == 'ftp://' ? '' : $options['download_dir']));
  479.     }
  480.  
  481.     $user = strtolower($user);
  482.     $filename = DOWNLOAD_DIR.basename('mega_ul.php');
  483.     if (!file_exists($filename) || filesize($filename) <= 6) return Login($user, $pass);
  484.  
  485.     $file = file($filename);
  486.     $savedcookies = unserialize($file[1]);
  487.     unset($file);
  488.  
  489.     $hash = hash('crc32b', $user.':'.$pass);
  490.     if (is_array($savedcookies) && array_key_exists($hash, $savedcookies)) {
  491.         $_secretkey = $secretkey;
  492.         $secretkey = hash('crc32b', $pass).sha1($user.':'.$pass).hash('crc32b', $user); // A 56 char key should be safer. :D
  493.         $cookie = (decrypt(urldecode($savedcookies[$hash]['enc'])) == 'OK') ? IWillNameItLater($savedcookies[$hash]['cookie']) : '';
  494.         $secretkey = $_secretkey;
  495.         if ((is_array($cookie) && count($cookie) < 1) || empty($cookie)) return Login($user, $pass);
  496.  
  497.         $T8['sid'] = $cookie['sid'];
  498.         $T8['user_handle'] = $cookie['user_handle'];
  499.         $T8['master_key'] = base64_to_a32($cookie['master_key']);
  500.         $T8['root_id'] = $cookie['root_id'];
  501.         $rsa_priv_key = explode('/T8\\', $cookie['rsa_priv_key']);
  502.  
  503.         $quota = apiReq(array('a' => 'uq', 'strg' => 1)); // I'm using the 'User quota details' request for validating the session id.
  504.         if (is_numeric($quota[0]) && $quota[0] < 0) {
  505.             if ($quota[0] == -15) { // Session code expired... We need to get a newer one.
  506.                 if (!extension_loaded('bcmath')) html_error('This plugin needs BCMath extension for login.');
  507.                 $T8['sid'] = false; // Do not send old sid or it will get '-15' error.
  508.                 $res = apiReq(array('a' => 'us', 'user' => $user, 'uh' => $T8['user_handle']));
  509.                 if (is_numeric($res[0])) check_errors($res[0], 'Cannot re-login');
  510.                 $T8['sid'] = rsa_decrypt(mpi2bc(base64url_decode($res[0]['csid'])), $rsa_priv_key[0], $rsa_priv_key[1], $rsa_priv_key[2]);
  511.                 $T8['sid'] = base64url_encode(substr(strrev($T8['sid']), 0, 43));
  512.                 t8ArrToCookieArr();
  513.             } else check_errors($quota[0], 'Cannot validate saved-login');
  514.         }
  515.         SaveCookies($user, $pass); // Update last used time.
  516.         $cookie = '';
  517.         if (($quota[0]['mstrg'] - $quota[0]['cstrg']) < $GLOBALS['fsize']) html_error('Insufficient Free Space in Account for Upload this File');
  518.         return;
  519.     }
  520.     return Login($user, $pass);
  521. }
  522.  
  523. function t8ArrToCookieArr($rsa_priv_key = 0) {
  524.     global $cookie, $T8;
  525.     if (empty($cookie) || !is_array($cookie)) $cookie = array();
  526.     $cookie['sid'] = $T8['sid'];
  527.     $cookie['user_handle'] = $T8['user_handle'];
  528.     $cookie['master_key'] = a32_to_base64($T8['master_key']);
  529.     $cookie['root_id'] = $T8['root_id'];
  530.     if (!empty($rsa_priv_key) && is_array($rsa_priv_key) && count($rsa_priv_key) > 2) $cookie['rsa_priv_key'] = implode('/T8\\', array_slice($rsa_priv_key, 0, 3)); // For decrypt the SID we need only the first 3 elements of the priv key, so we will only save those 3 elements.
  531. }
  532.  
  533. function SaveCookies($user, $pass) {
  534.     global $cookie, $secretkey;
  535.     $maxdays = 30; // Max days to keep cookies for more than 1 user.
  536.     $filename = DOWNLOAD_DIR.basename('mega_ul.php');
  537.     if (file_exists($filename) && filesize($filename) > 6) {
  538.         $file = file($filename);
  539.         $savedcookies = unserialize($file[1]);
  540.         unset($file);
  541.  
  542.         // Remove old cookies
  543.         if (is_array($savedcookies)) {
  544.             foreach ($savedcookies as $k => $v) if (time() - $v['time'] >= ($maxdays * 24 * 60 * 60)) unset($savedcookies[$k]);
  545.         } else $savedcookies = array();
  546.     } else $savedcookies = array();
  547.     $hash = hash('crc32b', $user.':'.$pass);
  548.     $_secretkey = $secretkey;
  549.     $secretkey = hash('crc32b', $pass).sha1($user.':'.$pass).hash('crc32b', $user); // A 56 char key should be safer. :D
  550.     $savedcookies[$hash] = array('time' => time(), 'enc' => urlencode(encrypt('OK')), 'cookie' => IWillNameItLater($cookie, false));
  551.     $secretkey = $_secretkey;
  552.  
  553.     write_file($filename, "<?php exit(); ?>\r\n" . serialize($savedcookies));
  554. }
  555.  
  556. function chunk_ul($scheme, $host, $port, $url, $onlyOpen = false) {
  557.     global $nn, $pauth, $fp, $errno, $errstr, $fsize, $pbChunkSize, $data, $zapros;
  558.     if ($scheme == 'https://') {
  559.         $scheme = 'tls://';
  560.         $port = 443;
  561.     }
  562.  
  563.     if (!empty($_GET['proxy'])) {
  564.         $proxy = true;
  565.         list($proxyHost, $proxyPort) = explode(':', $_GET['proxy'], 2);
  566.         $host = $host . ($port != 80 && ($scheme != 'tls://' || $port != 443) ? ':' . $port : '');
  567.         $url = $scheme . $host . $url;
  568.     } else $proxy = false;
  569.  
  570.     if ($scheme != 'tls://') $scheme = '';
  571.     $request = array();
  572.     $request[] = 'POST ' . str_replace(' ', '%20', $url) . ' HTTP/1.0';
  573.     $request[] = "Host: $host";
  574.     $request[] = 'User-Agent: '. (defined('rl_UserAgent') ? rl_UserAgent : 'Opera/9.80 (Windows NT 6.1) Presto/2.12.388 Version/12.17');
  575.     $request[] = 'Accept: */*';
  576.     $request[] = 'Accept-Language: en-US;q=0.7,en;q=0.3';
  577.     $request[] = 'Accept-Charset: utf-8,windows-1251;q=0.7,*;q=0.7';
  578.     $request[] = 'Content-Type: application/octet-stream';
  579.     $request[] = "Content-Length: ".($onlyOpen ? $fsize : strlen($data));
  580.     if ($proxy && !empty($pauth)) $request[] = "Proxy-Authorization: Basic $pauth\r\n";
  581.     $request[] = 'Connection: Close';
  582.  
  583.     $zapros = implode("\r\n", $request) . "\r\n\r\n";
  584.     $errno = 0; $errstr = '';
  585.     $posturl = (!empty($proxyHost) ? $scheme . $proxyHost : $scheme . $host) . ':' . (!empty($proxyPort) ? $proxyPort : $port);
  586.     $fp = @stream_socket_client($posturl, $errno, $errstr, 120, STREAM_CLIENT_CONNECT);
  587.  
  588.     if (!$fp) {
  589.         $dis_host = $proxy ? $proxyHost : $host;
  590.         $dis_port = $proxy ? $proxyPort : $port;
  591.         html_error(sprintf(lang(88), $dis_host, $dis_port));
  592.     } elseif ($errno || $errstr) html_error($errstr);
  593.  
  594.     if (!@fputs($fp, $zapros)) html_error('Cannot send request headers.');
  595.     fflush($fp);
  596.  
  597.     require_once(TEMPLATE_DIR . '/uploadui.php');
  598.     echo "\n<script type='text/javascript'>document.getElementById('ul_con').innerHTML ='".($proxy ? (sprintf(lang(89), $proxyHost, $proxyPort) . "<br />'UPLOAD: <b>$url</b>...<br />") : sprintf(lang(90), $host, $port))."';document.getElementById('ul_fname').style.display = 'block';</script>";
  599.     flush();
  600.  
  601.     if ($onlyOpen) return;
  602.     global $timeStart, $totalsend, $time, $lastChunkTime;
  603.     $dlen = strlen($data);
  604.     $sended = 0;
  605.     for ($s = 0; $s < ($dlen - 1); $s += $pbChunkSize) {
  606.         $chunk = ($pbChunkSize >= ($dlen - $s)) ? substr($data, $s) : substr($data, $s, $pbChunkSize);
  607.         $sendbyte = @fputs($fp, $chunk);
  608.         fflush($fp);
  609.  
  610.         if ($sendbyte === false || strlen($chunk) > $sendbyte) {
  611.             fclose($fp);
  612.             html_error(lang(113));
  613.         }
  614.  
  615.         $totalsend += $sendbyte;
  616.         $sended += $sendbyte;
  617.  
  618.         $time = getmicrotime() - $timeStart;
  619.         $chunkTime = $time - $lastChunkTime;
  620.         if (($s + $sendbyte) <= ($dlen - 1) && $chunkTime < 1) continue;
  621.         $chunkTime = (!($chunkTime < 0) && $chunkTime > 0) ? $chunkTime : 1;
  622.         $lastChunkTime = $time;
  623.         $speed = round($sended / 1024 / $chunkTime, 2);
  624.         $percent = round($totalsend / $fsize * 100, 2);
  625.         echo "<script type='text/javascript'>pr('$percent', '" . bytesToKbOrMbOrGb($totalsend) . "', '$speed');</script>\n";
  626.         flush();
  627.         $sended = 0;
  628.     }
  629.     if ($errno || $errstr) html_error($errstr);
  630.     fflush($fp);
  631.  
  632.     $page = '';
  633.     while (!feof($fp)) {
  634.         $data = fgets($fp, 16384);
  635.         if ($data === false) break;
  636.         $page .= $data;
  637.     }
  638.  
  639.     fclose($fp);
  640.     $body = substr($page, strpos($page, "\r\n\r\n") + 4);
  641.     if (is_numeric($body) && $body < 0) check_errors($body, 'Error while uploading chunk');
  642.     return $page;
  643. }
  644.  
  645. function T8_mega_upload($link, $ul_key, $file, $filename, &$mac_str = '') {
  646.     global $nn, $fp, $fs, $errno, $errstr, $fsize, $pbChunkSize, $T8, $chunk_UL, $calcMacEachChunk, $zapros;
  647.     $pbChunkSize = GetChunkSize($fsize);
  648.     $_link = parse_url($link);
  649.     $scheme = $_link['scheme'] . '://';
  650.     $host = $_link['host'];
  651.     $port = defport($_link);
  652.     $url = $_link['path']. (!empty($_link['query']) ? '?'.$_link['query'] : '');
  653.     unset($_link);
  654.     $key = a32_to_str(array_slice($ul_key, 0, 4));
  655.  
  656.     $_td = mcrypt_module_open('rijndael-128', '', 'ctr', '');
  657.     $init = mcrypt_generic_init($_td, $key, a32_to_str(array($ul_key[4], $ul_key[5], 0, 0)));
  658.     if ($init === false || $init < 0) html_error('Cannot init mcrypt');
  659.  
  660.     if (!is_readable($file)) html_error(sprintf(lang(65), $file));
  661.  
  662.     echo "\n<p id='ul_con'></p>\n<p id='ul_fname' style='display:none'>" . lang(104) . " <b>$filename</b>, " . lang(56) . ' <b>' . bytesToKbOrMbOrGb($fsize) . "</b>...<br /></p><p id='T8' style='display:none'></p>\n";
  663.     flush();
  664.  
  665.     if ($chunk_UL) global $chunkSize, $timeStart, $data, $totalsend, $time, $lastChunkTime;
  666.     else chunk_ul($scheme, $host, $port, $url, true);
  667.  
  668.     $fs = fopen($file, 'rb');
  669.     $chunkSize = 131072;
  670.     $totalsend = $time = $lastChunkTime = 0;
  671.     $_data = '';
  672.     if ($calcMacEachChunk) {
  673.         global $m_td1, $m_td2;
  674.         $m_td1 = mcrypt_module_open('rijndael-128', '', 'cbc', '');
  675.         $m_td2 = mcrypt_module_open('rijndael-128', '', 'cbc', '');
  676.         $init = mcrypt_generic_init($m_td1, $key, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  677.         if ($init === false || $init < 0) html_error('Cannot init mcrypt');
  678.         $c_mac = a32_to_str(array($ul_key[4], $ul_key[5], $ul_key[4], $ul_key[5]));
  679.     }
  680.  
  681.     $timeStart = microtime(true);
  682.  
  683.     while (!feof($fs) && !$errno && !$errstr) {
  684.         $data = fread($fs, $chunkSize);
  685.         if ($data === false) {
  686.             fclose($fs);
  687.             if (!$chunk_UL) fclose($fp);
  688.             html_error(lang(112));
  689.         }
  690.         if ($_data !== '') {
  691.             $data = $_data . $data;
  692.             $_data = '';
  693.         }
  694.         if (strlen($data) < $chunkSize && !feof($fs)) {
  695.             $_data .= $data;
  696.             continue;
  697.         }
  698.         if (strlen($data) > $chunkSize) {
  699.             $_data .= substr($data, $chunkSize);
  700.             $data = substr($data, 0, $chunkSize);
  701.         }
  702.         if ($calcMacEachChunk) $mac_str = calcChunkMac($data, $key, $c_mac);
  703.         if ($chunkSize < 1048576) $chunkSize = getNextChunkLength($chunkSize);
  704.  
  705.         $data = mcrypt_generic($_td, $data);
  706.         if ($chunk_UL) $page = chunk_ul($scheme, $host, $port, "$url/$totalsend-" . (($totalsend + strlen($data)) - 1));
  707.         else {
  708.             $dlen = strlen($data);
  709.             $sended = 0;
  710.             for ($s = 0; $s < ($dlen - 1); $s += $pbChunkSize) {
  711.                 $chunk = ($pbChunkSize >= ($dlen - $s)) ? substr($data, $s) : substr($data, $s, $pbChunkSize);
  712.                 $sendbyte = @fputs($fp, $chunk);
  713.                 fflush($fp);
  714.  
  715.                 if ($sendbyte === false || strlen($chunk) > $sendbyte) {
  716.                     fclose($fs);
  717.                     fclose($fp);
  718.                     html_error(lang(113));
  719.                 }
  720.  
  721.                 $totalsend += $sendbyte;
  722.                 $sended += $sendbyte;
  723.  
  724.                 $time = getmicrotime() - $timeStart;
  725.                 $chunkTime = $time - $lastChunkTime;
  726.                 if (($s + $sendbyte) <= ($dlen - 1) && $chunkTime < 1) continue;
  727.                 $chunkTime = (!($chunkTime < 0) && $chunkTime > 0) ? $chunkTime : 1;
  728.                 $lastChunkTime = $time;
  729.                 $speed = round($sended / 1024 / $chunkTime, 2);
  730.                 $percent = round($totalsend / $fsize * 100, 2);
  731.                 echo "<script type='text/javascript'>pr('$percent', '" . bytesToKbOrMbOrGb($totalsend) . "', '$speed');</script>\n";
  732.                 flush();
  733.                 $sended = 0;
  734.             }
  735.         }
  736.     }
  737.     mcrypt_generic_deinit($_td);
  738.     mcrypt_module_close($_td);
  739.     if ($errno || $errstr) {
  740.         $lastError = $errstr;
  741.         return false;
  742.     }
  743.  
  744.     if (!$chunk_UL) {
  745.         fflush($fp);
  746.         $page = '';
  747.         while (!feof($fp)) {
  748.             $data = fgets($fp, 16384);
  749.             if ($data === false) break;
  750.             $page .= $data;
  751.         }
  752.         fclose($fp);
  753.     }
  754.     fclose($fs);
  755.     return $page;
  756. }
  757.  
  758. //[23-7-2013] Written by Th3-822.
  759. //[30-1-2014] Ephemeral account support removed, mega is not allowing anon users to generate public links. - Th3-822
  760. //[15-4-2014] Fixed re-login error. - Th3-822
  761. //[19-5-2016] Using OpenSSL where is possible for better login speed & Added free space check. - Th3-822
Add Comment
Please, Sign In to add comment