Jump to content

[SOLVED] New Error 500 on script


applovr

Recommended Posts

Hi everyone,

 

Glad to see that there is another php forum for us stupid newbies :P

 

Here's my problem. I know what usually causes an error 500, but this seems like an exception.

 

I am running a small torrent tracker community for music freaks, and until we got about 70 users, the upload worked fine. Then it just suddenly stopped. I don't know if this could be related to the users at all (I HIGHLY doubt it), but I don't know where else to look.

 

Here's the relevant page:

<?php
require_once("include/benc.php");
require_once("include/bittorrent.php");
ini_set("upload_max_filesize" ,"$max_torrent_size");

function bark($msg) {
genbark($msg, "Upload failed!");
}
dbconn(); 
loggedinorreturn();
iplogger ();
maxsysop ();

if ($CURUSER["uploadpos"] == 'no')
die;

foreach(explode(":","descr:type:name") as $v) {
if (!isset($_POST[$v]))
	bark("missing form data");
}

if (!isset($_FILES["file"]))
bark("missing form data");

$f = $_FILES["file"];
$fname = unesc($f["name"]);
if (empty($fname))
    bark("Empty filename!");
if ($_POST['uplver'] == 'yes') {
$anonymous = "yes";
$anon = "Anonymous";
}
else {
$anonymous = "no";
$anon = $CURUSER["username"];
}

$nfofile = $_FILES['nfo'];
if ($nfofile['name'] != '') {

if ($nfofile['size'] == 0)
bark("0-byte NFO");

if ($nfofile['size'] > 65535000000000)
bark("NFO is too big! Max 65,535 bytes.");

$nfofilename = $nfofile['tmp_name'];

if (@!is_uploaded_file($nfofilename))
bark("NFO upload failed");
}

$descr = unesc($_POST["descr"]);
if (!$descr)
  bark("You must enter a description!");

$catid = (0 + $_POST["type"]);
if (!is_valid_id($catid))
bark("You must select a category to put the torrent in!");

if (!validfilename($fname))
bark("Invalid filename!");
if (!preg_match('/^(.+)\.torrent$/si', $fname, $matches))
bark("Invalid filename (not a .torrent).");
$shortfname = $torrent = $matches[1];
if (!empty($_POST["name"]))
$torrent = unesc($_POST["name"]);

$tmpname = $f["tmp_name"];
if (!is_uploaded_file($tmpname))
bark("eek");
if (!filesize($tmpname))
bark("Empty file!");

$dict = bdec_file($tmpname, $max_torrent_size);
if (!isset($dict))
bark("What did you upload? This is not an encoded file!");

function dict_check($d, $s) {
if ($d["type"] != "dictionary")
	bark("not a dictionary");
$a = explode(":", $s);
$dd = $d["value"];
$ret = array();
foreach ($a as $k) {
	unset($t);
	if (preg_match('/^(.*)\((.*)\)$/', $k, $m)) {
		$k = $m[1];
		$t = $m[2];
	}
	if (!isset($dd[$k]))
		bark("dictionary is missing key(s)");
	if (isset($t)) {
		if ($dd[$k]["type"] != $t)
			bark("invalid entry in dictionary");
		$ret[] = $dd[$k]["value"];
	}
	else
		$ret[] = $dd[$k];
}
return $ret;
}

function dict_get($d, $k, $t) {
if ($d["type"] != "dictionary")
	bark("not a dictionary");
$dd = $d["value"];
if (!isset($dd[$k]))
	return;
$v = $dd[$k];
if ($v["type"] != $t)
	bark("invalid dictionary entry type");
return $v["value"];
}

list($ann, $info) = dict_check($dict, "announce(string):info");
list($dname, $plen, $pieces) = dict_check($info, "name(string):piece length(integer):pieces(string)");

if (!in_array($ann, $announce_urls, 1))
{
$aok=false;
foreach($announce_urls as $au)
{
	if($ann=="$au?passkey=$CURUSER[passkey]")  $aok=true;
}
if(!$aok)
	bark("Invalid announce url! Must be: " . $announce_urls[0] . "?passkey=$CURUSER[passkey]");
}

if (strlen($pieces) % 20 != 0)
bark("invalid pieces");

$filelist = array();
$totallen = dict_get($info, "length", "integer");
if (isset($totallen)) {
$filelist[] = array($dname, $totallen);
$type = "single";
}
else {
$flist = dict_get($info, "files", "list");
if (!isset($flist))
	bark("missing both length and files");
if (!count($flist))
	bark("no files");
$totallen = 0;
foreach ($flist as $fn) {
	list($ll, $ff) = dict_check($fn, "length(integer):path(list)");
	$totallen += $ll;
	$ffa = array();
	foreach ($ff as $ffe) {
		if ($ffe["type"] != "string")
			bark("filename error");
		$ffa[] = $ffe["value"];
	}
	if (!count($ffa))
		bark("filename error");
	$ffe = implode("/", $ffa);
	$filelist[] = array($ffe, $ll);
}
$type = "multi";
}

$infohash = pack("H*", sha1($info["string"]));

// Replace punctuation characters with spaces

$torrent = str_replace("_", " ", $torrent);

$nfo = sqlesc(str_replace("\x0d\x0d\x0a", "\x0d\x0a", @file_get_contents($nfofilename)));

$ret = sql_query("INSERT INTO torrents (search_text, filename, owner, visible, anonymous, info_hash, name, size, numfiles, type, descr, ori_descr, category, save_as, added, last_action, nfo) VALUES (" .
	implode(",", array_map("sqlesc", array(searchfield("$shortfname $dname $torrent"), $fname, $CURUSER["id"], "no", $anonymous, $infohash, $torrent, $totallen, count($filelist), $type, $descr, $descr, 0 + $_POST["type"], $dname))) .
	", '" . get_date_time() . "', '" . get_date_time() . "', $nfo)");
if (!$ret) {
if (mysql_errno() == 1062)
	bark("torrent already uploaded!");
bark("mysql puked: ".mysql_error());
}
$id = mysql_insert_id();

@sql_query("DELETE FROM files WHERE torrent = $id");
foreach ($filelist as $file) {
@sql_query("INSERT INTO files (torrent, filename, size) VALUES ($id, ".sqlesc($file[0]).",".$file[1].")");
}

move_uploaded_file($tmpname, "$torrent_dir/$id.torrent");

//===add karma
KPS("+","$kpsupload",$CURUSER["id"]);
//===end

if ($CURUSER["anonymous"]=='yes')
write_log("Torrent $id ($torrent) was uploaded by an anonymous user");
else
write_log("Torrent $id ($torrent) was uploaded by $CURUSER[username]");

//===notify people who voted on offer===\\
if (isset($_POST['offer'])) {
$res = mysql_query("SELECT `userid` FROM `offervotes` WHERE `userid` != " . $CURUSER["id"] . " AND `offerid` = ". ($_POST['offer'] + 0)) or sqlerr(__FILE__, __LINE__);
$pn_msg = "The Offer you voted for: \"$torrent\" was uploaded by " . $CURUSER["username"] . ".\nYou can Download the Torrent [url=$DEFAULTBASEURL/details.php?id=$id&hit=1]here[/url]";

while($row = mysql_fetch_assoc($res)) {
//=== use this if you DO have subject in your PMs
$subject = "Offer $torrent was just uploaded";
//=== use this if you DO NOT have subject in your PMs
//$some_variable .= "(0, 0, $row[userid], '" . get_date_time() . "', " . sqlesc($pn_msg) . ")";

//=== use this if you DO have subject in your PMs
mysql_query("INSERT INTO messages (poster, sender, subject, receiver, added, msg) VALUES (0, 0, ".sqlesc($subject).", $row[userid], ".sqlesc(get_date_time()).", " . sqlesc($pn_msg) . ")") or sqlerr(__FILE__, __LINE__);
//=== use this if you do NOT have subject in your PMs
//mysql_query("INSERT INTO messages (poster, sender, receiver, added, msg) VALUES ".$some_variable."") or sqlerr(__FILE__, __LINE__);
//===end
}
//=== delete all offer stuff
@mysql_query("DELETE FROM `offers` WHERE `id` = ". ($_POST['offer'] + 0));
@mysql_query("DELETE FROM `offervotes` WHERE `offerid` = ". ($_POST['offer'] + 0));
@mysql_query("DELETE FROM `comments` WHERE `offer` = ". ($_POST['offer'] + 0). "");
}
//=== end notify people who voted on offer

/* Email notifs*/ 


$res = sql_query("SELECT name FROM categories WHERE id=$catid") or sqlerr(__FILE__,__LINE__);
$arr = mysql_fetch_assoc($res);
$cat = $arr["name"];
$res = sql_query("SELECT email FROM users WHERE enabled='yes' AND parked='no' AND status='confirmed' AND notifs LIKE '%[cat$catid]%' AND notifs LIKE '%[email]%'") or sqlerr(__FILE__, __LINE__);

$uploader = $anon;

$size = mksize($totallen);
$description = ($html ? strip_tags($descr) : $descr);

$body = <<<EOD

A new torrent has been uploaded.

Name: $torrent
Size: $size 
Category:  $cat 
Uploaded by: $uploader 

Description
-------------------------------------------------------------------------------
$description 
-------------------------------------------------------------------------------

You can use the URL below to download the torrent (you may have to login).

$DEFAULTBASEURL/details.php?id=$id&hit=1

------
Yours,
The $SITENAME Team.

EOD;
$to = "";
$nmax = 1000000000; // Max recipients per message
$nthis = 0;
$ntotal = 0;
$total = mysql_num_rows($res);
while ($arr = mysql_fetch_row($res))
{
  if ($nthis == 0)
    $to = $arr[0];
  else
    $to .= "," . $arr[0];
  ++$nthis;
  ++$ntotal;
  if ($nthis == $nmax || $ntotal == $total)
  {
  $sm = sent_mail("Multiple recipients <$SITEEMAIL>",$SITENAME,$SITEEMAIL,"$SITENAME New torrent - $torrent",$body,"torrent upload",false,true,$to);
  if (!$sm)
  stderr("Error", "Your torrent has been been uploaded. DO NOT RELOAD THE PAGE!\n" .
    "There was however a problem delivering the e-mail notifcations.\n" .
    "Please let an administrator know about this error!\n");
    $nthis = 0;
  }
}
header("Location: $BASEURL/details.php?id=".htmlspecialchars($id)."&uploaded=1");
?>

 

 

Link to comment
Share on other sites

I know that .htaccess files sometimes spit out error 500s, but not so in this case.

 

The weird thing is that this happened several other times, using the same code, each time permanant. ???

 

Thanks for your thoughts!

Link to comment
Share on other sites

Sounds like time for debugging.

 

I suggest using this:

 

die("Code got to here");

 

After each statement and move it if succesful, this should narrow it down to the right line.

 

IE:

 

<?php
require_once("include/benc.php");
// die("Code included benc"); if it got to here comment out and than move this down one as seen below
require_once("include/bittorrent.php");
die("Code included bittorent");
ini_set("upload_max_filesize" ,"$max_torrent_size");

function bark($msg) {
genbark($msg, "Upload failed!");
}
dbconn(); 
loggedinorreturn();
iplogger ();
maxsysop ();

 

Do that throughout the whole script till you get the 500 error message, that means that the line above is throwing the error.

Link to comment
Share on other sites

So, Now I have isolated the error. Everything looks alright to me, but then, I am a n00b ;)

 

//Here's our little error!	

$dict = bdec_file($tmpname, $max_torrent_size);
if (!isset($dict))
bark("What did you upload? This is not an encoded file!");

// End Error

Link to comment
Share on other sites

Throw the debug code in there too and see exactly where it is stopping it

 

function bdec_file($f, $ms) {
$fp = fopen($f, "rb");
  die('failed here'); //etc...	
if (!$fp)
	return;
$e = fread($fp, $ms);
fclose($fp);
return bdec($e);
}

Link to comment
Share on other sites

Note:  If you just want to get the contents of a file into a string, use file_get_contents() as it has much better performance than the code above.

 

Try this instead:

 

function bdec_file($f, $ms) {
$str = file_get_contents($f) OR return;
return $str;
}

 

Would that work out for you?

Link to comment
Share on other sites

OK thanks! That worked great. Unfortunately, now the next function is goofing up... We love php...

 

function dict_check($d, $s) {
if ($d["type"] != "dictionary")
	bark("not a dictionary"); // This is what I get when I run the takeupload.php
$a = explode(":", $s);
$dd = $d["value"];
$ret = array();
foreach ($a as $k) {
	unset($t);
	if (preg_match('/^(.*)\((.*)\)$/', $k, $m)) {
		$k = $m[1];
		$t = $m[2];
	}
	if (!isset($dd[$k]))
		bark("dictionary is missing key(s)");
	if (isset($t)) {
		if ($dd[$k]["type"] != $t)
			bark("invalid entry in dictionary");
		$ret[] = $dd[$k]["value"];
	}
	else
		$ret[] = $dd[$k];
}
return $ret;
}

Link to comment
Share on other sites

I end up getting the bark: not a dictionary.  This is not an error per se with this part of the code, I think. Anything we can do about this one?

 

I really appreciate this help, by the way. I don't know where I would be without it :P

 

alex

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.