Moving things around to make it more structured. and turn into library

This commit is contained in:
Jocelyn Fiat
2011-05-27 15:21:30 +02:00
parent c553bd1e1e
commit 54b95650c5
90 changed files with 24 additions and 2 deletions

5
src/README Normal file
View File

@@ -0,0 +1,5 @@
Eiffel Web Nino is and HTTPD server. It's a work in progress, so maybe it will be refactored.
The goal of is to provide a simple web server for development (like Java, Python and Ruby provide)

View File

@@ -0,0 +1,60 @@
note
description: "Summary description for {HTTP_SERVER_CONFIGURATION}."
date: "$Date$"
revision: "$Revision$"
class
HTTP_SERVER_CONFIGURATION
create
make
feature {NONE} -- Initialization
make
do
http_server_port := 9_000
max_tcp_clients := 100
socket_accept_timeout := 1_000
socket_connect_timeout := 5_000
document_root := "htdocs"
end
feature -- Access
Server_details : STRING = "Server : NANO Eiffel Server"
document_root: STRING assign set_document_root
http_server_port: INTEGER assign set_http_server_port
max_tcp_clients: INTEGER assign set_max_tcp_clients
socket_accept_timeout: INTEGER assign set_socket_accept_timeout
socket_connect_timeout: INTEGER assign set_socket_connect_timeout
feature -- Element change
set_http_server_port (v: like http_server_port)
do
http_server_port := v
end
set_document_root (v: like document_root)
do
document_root := v
end
set_max_tcp_clients (v: like max_tcp_clients)
do
max_tcp_clients := v
end
set_socket_accept_timeout (v: like socket_accept_timeout)
do
socket_accept_timeout := v
end
set_socket_connect_timeout (v: like socket_connect_timeout)
do
socket_connect_timeout := v
end
end

View File

@@ -0,0 +1,45 @@
note
description: "Summary description for {HTTP_SERVER_SHARED_CONFIGURATION}."
author: ""
date: "$Date$"
revision: "$Revision$"
class
HTTP_SERVER_SHARED_CONFIGURATION
feature -- Access
server_configuration: detachable HTTP_SERVER_CONFIGURATION
-- Shared configuration
do
if attached server_configuration_cell.item as l_cfg then
Result := l_cfg
end
end
document_root: STRING_8
-- Shared document root
do
if attached server_configuration as l_cfg then
Result := l_cfg.document_root
else
Result := ""
end
end
feature -- Element change
set_server_configuration (a_cfg: like server_configuration)
-- Set `server_configuration' to `a_cfg'.
do
server_configuration_cell.replace (a_cfg)
end
feature {NONE} -- Implementation
server_configuration_cell: CELL [detachable HTTP_SERVER_CONFIGURATION]
once ("PROCESS")
create Result.put (Void)
end
end

View File

@@ -0,0 +1,150 @@
note
description: "Summary description for {HTTP_CONNECTION_HANDLER}."
author: ""
date: "$Date$"
revision: "$Revision$"
deferred class
HTTP_CONNECTION_HANDLER
inherit
HTTP_HANDLER
redefine
make
end
feature {NONE} -- Initialization
make (a_main_server: like main_server; a_name: STRING)
-- Creates a {HTTP_CONNECTION_HANDLER}, assigns the main_server and sets the current_request_message to empty.
--
-- `a_main_server': The main server object
-- `a_name': The name of this module
do
Precursor (a_main_server, a_name)
create method.make_empty
create uri.make_empty
create request_header.make_empty
create request_header_map.make (10)
end
feature -- Execution
receive_message_and_send_reply (client_socket: TCP_STREAM_SOCKET)
local
l_input: HTTP_INPUT_STREAM
l_output: HTTP_OUTPUT_STREAM
do
create l_input.make (client_socket)
create l_output.make (client_socket)
analyze_request_message (l_input)
process_request (uri, method, request_header_map, request_header, l_input, l_output)
end
feature -- Request processing
process_request (a_uri: STRING; a_method: STRING; a_headers_map: HASH_TABLE [STRING, STRING]; a_headers_text: STRING; a_input: HTTP_INPUT_STREAM; a_output: HTTP_OUTPUT_STREAM)
-- Process request ...
require
a_uri_attached: a_uri /= Void
a_method_attached: a_method /= Void
a_headers_text_attached: a_headers_text /= Void
a_input_attached: a_input /= Void
a_output_attached: a_output /= Void
deferred
end
feature {NONE} -- Access
request_header: STRING
-- Header' source
request_header_map : HASH_TABLE [STRING,STRING]
-- Contains key:value of the header
method: STRING
-- http verb
uri: STRING
-- http endpoint
version: detachable STRING
-- http_version
--| unused for now
feature -- Parsing
parse_http_request_line (line: STRING)
require
line /= Void
local
pos, next_pos: INTEGER
do
print ("%N parse http request line:%N" + line)
-- parse (this should be done by a lexer)
pos := line.index_of (' ', 1)
method := line.substring (1, pos - 1)
next_pos := line.index_of (' ', pos+1)
uri := line.substring (pos+1, next_pos-1)
ensure
not_void_method: method /= Void
end
analyze_request_message (a_input: HTTP_INPUT_STREAM)
require
input_redable: a_input /= Void and then not a_input.is_readable
local
end_of_stream : BOOLEAN
pos : INTEGER
line : STRING
txt: STRING
do
create txt.make (64)
a_input.read_line
line := a_input.last_string
analyze_request_line (line)
txt.append (line)
txt.append_character ('%N')
request_header := txt
from
a_input.read_line
until
end_of_stream
loop
line := a_input.last_string
print ("%N" +line+ "%N")
pos := line.index_of (':',1)
request_header_map.put (line.substring (pos + 1, line.count), line.substring (1,pos-1))
txt.append (line)
txt.append_character ('%N')
if line.is_empty or else line[1] = '%R' then
end_of_stream := True
else
a_input.read_line
end
end
end
analyze_request_line (line: STRING)
require
line /= Void
local
pos, next_pos: INTEGER
do
print ("%N parse request line:%N" + line)
pos := line.index_of (' ', 1)
method := line.substring (1, pos - 1)
next_pos := line.index_of (' ', pos+1)
uri := line.substring (pos+1, next_pos-1)
version := line.substring (next_pos + 1, line.count)
ensure
not_void_method: method /= Void
end
invariant
request_header_attached: request_header /= Void
end

146
src/http_constants.e Normal file
View File

@@ -0,0 +1,146 @@
note
description: "Summary description for {HTTP_CONSTANTS}."
author: ""
date: "$Date$"
revision: "$Revision$"
class
HTTP_CONSTANTS
feature
http_version_1_1: STRING = "HTTP/1.1"
http_version_1_0: STRING = "HTTP/1.0"
crlf: STRING = "%/13/%/10/"
feature -- Status codes
-- 1xx Informational -Request received, continuing process
Continue : STRING = "100"
Switching_Protocols : STRING = "101"
-- 2xx Success - The action was successfully received, understood, and accepted
Ok: STRING = "200"
Created : STRING = "201"
Accepted : STRING = "202"
Non_Authoritative_Information : STRING = "203"
No_Content : STRING = "204"
Reset_Content : STRING = "205"
Parcial_Content : STRING = "206"
-- 3xx Redirection - Further Action must be taken in order to complete the request
Multiple_Choices : STRING = "300"
Moved_Permanently: STRING = "301"
Found : STRING = "302"
See_Other : STRING = "303"
Not_Modified : STRING = "304"
Use_Proxy : STRING = "305"
Temporary_Redirect : STRING = "307"
--4xx Client Error - The request contains bad syntax or cannot be fulfilled
Bad_Request : STRING = "400"
Unauthorized : STRING = "401"
Payment_Required : STRING = "402"
Forbidden : STRING = "403"
Not_Found : STRING = "404"
Method_Not_Allowed : STRING = "405"
Not_Acceptable : STRING = "406"
Proxy_Authentication_Required : STRING = "407"
Request_Time_out : STRING = "408"
Conflict : STRING = "409"
Gone : STRING = "410"
Length_Required : STRING = "411"
Precondition_Failed : STRING = "412"
Request_Entity_Too_Large : STRING = "413"
Request_URI_Too_Large : STRING = "414"
Unsupported_Media_Type : STRING = "415"
Requested_range_not_satisfiable : STRING = "416"
Expectation_Failed : STRING = "417"
--5xx Server Error - The server failed to fulfill an apparently valid request
server_error: STRING = "500"
Internal_Server_Error : STRING = "500"
Not_Implemented : STRING = "501"
Bad_Gateway : STRING = "502"
Service_Unavailable : STRING = "503"
Gateway_Time_out : STRING = "504"
HTTP_Version_not_supported : STRING = "505"
-- messages
ok_message: STRING = "OK"
continue_message : STRING = "Continue"
not_found_message: STRING = "URI not found"
not_implemented_message: STRING = "Not Implemented"
feature -- content types
text_html: STRING = "text/html"
feature -- General Header Fields
-- There are a few header fields which have general applicability for both request and response messages,
-- but which do not apply to the entity being transferred.
-- These header fields apply only to the message being transmitted.
Cache_control : STRING = "Cache-Control"
Connection : STRING = "Connection"
Date : STRING = "Date"
Pragma : STRING = "PRAGMA"
Trailer : STRING = "Trailer"
Transfer_encoding : STRING = "Transfer-Encoding"
Upgrade : STRING = "Upgrade"
Via : STRING = "Via"
Warning : STRING = "Warning"
feature -- Request Header
Accept : STRING = "Accept"
Accept_charset : STRING = "Accept-Charset"
Accept_encoding : STRING = "Accept-Encoding"
Accept_language : STRING = "Accept-Language"
Authorization : STRING = "Authorization"
Expect : STRING = "Expect"
From_header : STRING = "From"
Host : STRING = "Host"
If_match : STRING = "If-Match"
If_modified_since : STRING = "If-Modified-Since"
If_none_match : STRING = "If-None-Match"
If_range : STRING = "If-Range"
If_unmodified_since : STRING = "If-Unmodified-Since"
Max_forwards : STRING = "Max-Forwards"
Proxy_authorization : STRING = "Proxy-Authorization"
Range : STRING = "Range"
Referer : STRING = "Referrer"
TE : STRING = "TE"
User_agent : STRING = "User-Agent"
feature -- Entity Header
Allow : STRING = "Allow"
Content_encoding : STRING = "Content-Encoding"
Content_language : STRING = "Content-Language"
Content_length : STRING = "Content-Length"
Content_location : STRING = "Content-Location"
Content_MD5 : STRING = "Content-MD5"
Content_range : STRING = "Content-Range"
Content_type : STRING = "Content-Type"
Expires : STRING = "Expires"
Last_modified : STRING = "Last-Modified"
feature -- Http Method
Options : STRING = "OPTIONS"
Get : STRING = "GET"
Head : STRING = "HEAD"
Post : STRING = "POST"
Put : STRING = "PUT"
Delete : STRING = "DELETE"
Trace : STRING = "TRACE"
Connect : STRING = "CONNECT"
end

View File

@@ -0,0 +1,57 @@
note
description: "[
Provides features to encode and decode messages
]"
legal: "See notice at end of class."
status: "Community Preview 1.0"
date: "$Date: 2009-09-01 19:15:37 -0300 (mar 01 de sep de 2009) $"
revision: "$Revision: 80577 $"
class
HTTP_ENCODING_FACILITIES
create
make
feature -- Initialization
make
do
end
feature -- Conversion
encode_natural(a_i: NATURAL; a_is_fragmented: BOOLEAN): NATURAL
-- Leftshift of the natural (don't use numbers >= 2^31) and subsequent append of the flag bit.
-- Use decode_natural and decode_flag for decoding.
require
no_too_big: a_i < 2147483648
do
Result := (a_i |<< 1) + a_is_fragmented.to_integer.as_natural_32
end
change_flag(a_i: NATURAL; a_new_flag: BOOLEAN): NATURAL
-- Changes the flag to "new_flag" and doesn't change the encoded natural.
do
Result := (a_i & 0xFFFFFFFE) + a_new_flag.to_integer.as_natural_32
end
decode_natural_and_flag (a_i: NATURAL): TUPLE [NATURAL, BOOLEAN]
-- Convenience feature which combines both decodings (natural and flag)
do
Result := [decode_natural (a_i), decode_flag (a_i)]
end
decode_natural (a_i: NATURAL): NATURAL
-- The natural that was encoded in {ENCODING_FACILITIES}.encode_natural.
do
Result := (a_i |>> 1)
end
decode_flag (a_i: NATURAL): BOOLEAN
--`Result': the flag that was encoded in encode_natural
do
Result := (a_i.bit_and (1) = 1)
end
end

123
src/http_handler.e Normal file
View File

@@ -0,0 +1,123 @@
note
description: "Summary description for {HTTP_CONNECTION_HANDLER}."
author: ""
date: "$Date$"
revision: "$Revision$"
deferred class
HTTP_HANDLER
inherit
THREAD
HTTP_CONSTANTS
feature {NONE} -- Initialization
make (a_main_server: like main_server; a_name: STRING)
-- Creates a {HTTP_HANDLER}, assigns the main_server and initialize various values
--
-- `a_main_server': The main server object
-- `a_name': The name of this module
require
a_main_server_attached: a_main_server /= Void
a_name_attached: a_name /= Void
do
main_server := a_main_server
is_stop_requested := False
ensure
main_server_set: a_main_server ~ main_server
end
feature -- Inherited Features
execute
-- <Precursor>
-- Creates a socket and connects to the http server.
local
l_http_socket: detachable TCP_STREAM_SOCKET
l_http_port: INTEGER
do
is_stop_requested := False
l_http_port := main_server_configuration.http_server_port
create l_http_socket.make_server_by_port (l_http_port)
if not l_http_socket.is_bound then
print ("Socket could not be bound on port " + l_http_port.out )
else
from
l_http_socket.listen (main_server_configuration.max_tcp_clients)
print ("%NHTTP Connection Server ready on port " + l_http_port.out +"%N")
until
is_stop_requested
loop
l_http_socket.accept
if not is_stop_requested then
if attached l_http_socket.accepted as l_thread_http_socket then
receive_message_and_send_reply (l_thread_http_socket)
l_thread_http_socket.cleanup
check
socket_closed: l_thread_http_socket.is_closed
end
end
end
end
l_http_socket.cleanup
check
socket_is_closed: l_http_socket.is_closed
end
end
print ("HTTP Connection Server ends.")
rescue
print ("HTTP Connection Server shutdown due to exception. Please relaunch manually.")
if attached l_http_socket as ll_http_socket then
ll_http_socket.cleanup
check
socket_is_closed: ll_http_socket.is_closed
end
end
is_stop_requested := True
retry
end
feature -- Access
is_stop_requested: BOOLEAN
-- Set true to stop accept loop
feature {NONE} -- Access
main_server: HTTP_SERVER
-- The main server object
main_server_configuration: HTTP_SERVER_CONFIGURATION
-- The main server's configuration
do
Result := main_server.configuration
end
Max_fragments: INTEGER = 1000
-- Defines the maximum number of fragments that can be received
feature -- Status setting
shutdown
-- Stops the thread
do
is_stop_requested := True
end
feature -- Execution
receive_message_and_send_reply (client_socket: TCP_STREAM_SOCKET)
require
socket_attached: client_socket /= Void
-- socket_valid: client_socket.is_open_read and then client_socket.is_open_write
a_http_socket:client_socket /= Void and then not client_socket.is_closed
deferred
end
invariant
main_server_attached: main_server /= Void
end

177
src/http_protocol_handler.e Normal file
View File

@@ -0,0 +1,177 @@
class HTTP_PROTOCOL_HANDLER
inherit
SHARED_HTTP_REQUEST_HANDLERS
HTTP_CONSTANTS
create
make
feature -- Initialization
make (socket: NETWORK_STREAM_SOCKET)
require
valid_socket: socket /= Void and then socket.is_bound
local
done: BOOLEAN
client_socket: detachable NETWORK_STREAM_SOCKET
do
from
done := False
until
done
loop
socket.accept
client_socket := socket.accepted
if client_socket = Void then
-- Some error occured, perhaps because of the timeout
-- We probably should provide some diagnostics here
io.put_string ("accept result = Void")
io.put_new_line
else
perform_client_communication (client_socket)
end
end
end
feature -- Access
method : STRING
uri : STRING
version : STRING
request_header_map : HASH_TABLE [STRING,STRING]
-- Containts key value of the header
feature -- Implementation
perform_client_communication (socket: NETWORK_STREAM_SOCKET)
require
socket_attached: socket /= Void
socket_valid: socket.is_open_read and then socket.is_open_write
local
done: BOOLEAN
l_address, l_peer_address: detachable NETWORK_SOCKET_ADDRESS
do
l_address := socket.address
l_peer_address := socket.peer_address
check
l_address_attached: l_address /= Void
l_peer_address_attached: l_peer_address /= Void
end
io.put_string ("Accepted client on the listen socket address = "+ l_address.host_address.host_address + " port = " + l_address.port.out +".")
io.put_new_line
io.put_string ("%T Accepted client address = " + l_peer_address.host_address.host_address + " , port = " + l_peer_address.port.out)
io.put_new_line
create request_header_map.make (20)
from
done := False
until
done
loop
if socket.socket_ok then
done := receive_message_and_send_reply (socket)
request_header_map.wipe_out
else
done := True
end
end
io.put_string ("Finished processing the client, address = "+ l_peer_address.host_address.host_address + " port = " + l_peer_address.port.out + ".")
io.put_new_line
end
receive_message_and_send_reply (client_socket: NETWORK_STREAM_SOCKET): BOOLEAN
require
socket_attached: client_socket /= Void
socket_valid: client_socket.is_open_read and then client_socket.is_open_write
local
message: detachable STRING
l_http_request : HTTP_REQUEST_HANDLER
do
parse_request_line (client_socket)
message := receive_message_internal (client_socket)
if method.is_equal (Get) then
create {GET_REQUEST_HANDLER} l_http_request
l_http_request.set_uri (uri)
l_http_request.process
send_message (client_socket, l_http_request.answer.reply_header + l_http_request.answer.reply_text)
elseif method.is_equal (Post) then
elseif method.is_equal (Put) then
elseif method.is_equal (Options) then
elseif method.is_equal (Head) then
elseif method.is_equal (Delete) then
elseif method.is_equal (Trace) then
elseif method.is_equal (Connect) then
else
debug
print ("Method not supported")
end
end
end
parse_request_line (socket: NETWORK_STREAM_SOCKET)
require
socket: socket /= Void and then not socket.is_closed
do
socket.read_line
parse_request_line_internal (socket.last_string)
end
receive_message_internal (socket: NETWORK_STREAM_SOCKET) : STRING
require
socket: socket /= Void and then not socket.is_closed
local
end_of_stream : BOOLEAN
pos : INTEGER
line : STRING
do
from
socket.read_line
Result := ""
until
end_of_stream
loop
line := socket.last_string
print ("%N" +line+ "%N")
pos := line.index_of(':',1)
request_header_map.put (line.substring (pos + 1, line.count), line.substring (1,pos-1))
Result.append(socket.last_string)
if not socket.last_string.is_equal("%R") and socket.socket_ok then
socket.read_line
else
end_of_stream := True
end
end
end
send_message (client_socket : NETWORK_STREAM_SOCKET ; a_msg: STRING)
local
a_package : PACKET
a_data : MANAGED_POINTER
c_string : C_STRING
do
create c_string.make (a_msg)
create a_data.make_from_pointer (c_string.item, a_msg.count + 1)
create a_package.make_from_managed_pointer (a_data)
client_socket.send (a_package, 0)
end
parse_request_line_internal (line: STRING)
require
line /= Void
local
pos, next_pos: INTEGER
do
print ("%N parse request line:%N" + line)
pos := line.index_of (' ', 1)
method := line.substring (1, pos - 1)
next_pos := line.index_of (' ', pos+1)
uri := line.substring (pos+1, next_pos-1)
version := line.substring (next_pos + 1, line.count)
ensure
not_void_method: method /= Void
end
end

61
src/http_server.e Normal file
View File

@@ -0,0 +1,61 @@
note
description: "Summary description for {HTTP_SERVER}."
author: ""
date: "$Date$"
revision: "$Revision$"
class
HTTP_SERVER
inherit
HTTP_SERVER_SHARED_CONFIGURATION
create
make
feature -- Initialization
make (cfg: like configuration)
do
configuration := cfg
end
setup (a_http_handler : HTTP_HANDLER)
require
a_http_handler_valid: a_http_handler /= Void
do
print("%N%N%N")
print ("Starting Web Application Server:%N")
stop_requested := False
set_server_configuration (configuration)
a_http_handler.launch
a_http_handler.join
end
shutdown_server
do
stop_requested := True
end
feature -- Access
configuration: HTTP_SERVER_CONFIGURATION
-- Configuration of the server
stop_requested: BOOLEAN
-- Stops the server
feature {NONE} -- implementation
run
-- Start the server
local
e: EXECUTION_ENVIRONMENT
do
create e
from until stop_requested loop
e.sleep (1_000_000)
end
end
end

View File

@@ -0,0 +1,64 @@
note
description: "Summary description for {HTTP_INPUT_STREAM}."
author: ""
date: "$Date$"
revision: "$Revision$"
class
HTTP_INPUT_STREAM
create
make
feature {NONE} -- Initialization
make (a_socket: like source)
do
source := a_socket
create last_string.make_empty
end
source: TCP_STREAM_SOCKET
feature -- Status Report
is_readable: BOOLEAN
-- Is readable?
do
Result := source.is_open_read
end
feature -- Basic operation
read_line
require
is_readable: is_readable
do
last_string.wipe_out
if source.socket_ok then
source.read_line_thread_aware
last_string.append_string (source.last_string)
end
end
read_stream (nb_char: INTEGER)
-- Read a string of at most `nb_char' bound characters
-- or until end of file.
-- Make result available in `last_string'.
require
nb_char_positive: nb_char > 0
is_readable: is_readable
do
last_string.wipe_out
if source.socket_ok then
source.read_stream_thread_aware (nb_char)
last_string.append_string (source.last_string)
end
end
feature -- Access
last_string: STRING
-- Last string read
end

View File

@@ -0,0 +1,31 @@
note
description: "Summary description for {HTTP_OUTPUT_STREAM}."
author: ""
date: "$Date$"
revision: "$Revision$"
class
HTTP_OUTPUT_STREAM
create
make
feature {NONE} -- Initialization
make (a_socket: like target)
do
target := a_socket
end
target: TCP_STREAM_SOCKET
feature -- Basic operation
put_string (s: STRING)
-- Write string `s' to `target'
do
target.put_string (s)
end
end

View File

@@ -0,0 +1,175 @@
class
GET_REQUEST_HANDLER
inherit
HTTP_REQUEST_HANDLER
HTTP_SERVER_SHARED_CONFIGURATION
undefine
default_create
end
SHARED_URI_CONTENTS_TYPES
undefine
default_create
end
HTTP_CONSTANTS
undefine
default_create
end
create
make
feature {NONE} -- Initialization
make (a_input: like input; a_output: like output)
do
default_create
input := a_input
output := a_output
end
feature -- Access
input: HTTP_INPUT_STREAM
output: HTTP_OUTPUT_STREAM
feature -- Execution
process
-- process the request and create an answer
local
fname: STRING_8
f: RAW_FILE
ctype, extension: detachable STRING_8
do
answer.reset
if script_name.is_equal ("/") then
process_default
answer.set_content_type ("text/html")
else
create fname.make_from_string (Document_root)
fname.append (script_name)
debug
print ("URI filename: " + fname)
end
create f.make (real_filename (fname))
if f.exists then
extension := Ct_table.extension (script_name)
ctype := Ct_table.content_types.item (extension)
if f.is_directory then
process_directory (f)
else
if ctype = Void then
process_raw_file (f)
answer.set_content_type ("text/html")
else
if ctype.is_equal ("text/html") then
process_text_file (f)
else
process_raw_file (f)
end
answer.set_content_type (ctype)
end
end
else
answer.set_status_code (Not_found)
answer.set_reason_phrase (Not_found_message)
answer.set_reply_text ("Not found on this server")
end
end
if attached answer.reply_text as t then
answer.set_content_length (t.count)
else
answer.set_content_length (0)
end
--| Output the result
output.put_string (answer.reply_header + answer.reply_text)
end
process_default
-- Return a default response
local
html: STRING_8
do
answer.set_reply_text ("")
html := " <html> <head> <title> NINO HTTPD </title> " + " </head> " + " <body> " + " <h1> Welcome to NINO HTTPD! </h1> " + " <p> Default page " + " </p> " + " </body> " + " </html> "
answer.append_reply_text (html)
end
process_text_file (f: FILE)
-- send a text file reply
require
valid_f: f /= Void
do
f.open_read
from
answer.set_reply_text ("")
f.read_line
until
f.end_of_file
loop
answer.append_reply_text (f.last_string)
answer.append_reply_text (Crlf)
f.read_line
end
f.close
end
process_raw_file (f: FILE)
-- send a raw file reply
require
valid_f: f /= Void
do
f.open_read
from
answer.set_reply_text ("")
until
f.end_of_file
loop
f.read_stream_thread_aware (1024)
answer.append_reply_text (f.last_string)
end
f.close
end
process_directory (f: FILE)
--read the directory
require
is_directory: f.is_directory
local
l_dir: DIRECTORY
files: ARRAYED_LIST [STRING_8]
html1: STRING_8
html2: STRING_8
htmldir: STRING_8
path: STRING_8
do
answer.set_reply_text ("")
html1 := " <html> <head> <title> NINO HTTPD </title> " + " </head> " + " <body> " + " <h1> Welcome to NINO HTTPD! </h1> " + " <p> Default page "
html2 := " </p> " + " </body> " + " </html> "
path := script_name
if path[path.count] = '/' then
path.remove_tail (1)
end
create l_dir.make_open_read (f.name)
files := l_dir.linear_representation
from
files.start
htmldir := "<ul>"
until
files.after
loop
htmldir := htmldir + "<li><a href=%"" + path + "/" + files.item_for_iteration + "%">" + files.item_for_iteration + "</a> </li>%N"
files.forth
end
htmldir := htmldir + "</ul>"
answer.append_reply_text (html1 + htmldir + html2)
end
end -- class GET_REQUEST_HANDLER

View File

@@ -0,0 +1,115 @@
note
description: "Summary description for {HEAD_REQUEST_HANDLER}."
author: ""
date: "$Date$"
revision: "$Revision$"
class
HEAD_REQUEST_HANDLER
inherit
SHARED_DOCUMENT_ROOT
SHARED_URI_CONTENTS_TYPES
HTTP_REQUEST_HANDLER
HTTP_CONSTANTS
feature
process
-- process the request and create an answer
local
fname: STRING
f: RAW_FILE
ctype, extension: STRING
do
fname := document_root_cell.item.twin
fname.append (request_uri)
debug
print ("URI name: " + fname )
end
create f.make (fname)
create answer.make
if f.exists then
extension := ct_table.extension (request_uri)
ctype := ct_table.content_types.item (extension)
-- TODO: This code could be improved to avoid string
-- comparisons
if ctype = Void then
process_default
answer.set_content_type ("text/html")
else
if ctype.is_equal ("text/html") then
process_text_file (f)
else
process_raw_file (f)
end
answer.set_content_type (ctype)
end
else
answer.set_status_code (not_found)
answer.set_reason_phrase (not_found_message)
answer.set_reply_text ("Not found on this server%N%R")
end
end
process_default
--
local
html : STRING
do
answer.set_reply_text ("")
html := " <html> <head> <title> Micro HTTPD </title> " +
" </head> " +
" <body> " +
" <h1> Welcome to Micro HTTPD! </h1> "+
" <p> Default page " +
" </p> " +
" </body> " +
" </html> "
answer.append_reply_text (html)
end
process_text_file (f: FILE)
-- send a text file reply
require
valid_f: f /= Void
do
f.open_read
from
answer.set_reply_text ("")
f.read_line
until f.end_of_file
loop
answer.append_reply_text (f.last_string)
answer.append_reply_text (crlf)
f.read_line
end
f.close
end
process_raw_file (f: FILE)
-- send a raw file reply
require
valid_f: f /= Void
do
-- this is not quite right....
f.open_read
from
answer.set_reply_text ("")
until f.end_of_file
loop
f.read_stream (1024)
answer.append_reply_text (f.last_string)
end
f.close
end
end

View File

@@ -0,0 +1,115 @@
deferred class HTTP_REQUEST_HANDLER
inherit
ANY
redefine
default_create
end
feature {NONE} -- Initialization
default_create
do
Precursor
create request_uri.make_empty
create script_name.make_empty
create query_string.make_empty
create answer
create headers.make (0)
end
feature -- Access
request_uri: STRING
-- requested url
script_name: STRING
-- Script name
query_string: STRING
-- Query string
data: detachable STRING
-- the entire request message
headers : HASH_TABLE [STRING, STRING]
-- Provides access to the request's HTTP headers, for example:
-- headers["Content-Type"] is "text/plain"
answer: HTTP_RESPONSE
-- reply to this request
feature -- Execution
process
-- process the request and create an answer
require
valid_uri: request_uri /= Void
deferred
end
feature -- Recycle
reset
-- reinit the fields
do
request_uri.wipe_out
script_name.wipe_out
query_string.wipe_out
data := Void
answer.reset
end
feature -- Element change
set_uri (new_uri: STRING)
-- set new URI
require
valid_uri: new_uri /= Void
local
p: INTEGER
do
request_uri := new_uri
p := new_uri.index_of ('?', 1)
if p > 0 then
script_name := new_uri.substring (1, p - 1)
query_string := new_uri.substring (p + 1, new_uri.count)
else
script_name := new_uri.string
query_string := ""
end
end
set_data (new_data: STRING)
-- set new data
do
data := new_data
end
set_headers ( a_header : HASH_TABLE [STRING, STRING] )
do
headers := a_header
end
feature {NONE} -- Implementation
real_filename (fn: STRING): STRING
-- Real filename from url-path `fn'
--| Find a better design for this piece of code
--| Eventually in a spec/$ISE_PLATFORM/ specific cluster
do
if {PLATFORM}.is_windows then
create Result.make_from_string (fn)
Result.replace_substring_all ("/", "\")
if Result[Result.count] = '\' then
Result.remove_tail (1)
end
else
Result := fn
if Result[Result.count] = '/' then
Result := Result.substring (1, Result.count - 1)
end
end
end
end

View File

@@ -0,0 +1,42 @@
note
description: "Summary description for {POST_REQUEST_HANDLER}."
author: ""
date: "$Date$"
revision: "$Revision$"
class
POST_REQUEST_HANDLER
inherit
GET_REQUEST_HANDLER
redefine
process
end
create
make
feature -- Execution
process
-- process the request and create an answer
local
l_data: STRING
s: STRING
n: INTEGER
do
from
n := 1_024
input.read_stream (n)
s := input.last_string
create l_data.make_empty
until
s.count < n
loop
l_data.append_string (s)
input.read_stream (n)
end
Precursor
end
end

View File

@@ -0,0 +1,144 @@
class HTTP_RESPONSE
inherit
HTTP_CONSTANTS
redefine
default_create
end
create
default_create
feature -- creation
default_create
do
Precursor
set_defaults
end
set_defaults
-- Set default values for the reply
do
status_code := ok
create content_length_data.make_empty
reason_phrase := ok_message
content_type_data := text_html
set_reply_text (Void)
end
feature -- Recycle
reset
do
set_defaults
end
feature -- response header fields
status_code: STRING
-- status
content_length_data : STRING
-- length
reason_phrase: STRING
-- message, if any
content_type_data: STRING
-- type of content in this reply (eg. text/html)
feature -- Element change
set_content_length (new_content_length: INTEGER)
require
positive_or_zero: new_content_length >= 0
do
content_length_data := new_content_length.out
end
set_status_code (new_status_code: STRING)
require
not_void: new_status_code /= Void
do
status_code := new_status_code
end
set_reason_phrase (new_reason_phrase: STRING)
require
not_void: new_reason_phrase /= Void
do
reason_phrase := new_reason_phrase
end
set_content_type (new_content_type: STRING)
require
not_void: new_content_type /= Void
do
content_type_data := new_content_type
end
feature -- Access: send reply
reply_header: STRING
-- header
do
Result := http_version_1_1.twin
Result.extend (' ')
Result.append (status_code)
Result.extend (' ')
Result.append (reason_phrase)
Result.append (crlf)
Result.append ({HTTP_SERVER_CONFIGURATION}.Server_details)
Result.append (crlf)
Result.append (Content_type + ": ")
Result.append (content_type_data)
Result.append (crlf)
Result.append (Content_length + ": ")
Result.append (content_length_data)
Result.append (crlf)
Result.append (crlf)
-- TODO: could add the size of data being sent here and
-- then keep the connection alive
end
reply_header_continue: STRING
-- header
do
Result := http_version_1_1.twin
Result.extend (' ')
Result.append (status_code)
Result.extend (' ')
Result.append (continue_message)
Result.append (crlf)
Result.append (crlf)
-- TODO: could add the size of data being sent here and
-- then keep the connection alive
end
reply_text: STRING
-- reply text
feature -- Change element: send reply
set_reply_text (new_text: detachable STRING)
-- text could be Void
do
if new_text = Void then
create reply_text.make_empty
else
reply_text := new_text
end
end
append_reply_text (more_text: STRING)
-- add more text to the reply
require
reply_text /= Void
more_text /= Void
do
reply_text.append (more_text)
end
end

View File

@@ -0,0 +1,13 @@
class SHARED_HTTP_REQUEST_HANDLERS
feature
http_request_handlers: HASH_TABLE [HTTP_REQUEST_HANDLER, STRING]
local
a_handler: HTTP_REQUEST_HANDLER
once
create Result.make (5)
create {GET_REQUEST_HANDLER} a_handler
Result.put (a_handler, "GET")
end
end

View File

@@ -0,0 +1,15 @@
note
description: "Summary description for {SHARED_URI_CONTENTS_TYPES}."
author: ""
date: "$Date$"
revision: "$Revision$"
class
SHARED_URI_CONTENTS_TYPES
feature
ct_table: URI_CONTENTS_TYPES
once
create Result.make
end
end

32
src/tcp_stream_socket.e Normal file
View File

@@ -0,0 +1,32 @@
note
description: "Summary description for {TCP_STREAM_SOCKET}."
date: "$Date$"
revision: "$Revision$"
class
TCP_STREAM_SOCKET
inherit
NETWORK_STREAM_SOCKET
create
make_server_by_port
create {NETWORK_STREAM_SOCKET}
make_from_descriptor_and_address
feature -- Basic operation
send_message (a_msg: STRING)
local
a_package : PACKET
a_data : MANAGED_POINTER
c_string : C_STRING
do
create c_string.make (a_msg)
create a_data.make_from_pointer (c_string.item, a_msg.count + 1)
create a_package.make_from_managed_pointer (a_data)
send (a_package, 1)
end
end

88
src/uri_contents_types.e Normal file
View File

@@ -0,0 +1,88 @@
class URI_CONTENTS_TYPES
create
make
feature
content_types: HASH_TABLE [STRING, STRING]
extension (uri: STRING): STRING
-- extract extendion from a URI
local
i: INTEGER
do
-- going from the end find the position of the "."
from
i := uri.count
until
i = 0 or else uri.item (i) = '.'
loop
i := i - 1
end
Result := uri.substring (i+1, uri.count)
end
feature {NONE}
make
do
create content_types.make (30)
content_types.put ("text/html", "html")
content_types.put ("text/html", "htm")
content_types.put ("image/gif", "gif")
content_types.put ("image/jpeg", "jpeg")
content_types.put ("image/png", "jpg")
content_types.put ("image/png", "png")
end
feature -- Access: Encoding
urlencode (s: STRING): STRING
-- URL encode `s'
do
Result := s.string
Result.replace_substring_all ("#", "%%23")
Result.replace_substring_all (" ", "%%20")
Result.replace_substring_all ("%T", "%%09")
Result.replace_substring_all ("%N", "%%0A")
Result.replace_substring_all ("/", "%%2F")
Result.replace_substring_all ("&", "%%26")
Result.replace_substring_all ("<", "%%3C")
Result.replace_substring_all ("=", "%%3D")
Result.replace_substring_all (">", "%%3E")
Result.replace_substring_all ("%"", "%%22")
Result.replace_substring_all ("%'", "%%27")
end
urldecode (s: STRING): STRING
-- URL decode `s'
do
Result := s.string
Result.replace_substring_all ("%%23", "#")
Result.replace_substring_all ("%%20", " ")
Result.replace_substring_all ("%%09", "%T")
Result.replace_substring_all ("%%0A", "%N")
Result.replace_substring_all ("%%2F", "/")
Result.replace_substring_all ("%%26", "&")
Result.replace_substring_all ("%%3C", "<")
Result.replace_substring_all ("%%3D", "=")
Result.replace_substring_all ("%%3E", ">")
Result.replace_substring_all ("%%22", "%"")
Result.replace_substring_all ("%%27", "%'")
end
stripslashes (s: STRING): STRING
do
Result := s.string
Result.replace_substring_all ("\%"", "%"")
Result.replace_substring_all ("\'", "'")
Result.replace_substring_all ("\/", "/")
Result.replace_substring_all ("\\", "\")
end
end