Class: WebserverAbstract
- Inherits:
-
Object
- Object
- WebserverAbstract
- Defined in:
- lib/femtows.rb
Direct Known Subclasses
Constant Summary collapse
- LICON =
"☀☃☎☑☑☠☣☮☺☂".split(/;/).map {|c| c+";"}
- MIME =
{"png" => "image/png", "gif" => "image/gif", "html" => "text/html","htm" => "text/html", "js" => "text/javascript" ,"css" => "text/css","jpeg" => "image/jpeg" ,"jpg" => "image/jpeg", ".json" => "applicatipon/json", "pdf"=> "application/pdf" , "svg" => "image/svg+xml","svgz" => "image/svg+xml", "xml" => "text/xml" ,"xsl" => "text/xml" ,"bmp" => "image/bmp" ,"txt" => "text/plain" , "rb" => "text/plain" ,"pas" => "text/plain" ,"tcl" => "text/plain" ,"java" => "text/plain" , "c" => "text/plain" ,"h" => "text/plain" ,"cpp" => "text/plain", "xul" => "application/vnd.mozilla.xul+xml", "doc" => "application/msword", "docx" => "application/msword","dot"=> "application/msword", "xls" => "application/vnd.ms-excel","xla" => "application/vnd.ms-excel","xlt" => "application/vnd.ms-excel","xlsx" => "application/vnd.ms-excel", "ppt" => "application/vnd.ms-powerpoint", "pptx" => "application/vnd.ms-powerpoint" }
Instance Method Summary collapse
- #do_service(session, request, service, user_passwd, params) ⇒ Object
- #error(txt) ⇒ Object
- #escape(string) ⇒ Object
- #hescape(string) ⇒ Object
- #httpdate(aTime = nil) ⇒ Object
- #info(txt) ⇒ Object
-
#initialize(port, root, name, cadence, timeout, options) ⇒ WebserverAbstract
constructor
A new instance of WebserverAbstract.
- #logg(*args) ⇒ Object
- #makeIndex(adir) ⇒ Object
- #mime(string) ⇒ Object
- #n3(n) ⇒ Object
- #observe(sleeping, delta) ⇒ Object
- #pool_create ⇒ Object
- #pool_get(param, &block) ⇒ Object
- #read_header(session, params) ⇒ Object
- #redirect(o, d) ⇒ Object
- #request(session) ⇒ Object
- #run(session) ⇒ Object
- #sendData(sock, type, content) ⇒ Object
- #sendError(sock, no, txt = nil) ⇒ Object
- #sendFile(sock, filename) ⇒ Object
- #serve(uri, &blk) ⇒ Object
- #stop_browser ⇒ Object
- #to_absolute(f) ⇒ Object
- #to_relative(f) ⇒ Object
- #to_table(l) ⇒ Object
- #to_tableb(l, &bl) ⇒ Object
- #unescape(string) ⇒ Object
Constructor Details
#initialize(port, root, name, cadence, timeout, options) ⇒ WebserverAbstract
Returns a new instance of WebserverAbstract.
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/femtows.rb', line 40 def initialize(port,root,name,cadence,timeout,) raise("tcp port illegal #{port}") unless port.to_i>=80 raise("root not exist #{root}") unless File.exists?(root) @cb_log= ["logg"] @last_mtime=File.mtime(__FILE__) @port=port.to_i @root=root @name=name @rootd=root[-1,1]=="/" ? root : root+"/" @timeout=timeout @th={} @cb={} @redirect={} info(" serveur http #{port} on #{@rootd} ready!") observe(cadence,timeout*2) pool_create @thm=Thread.new { sleep(0.1); loop { nbError=0 begin session=nil @server = TCPServer.new('0.0.0.0', @port) @server.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true) while (session = @server.accept) nbError=0 run(session) end rescue Exception => e nbError+=1 error($!.to_s + " " + $!.backtrace[0..2].join(" ")) session.close rescue nil @server.close rescue nil end sleep(3); info("restart accept") } } end |
Instance Method Details
#do_service(session, request, service, user_passwd, params) ⇒ Object
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/femtows.rb', line 139 def do_service(session,request,service,user_passwd,params) redir=@redirect["/"+service] service=redir.gsub(/^\//,"") if @redirect[redir] aservice=to_absolute(service) if redir && ! @redirect[redir] do_service(session,request,redir.gsub(/^\//,""),user_passwd,params) elsif @cb["/"+service] begin code,type,data= @cb["/"+service].call(params) if code==0 && data != '/'+service do_service(session,request,data[1..-1],user_passwd,params) else code==200 ? sendData(session,type,data) : sendError(session,code,data) end rescue logg session.peeraddr.last,"Error in get /#{service} : #{$!}" sendError(session,501,"#{$!} : at #{$!.backtrace.first}") end elsif service =~ /^stop/ sendData(session,".html","Stopping..."); Thread.new() { sleep(0.1); stop_browser() } elsif File.directory?(aservice) sendData(session,".html",makeIndex(aservice)) elsif File.exists?(aservice) sendFile(session,aservice) else info("unknown request serv=#{service} params=#{params.inspect} #{File.exists?(service)}") sendError(session,500,"unknown request serv=#{aservice} params=#{params.inspect} #{File.exists?(service)}"); end end |
#error(txt) ⇒ Object
28 |
# File 'lib/femtows.rb', line 28 def error(txt) ; logg("nw>e>",txt) ; end |
#escape(string) ⇒ Object
30 |
# File 'lib/femtows.rb', line 30 def escape(string) ; string.gsub(/([^ \/a-zA-Z0-9_.\-]+)/) { '%' + $1.unpack('H2' * $1.size).join('%').upcase }.tr(' ', '+') end |
#hescape(string) ⇒ Object
31 |
# File 'lib/femtows.rb', line 31 def hescape(string) ; escape(string.gsub("/./","/").gsub("//","/")) ; end |
#httpdate(aTime = nil) ⇒ Object
228 |
# File 'lib/femtows.rb', line 228 def httpdate( aTime=nil ); (aTime||Time.now).gmtime.strftime( "%a, %d %b %Y %H:%M:%S GMT" ); end |
#info(txt) ⇒ Object
27 |
# File 'lib/femtows.rb', line 27 def info(txt) ; logg("nw>i>",txt) ; end |
#logg(*args) ⇒ Object
22 23 24 25 26 |
# File 'lib/femtows.rb', line 22 def logg(*args) if @cb_log then @cb_log.call(@name,*args) else puts(args.join(" ")) end rescue puts(args.join(" ")) end |
#makeIndex(adir) ⇒ Object
174 175 176 177 178 179 180 181 182 |
# File 'lib/femtows.rb', line 174 def makeIndex(adir) dir=to_relative(adir) dirs,files=Dir.glob(adir==@rootd ? "#{@rootd}*" : "#{adir}/*").sort.partition { |f| File.directory?(f)} updir = hescape( dir.split(/\//)[0..-2].join("/")) updir="/" if updir.length==0 up=(dir!="/") ? "<input type='button' onclick='location.href=\"#{updir}\"' value='Parent'>" : "" "<html><head><title>#{dir}</title></head>\n<body><h3><center>#{@name} : #{dir[0..-1]}</center></h3>\n<hr>#{up}<br>#{to_table(dirs.map {|s| " <a href='#{hescape(to_relative(s))}'>"+File.basename(s)+"/"+"</a>\n"})}<hr>#{to_tableb(files) {|f| [" <a href='#{hescape(to_relative(f))}'>"+File.basename(f)+"</a>",n3(File.size(f)),File.mtime(f).strftime("%d/%m/%Y %H:%M:%S")]}}</body></html>" end |
#mime(string) ⇒ Object
229 230 231 |
# File 'lib/femtows.rb', line 229 def mime(string) MIME[string.split(/\./).last] || "application/octet-stream" end |
#n3(n) ⇒ Object
185 186 187 188 189 190 191 192 193 194 195 |
# File 'lib/femtows.rb', line 185 def n3(n) u=" B" if n> 10000000 n=n/(1024*1024) u=" MB" elsif n> 100000 n=n/1024 u=" KB" end "<div style='width:100px;text-align:right;'>#{(n.round.to_i.to_s.reverse.gsub(/(\d\d\d)(?=\d)/,'\1 ' ).reverse) +u} | </div>" end |
#observe(sleeping, delta) ⇒ Object
32 33 34 35 36 37 38 39 |
# File 'lib/femtows.rb', line 32 def observe(sleeping,delta) @tho=Thread.new do loop do sleep(sleeping) nowDelta=Time.now-delta l=@th.select { |th,tm| (tm[0]<nowDelta) } l.each { |th,tm| info("killing thread") ; th.kill; @th.delete(th) ; tm[1].close rescue nil } end ; end end |
#pool_create ⇒ Object
75 76 77 78 79 80 81 82 |
# File 'lib/femtows.rb', line 75 def pool_create @queue=Queue.new ici=self 100.times { Thread.new { loop { param,bloc=@queue.pop bloc.call(param) rescue p $! } } } end |
#pool_get(param, &block) ⇒ Object
83 84 85 |
# File 'lib/femtows.rb', line 83 def pool_get(param,&block) @queue.push([param,block]) end |
#read_header(session, params) ⇒ Object
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
# File 'lib/femtows.rb', line 119 def read_header(session,params) head=session.gets("\r\n\r\n") head.split(/\r\n/m).each { |line| name,data=line.split(": ",2) ; params["HEAD-"+name.upcase]=data } if params["HEAD-CONTENT-LENGTH"] len= params["HEAD-CONTENT-LENGTH"].split(/\s+/).last.to_i params["HEAD-CONTENT-LENGTH"]=len data="" while len>0 d=session.read(len>64*1024 ? 64*1024 : len) raise("closed") if !d len -= d.length data+=d end params["HEAD-DATA"]=data end end |
#redirect(o, d) ⇒ Object
136 137 138 |
# File 'lib/femtows.rb', line 136 def redirect(o,d) @redirect[o]=d end |
#request(session) ⇒ Object
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
# File 'lib/femtows.rb', line 97 def request(session) request = session.gets return unless request uri = (request.split(/\s+/)+['','',''])[1] #info uri service,param,*bidon=(uri+"?").split(/\?/) params=Hash[*(param.split(/#/)[0].split(/[=&]/))] rescue {} params.each { |k,v| params[k]=unescape(v) } uri=unescape(service)[1..-1].gsub(/\.\./,"") userpass=nil if (buri=uri.split(/@/)).size>1 uri=buri[1..-1].join("@") userpass=buri[0].split(/:/) end read_header(session,params) do_service(session,request,uri,userpass,params) rescue Exception => e error("Error Web get on #{request}: \n #{$!.to_s} \n #{$!.backtrace.join("\n ")}" ) rescue nil session.write "HTTP/1.0 501 NOK\r\nContent-type: text/html\r\n\r\n<html><head><title>WS</title></head><body>Error : #{$!}" rescue nil ensure session.close rescue nil end |
#run(session) ⇒ Object
86 87 88 89 90 91 92 |
# File 'lib/femtows.rb', line 86 def run(session) pool_get(session) do |sess| @th[Thread.current]=[Time.now,sess] request(sess) @th.delete(Thread.current) end end |
#sendData(sock, type, content) ⇒ Object
208 209 210 211 |
# File 'lib/femtows.rb', line 208 def sendData(sock,type,content) sock.write "HTTP/1.0 200 OK\r\nContent-Type: #{mime(type)}\r\nContent-Length: #{content.size}\r\n\r\n" sock.write(content) end |
#sendError(sock, no, txt = nil) ⇒ Object
202 203 204 205 206 207 |
# File 'lib/femtows.rb', line 202 def sendError(sock,no,txt=nil) if txt txt="<html><body><code><pre></pre>#{txt}</code></body></html>" end sock.write "HTTP/1.0 #{no} NOK\r\nContent-type: #{mime(".html")}\r\n\r\n <html><p>Error #{no} : #{txt}</p></html>" end |
#sendFile(sock, filename) ⇒ Object
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 |
# File 'lib/femtows.rb', line 212 def sendFile(sock,filename) s=File.size(filename) if s < 0 || s>60_000_000 || File.extname(filename).downcase==".lnk" logg @name,"Error reading file/File not downloadable #{File.basename(filename)} : (size=#{s})" sendError(sock,500,"Error reading file/File not downloadable #{filename} : (size=#{s})" ) return end logg @name,filename," #{s/(1024*1024)} Mo" if s>10*1000_000 timeout([s/(512*1024),30.0].max.to_i) { sock.write "HTTP/1.0 200 OK\r\nContent-Type: #{mime(filename)}\r\nContent-Length: #{File.size(filename)}\r\nLast-Modified: #{httpdate(File.mtime(filename))}\r\nDate: #{httpdate(Time.now)}\r\n\r\n" File.open(filename,"rb") do |f| f.binmode; sock.binmode; ( sock.write(f.read(32*1024)) while (! f.eof? && ! sock.closed?) ) rescue nil end } end |
#serve(uri, &blk) ⇒ Object
93 94 95 96 |
# File 'lib/femtows.rb', line 93 def serve(uri,&blk) @cb[uri] = blk puts(" registered #{uri}") end |
#stop_browser ⇒ Object
169 170 171 172 173 |
# File 'lib/femtows.rb', line 169 def stop_browser info "exit on web demand !" [@tho,@thm].each { |th| th.kill } @server.close rescue nil end |
#to_absolute(f) ⇒ Object
184 |
# File 'lib/femtows.rb', line 184 def to_absolute(f) "#{@rootd}#{f.gsub(/^\//,'')}" end |
#to_relative(f) ⇒ Object
183 |
# File 'lib/femtows.rb', line 183 def to_relative(f) f.gsub(/^#{@rootd}/,"/") end |
#to_table(l) ⇒ Object
196 197 198 |
# File 'lib/femtows.rb', line 196 def to_table(l) "<table><tr>#{l.map {|s| "<td>#{s}</td>"}.join("</tr><tr>")}</tr></table>" end |
#to_tableb(l, &bl) ⇒ Object
199 200 201 |
# File 'lib/femtows.rb', line 199 def to_tableb(l,&bl) "<table><tr>#{l.map {|s| "<td>#{bl.call(s).join("</td><td>")}</td>"}.join("</tr><tr>")}</tr></table>" end |
#unescape(string) ⇒ Object
29 |
# File 'lib/femtows.rb', line 29 def unescape(string) ; string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2}))/n) { [$1.delete('%')].pack('H*') } end |