Created
January 24, 2011 08:41
-
-
Save wvdschel/792977 to your computer and use it in GitHub Desktop.
IRC proxy/download throttler combo script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'gserver' | |
require 'timeout' | |
require 'thread' | |
class ForwardThread < Thread | |
MAX_DATA = 1000 * 1024 | |
TIME_SLOT = 0.3 | |
@@lock = Mutex.new | |
@@data_sent = 0 | |
Thread.new do | |
while true | |
@@lock.lock | |
@@data_sent = 0 | |
@@lock.unlock | |
sleep TIME_SLOT | |
end | |
end | |
def report_data(bytes) | |
@@lock.lock | |
@@data_sent += bytes | |
@@lock.unlock | |
end | |
def can_send? | |
@@lock.lock | |
r = @@data_sent < MAX_DATA * TIME_SLOT | |
@@lock.unlock | |
return r | |
end | |
def initialize(input, output) | |
super() do | |
until input.eof? | |
if can_send? | |
#puts "accepted" | |
data = input.readpartial(2048) | |
report_data(data.size) | |
output.print(data) | |
else | |
#puts "rejected" | |
sleep TIME_SLOT/5 | |
end | |
end | |
output.close | |
end | |
end | |
end | |
class Limiter < GServer | |
def initialize(port=443, host='0.0.0.0') | |
super(port, host, Float::MAX, $stderr, true) | |
end | |
def serve(inside) | |
begin | |
outside = TCPSocket.new('irc.freenode.net', 6667) | |
rescue e | |
puts "Error while connecting: " + e.to_s | |
else | |
puts "Connected!" | |
in_to_out = ForwardThread.new(inside, outside); | |
out_to_in = ForwardThread.new(outside, inside); | |
in_to_out.join | |
out_to_in.join | |
puts "Stream ended" | |
ensure | |
outside.close | |
end | |
end | |
end | |
server = Limiter.new(ARGV[0] || 443) | |
server.start(-1) | |
server.join |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment