ruby/nar.rb
SuzTiki:ruby
require 'md5'
require 'cgi'
require 'magic'
$magic = Magic.new();
class MemoryIO
def initialize
@buf = [];
@write_line = '';
@read_ind = 0;
@read_pos = 0;
end
def write(str)
@write_line << str
if (str =~ /[\r\n]$/)
@buf << @write_line;
@write_line = '';
end
end
def read(len=0x7fffffff)
ret = '';
return nil if (@read_ind >= @buf.length)
while (len > 0 && (@read_ind < @buf.length))
line_len = @buf[@read_ind].length - @read_pos;
if (len < line_len)
ret << @buf[@read_ind][@read_pos,len];
@read_pos += len;
len -= line_len;
else
ret << @buf[@read_ind][@read_pos,line_len];
@read_pos = 0;
@read_ind += 1;
len -= line_len;
end
end
return ret;
end
def rewind
@read_ind = 0;
@read_pos = 0;
end
def close
end
end
class Nar
def self.export_file1(path,out_io=STDOUT,name_conv=nil,passwd=nil)
type = $magic.file(path);
st = File::Stat.new(path);
name = path
if (name_conv != nil)
name = name_conv(path);
end
head = "URI: " + name + "\r\n";
head << "Content-Type: "+ type + "\r\n";
head << "Content-Length: " + st.size.to_s + "\r\n";
head << "Last-Modified: " + CGI::rfc1123_date(st.mtime) + "\r\n";
io = File::open(path, 'r')
io.binmode
md5 = MD5::new
while (str = io.read(4096))
md5.update(str)
end
if (passwd != nil)
md5.update(head)
md5.update(passwd)
end
io.rewind
head << "Content-MD5: "+ md5.to_s + "\r\n";
head << "\r\n";
out_io.write head
while (str = io.read(4096))
out_io.write str
end
io.close;
end
def self.import_file1(head,in_io=STDIN,out_io=nil,passwd=nil)
md5 = MD5::new
len = head['CONTENT_LENGTH'].to_i
while (len > 0)
rlen = len;
rlen = 4096 if (len >= 4096);
len -= rlen;
str = in_io.read(rlen)
out_io.write(str) if (out_io != nil)
md5.update(str)
end
if (passwd != nil)
h = "URI: " + head['URI'] + "\r\n";
h << "Content-Type: "+ head['CONTENT_TYPE'] + "\r\n";
h << "Content-Length: " + head['CONTENT_LENGTH'] + "\r\n";
h << "Last-Modified: " + head['LAST_MODIFIED'] + "\r\n";
md5.update(h);
md5.update(passwd);
end
if (head['CONTENT_MD5'] != md5.to_s)
return false;
end
return true;
end
def self.test_out
self.export_file1("etc/protocols",STDOUT,nil,"pass");
self.export_file1("etc/services",STDOUT,nil,"pass");
end
def self.test_in(passwd=nil)
begin
error = true;
head = {}
while (str = gets)
str.gsub!(/[\r\n]+$/,'');
if str =~ /^(\S+):\s*(.*)$/ then
val = $2
key = $1.upcase
key.gsub!(/-/n, '_')
head[key] = val;
elsif str =~ /^\s*$/i then
error = false;
break;
else
break;
end
end
tmp = MemoryIO.new();
error = !self.import_file1(head,STDIN,tmp,"pass") if (!error)
if (!error)
print head['URI'] ,"is ok \n";
end
end until error;
end
end
#Nar::test_out
Nar::test_in
(最終更新 Thu Mar 30 18:43:01 2006)