From: David Tillman Date: 2001-09-22T04:57:39+09:00 Subject: [ruby-talk:21499] Speed Hello all, I would like to speed up the following bit of code if possible. This is sort of a toy proxy server. I initially knocked it together earlier this week when the latest MS IIS exploit was announced. One thing the offending virus does is attach a javascript command to fetch a "readme.eml" from the infected server. We use squid as a caching proxy server. This bit of code goes between the client and the proxy server and rewrites pages on the fly. One could have great fun with an unsuspecting victim as you insert their name in place of George Bush, whatever. My actual intentions were to replace "readme.eml" with something benign. It also works quite well as a banner-ad killer. With a little effort it could also be made to cache pages and retrieve pages directly. As I already have squid for that I didn't want to reinvent the wheel. As it stands now the speed is acceptable, but a bit on the slow side. Is there anything I can do to optimize? (besides turning off the debug info) -Dave #!/usr/local/bin/ruby require 'tempfile' require 'socket' Rproxy_port = 3031 Squid_port = 3128 Host = '172.16.16.13' server = TCPServer.new(Host, Rproxy_port) while TRUE Thread.new(session = server.accept) { |my_session| puts "***Thread count: #{Thread.list.length}" puts "***#{Thread.current}: Accepted connection from client." squid = TCPSocket.new(Host, Squid_port) puts "***#{Thread.current}: Opened socket to squid." request = my_session.recvfrom(2048) print "***#{Thread.current}: Request: #{request[0]}\n" squid.print(request[0]) puts "***#{Thread.current}: Gave request to squid." tf = Tempfile.new("rproxy") answer = squid.recvfrom(1024) while (answer[0].length > 0) tf.print(answer[0]) answer = squid.recvfrom(1024) end squid.close puts "***#{Thread.current}: Closed socket to squid." tf.pos = 0 headers = {} line = tf.gets("\r\n") while (line != "\r\n") line.chomp!("\r\n") title, data = line.split(/: /) headers[title] = data line = tf.gets end tf.pos = 0 if (headers["Content-Type"] == "text/html") while (answer = tf.gets("\r\n")) answer.gsub!(/readme\.eml/, "foo.html") my_session.print answer end else answer = tf.read(1024) while (answer) my_session.print answer answer = tf.read(1024) end end my_session.close puts "***#{Thread.current}: Closed socket to client." tf.close puts "***#{Thread.current}: Content-Type = #{headers['Content-Type']}" } end