#!/usr/bin/ruby # Script to upload a file to dl.free.fr # Yoann Guillot, 10/12/2005 require 'socket' def read_resp(s, firsttimeout = 10, nexttimeout = firsttimeout) resp = '' oldlen = 0 timeout = firsttimeout while select([s], nil, nil, timeout) resp << s.read break if resp.length == oldlen oldlen = resp.length timeout = nexttimeout end s.shutdown s.close resp end fd = File.open ARGV[0] flen = File.size ARGV[0] host = 'dl.free.fr' # find mirror s=TCPSocket.new(host, 80) s.write "GET / HTTP/1.0\r\nConnection: close\r\n\r\n" resp = read_resp(s) if resp =~ %r{HTTP/1.. 302 Found.*Location: http://(.*?)\r\n}m host = $1 puts "using host #$1" end # get target s=TCPSocket.new(host, 80) s.write "GET / HTTP/1.0\r\nConnection: close\r\n\r\n" resp = read_resp(s) if resp =~ /form action="(.*?)"/ target = $1 else puts "error while parsing index:", resp exit end # upload file bnd = 'blablaBoundary' contenthead = "--#{bnd}\r\n" contenthead += "Content-Disposition: form-data; name=\"ufile\"; filename=\"#{ARGV[0]}\"\r\n" contenthead += "Content-Type: application/octet-stream\r\n" contenthead += "\r\n" contenttail = "\r\n--#{bnd}--\r\n" req = "POST #{target} HTTP/1.0\r\n" req += "Connection: close\r\n" req += "Content-Type: multipart/form-data; boundary=#{bnd}\r\n" req += "Content-Length: #{contenthead.length + contenttail.length + flen}\r\n" req += "\r\n" s=TCPSocket.new(host, 80) s.write req s.write contenthead # send file content sent = 0 while sent < flen sent += s.write(fd.read(4096)) print "sent #{sent*100/flen}%\r" end s.write contenttail # parse response resp = read_resp(s, 120, 10) if resp =~ /upload.*?succ.*?a href="(.*?)"/m puts "Success ! url : #$1" else puts "error while parsing server answer:", resp end