description = [[
Performs a GET request for the root folder ("/") of a web server
and displays the value of the returned HTTP header, 'server'.
]]

---
-- @output
-- 80/tcp  open  http
-- |_http-server: Apache/2.2.15 (Unix)
-- 443/tcp open  https
-- |_http-server: lighttpd/1.4.19
--
-- Author: Michael Springer
-- Data: 01/08/2011
-- Email: mr.michael.springer () gmail com
--
-- References:
--  http-headers.nse
--  http-auth.nse

author = "Michael Springer"

license = "Same as Nmap--See http://nmap.org/book/man-legal.html"

categories = {"discovery", "safe"}

require "shortport"
require "http"

portrule = function(host, port)
	local svc = { std = { ["http"] = 1, ["http-alt"] = 1 },
				ssl = { ["https"] = 1, ["https-alt"] = 1 } }
	if port.protocol ~= 'tcp'
	or not ( svc.std[port.service] or svc.ssl[port.service] ) then
		return false
	end
	-- Don't bother running on SSL ports if we don't have SSL.
	if (svc.ssl[port.service] or port.version.service_tunnel == 'ssl')
	and not nmap.have_ssl() then
		return false
	end
	return true
end

action = function(host, port)
	local status = false
	local path  = "/"
	local result

	-- Check if the user didn't want HEAD to be used
	if(nmap.registry.args.useget == nil) then
		-- Try using HEAD first
		status, result = http.can_use_head(host, port, path)
	end

	-- If head failed, try using GET
	if(status == false) then
		stdnse.print_debug(1, "http-server.nse: HEAD request failed, falling back to GET")
		result = http.get(host, port, path)
	end

	if(result == nil) then
		if(nmap.debugging() > 0) then
			return "ERROR: Header request failed"
		else
			return nil
		end
	end

	if(result.rawheader == nil) then
		if(nmap.debugging() > 0) then
			return "ERROR: Header request didn't return a proper header"
		else
			return nil
		end
	end

	return result.header['server']

end
