shithub: iso

ref: 8fa9d99424da17b8ac3e67fb6d5563bf71f51e56
dir: /bin/trackerc/

View raw version
#!/bin/rc

# worst bittorrent tacker ever written... in rc.
dir=/tmp/tracker
cd $dir || exit 'no tracker directory'

cr='
'

ipv=ip
ipv6=()
if(! ~ $#net 1) net=$$#*
ip=`'!'{cat $net/remote}
ip=$ip(1)
~ $#ip 1 || exit 'no remote ip'

if(~ $ip *:*){
	ipv=ipv6
	ipv6=$ip
	ip=()
}

req=`{read}

q=`'?'{echo -n $req(2)}
q=`'&'{echo -n $q(2)}

for(i in $q){
	v=`'='{echo -n $i}
	k=$v(1)
	v=$v(2)
	switch($k){
	case info_hash peer_id port
		$k=$v
	}
}

# sanity
~ $#info_hash 1 || exit 'no info hash'

fn hex {
	xd -x1 | sed 's/^[^ ]+//g;s/[ ]//g;' | sed '{N;s/\n//;}'
}
info_hash=`{echo -n $info_hash | urlencode -d | hex}

# sanity
~ $info_hash ???????????????????????????????????????? || exit 'bad info hash format'

fn respond {
	echo $ip $req $* >[1=2]

	echo 'HTTP/1.1' $* $cr
	echo $cr
}

# is this a scrape?
if(! ~ $#peer_id 1){
	if(! test -d $info_hash){
		respond 404 'Not Found'
		exit ''
	}
}

fn str {
	n=`{echo -n $1 | wc -c}
	echo -n $n:$1
}
fn int {
	echo -n i^$1^e
}

if(~ $#peer_id 1){
	echo -n $peer_id | urlencode -d > /env/peer_id.bin
	peer_id=`{hex < /env/peer_id.bin}

	# sanity
	~ $peer_id ???????????????????????????????????????? || exit 'bad peer id format'

	port=`{echo $port | sed 's/[^0-9]//g'}
	~ $#port 1 || exit 'no port port'
	~ $port [0-9]* || exit 'bad port format'

	mkdir -p $info_hash || exit 'mkdir info hash directory'

	# write dict file for classic mode
	> $info_hash/$peer_id.$ipv.dict {
		echo -n d
		str 'peer id'
		echo -n '20:'
		cat /env/peer_id.bin
		str ip
		str $$ipv
		str port
		int $port
		echo -n e
	}
}

cd $info_hash || exit 'cd info hash directory'

# cleanup old files
for(i in *){
	test $i -older 5m && rm -f $i
}

respond 200 OK

echo -n d
str interval
int 120
str peers
echo -n l
cat *.dict >[2] /dev/null 
echo -n e
echo -n e

exit ''