<commit_before>--[[
	
	Nonsence Asynchronous event based Lua Web server.
	Author: <NAME> < <EMAIL> >
	
	This module "HTTPServer" is a part of the Nonsence Web server.
	< https://github.com/JohnAbrahamsen/nonsence-ng/ >
	
	Nonsence is licensed under the MIT license < http://www.opensource.org/licenses/mit-license.php >:

	"Permission is hereby granted, free of charge, to any person obtaining a copy of
	this software and associated documentation files (the "Software"), to deal in
	the Software without restriction, including without limitation the rights to
	use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
	of the Software, and to permit persons to whom the Software is furnished to do
	so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE."

  ]]
  
-------------------------------------------------------------------------
--
-- Load modules
--
local log = assert(require('log'), 
	[[Missing log module]])
local nixio = assert(require('nixio'),
	[[Missing required module: Nixio (https://github.com/Neopallium/nixio)]])
local tcpserver = assert(require('tcpserver'), 
	[[Missing tcpserver module]])
local httputil = assert(require('httputil'), 
	[[Missing httputil module]])
local ioloop = assert(require('ioloop'), 
	[[Missing ioloop module]])
local iostream = assert(require('iostream'), 
	[[Missing iostream module]])
assert(require('middleclass'), 
	[[Missing required module: MiddleClass 
	https://github.com/kikito/middleclass]])
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-- Speeding up globals access with locals :>
-- 
local class, instanceOf, assert, ostime, type, char, insert, tonumber
= class, instanceOf, assert, os.time, type, char, table.insert, 
tonumber
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-- Table to return on require.
local httpserver = {}
-------------------------------------------------------------------------

local function _parse_post_arguments(data)
	assert(type(data) == "string", "data into _parse_post_arguments() not a string.")
	local arguments_string = data:match("?(.+)")
	local arguments = {}
	local noDoS = 0;
	for k, v in arguments_string:gmatch("([^&=]+)=([^&]+)") do
		noDoS = noDoS + 1;
		if (noDoS > 256) then break; end -- hashing DoS attack ;O
		v = v:gsub("+", " "):gsub("%%(%w%w)", function(s) return char(tonumber(s,16)) end);
		if (not arguments[k]) then
			arguments[k] = v;
		else
			if ( type(arguments[k]) == "string") then
				local tmp = arguments[k];
				arguments[k] = {tmp};
			end
			insert(arguments[k], v);
		end
	end
	return arguments
end

httpserver.HTTPServer = class('HTTPServer', tcpserver.TCPServer)

function httpserver.HTTPServer:init(request_callback, no_keep_alive, io_loop, xheaders,
	ssl_options, kwargs)
	--[[ 
	
		HTTPServer with heritage from TCPServer.
		
	  ]]
	
	self.request_callback = request_callback
	self.no_keep_alive = no_keep_alive or false
	self.xheaders = xheaders or false
	-- Init superclass TCPServer.
	tcpserver.TCPServer:init(io_loop, ssl_options, kwargs)
end

function httpserver.HTTPServer:handle_stream(stream, address)
	-- Redefine handle_stream method from super class TCPServer
	
	httpserver.HTTPConnection:new(stream, address, self.request_callback,
		self.no_keep_alive, self.xheaders)
end

httpserver.HTTPConnection = class('HTTPConnection')

function httpserver.HTTPConnection:init(stream, address, request_callback,
	no_keep_alive, xheaders)

	self.stream = stream
	self.address = address
	local function _wrapped_request_callback(data)
		-- This is needed to retain the context.
		request_callback(data)
	end
	self.request_callback = _wrapped_request_callback
	self.no_keep_alive = no_keep_alive or false
	self.xheaders = xheaders or false
	self._request = nil
	self._request_finished = false
	local function _wrapped_header_callback(data)
		-- This is needed to retain the context.
		self:_on_headers(data)
	end
	self._header_callback = _wrapped_header_callback
	self.stream:read_until("\r\n\r\n", self._header_callback)
	self._write_callback = nil
end

function httpserver.HTTPConnection:write(chunk, callback)
	-- Writes a chunk of output to the stream.<commit_msg>Added example usage and moved parse_post_arguments to httputil<commit_after>--[[
	
	Nonsence Asynchronous event based Lua Web server.
	Author: <NAME> < <EMAIL> >
	
	This module "HTTPServer" is a part of the Nonsence Web server.
	< https://github.com/JohnAbrahamsen/nonsence-ng/ >
	
	Nonsence is licensed under the MIT license < http://www.opensource.org/licenses/mit-license.php >:

	"Permission is hereby granted, free of charge, to any person obtaining a copy of
	this software and associated documentation files (the "Software"), to deal in
	the Software without restriction, including without limitation the rights to
	use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
	of the Software, and to permit persons to whom the Software is furnished to do
	so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE."

  ]]
  
-------------------------------------------------------------------------
--
-- Load modules
--
local log = assert(require('log'), 
	[[Missing log module]])
local nixio = assert(require('nixio'),
	[[Missing required module: Nixio (https://github.com/Neopallium/nixio)]])
local tcpserver = assert(require('tcpserver'), 
	[[Missing tcpserver module]])
local httputil = assert(require('httputil'), 
	[[Missing httputil module]])
local ioloop = assert(require('ioloop'), 
	[[Missing ioloop module]])
local iostream = assert(require('iostream'), 
	[[Missing iostream module]])
assert(require('middleclass'), 
	[[Missing required module: MiddleClass 
	https://github.com/kikito/middleclass]])
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-- Speeding up globals access with locals :>
-- 
local class, instanceOf, assert, ostime, type, char, insert, tonumber
, _parse_post_arguments = class, instanceOf, assert, os.time, type, 
char, table.insert, tonumber, httputil.parse_post_arguments
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-- Table to return on require.
local httpserver = {}
-------------------------------------------------------------------------

httpserver.HTTPServer = class('HTTPServer', tcpserver.TCPServer)

function httpserver.HTTPServer:init(request_callback, no_keep_alive, io_loop, xheaders,
	ssl_options, kwargs)
	--[[ 
	
		HTTPServer with heritage from TCPServer.
		
		Example usage:
		
		local httpserver = require('httpserver')
		local ioloop = require('ioloop')
		local ioloop_instance = ioloop.instance()

		-- Request handler function
		function handle_request(request)
			local message = "You requested: " .. request._request.path
			request:write("HTTP/1.1 200 OK\r\nContent-Length:" .. message:len() .."\r\n\r\n")
			request:write(message)
			request:finish()
		end

		http_server = httpserver.HTTPServer:new(handle_request)
		http_server:listen(8888)
		ioloop_instance:start()

	  ]]
	
	self.request_callback = request_callback
	self.no_keep_alive = no_keep_alive or false
	self.xheaders = xheaders or false
	-- Init superclass TCPServer.
	tcpserver.TCPServer:init(io_loop, ssl_options, kwargs)
end

function httpserver.HTTPServer:handle_stream(stream, address)
	-- Redefine handle_stream method from super class TCPServer
	
	httpserver.HTTPConnection:new(stream, address, self.request_callback,
		self.no_keep_alive, self.xheaders)
end

httpserver.HTTPConnection = class('HTTPConnection')

function httpserver.HTTPConnection:init(stream, address, request_callback,
	no_keep_alive, xheaders)

	self.stream = stream
	self.address = address
	local function _wrapped_request_callback(RequestObject)
		-- This is needed to retain the context.
		request_callback(RequestObject)
	end
	self.request_callback = _wrapped_request_callback
	self.no_keep_alive = no_keep_alive or false
	self.xheaders = xheaders or false
	self._request = nil
	self._request_finished = false
	local function _wrapped_header_callback(RequestObject)
		-- This is needed to retain the context.
		self:_on_headers(RequestObject)
	end
	self._header_callback = _wrapped_header_callback
	self.stream:read_until("\r\n\r\n", self._header_callback)
	self._write_callback = nil
end

function httpserver.HTTPConnection:write(chunk, callback)
	-- Writes a chunk of output to the stream.
{'fraction_non_alphanumeric': 0.17769857433808553, 'fraction_numerical': 0.001629327902240326, 'mean_word_length': 3.1023391812865495, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 16, 'https://': 6, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1515598', 'n_tokens_mistral': 2826, 'n_tokens_neox': 2718, 'n_words': 880}