'''
hmap.py

Copyright 2006 Andres Riancho

This file is part of w3af, w3af.sourceforge.net .

w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.

w3af is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with w3af; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

'''

import core.controllers.outputManager as om
from core.controllers.basePlugin.baseDiscoveryPlugin import baseDiscoveryPlugin
import core.data.kb.knowledgeBase as kb
import plugins.discovery.oHmap.hmap as originalHmap
import core.data.parsers.urlParser as urlParser
from core.controllers.w3afException import w3afRunOnce

class hmap(baseDiscoveryPlugin):
	'''
	This plugin fingerprints the server type, i.e apache, iis, tomcat, etc.
	@author: Andres Riancho ( andres.riancho@gmail.com )
	'''
	
	'''
	It uses fingerprinting, not just the Server header returned by remote server.
	This plugin is a wrapper for Dustin Lee's hmap.
	
	@author: Andres Riancho ( andres.riancho@gmail.com )
	'''

	def __init__(self):
		baseDiscoveryPlugin.__init__(self)
		self._execOneTime = True
		self._exec = True
		self._matchCount = 1
		self._genFpF = False

	def discover(self, fuzzableRequest ):
		'''
		It calls the "main" from hmap and writes the results to the kb.
		
		@parameter fuzzableRequest: A fuzzableRequest instance that contains (among other things) the URL to test.
		'''
		if not self._exec:
			# This will remove the plugin from the discovery plugins to be runned.
			raise w3afRunOnce()
		else:
	
			if self._execOneTime:
				self._exec = False
			
			om.out.information('Hmap plugin is starting. Fingerprinting may take a while.')
			
			ssl = False
			url = fuzzableRequest.getURL()
			protocol = urlParser.getProtocol( url )
			server = urlParser.getDomain( url )
			if server.count(':'):
				port = int( server.split(':')[1] )
				server = server.split(':')[0]
			else:
				if protocol == 'https':
					port = 443
					ssl = True
				else:
					port = 80
			
			results = originalHmap.testServer( ssl, server, port, self._matchCount, self._genFpF )
			
			server = results[0]
			# Output the results
			om.out.information('The most accurate fingerprint for this HTTP server is: ' + server )

			# Save the results in the KB so that other plugins can use this information
			kb.kb.save( self , 'server' , server )
			
			# Fingerprint file generated
			if self._genFpF:
				om.out.information('Fingerprint file generated, please send a mail to w3af.project@gmail.com including'+
				' the fingerprint file, your name and what server you fingerprinted. New fingerprints make hmap plugin'+
				' more powerfull and accurate.')
			
		return []
		
	def getOptionsXML(self):
		'''
		This method returns a XML containing the Options that the plugin has.
		Using this XML the framework will build a window, a menu, or some other input method to retrieve
		the info from the user. The XML has to validate against the xml schema file located at :
		w3af/core/ui/userInterface.dtd
		
		@return: XML with the plugin options.
		'''	
		return	'<?xml version="1.0" encoding="ISO-8859-1"?>\
		<OptionList>\
			<Option name="genFpF">\
				<default>'+str(self._genFpF)+'</default>\
				<desc>Generate a fingerprint file.</desc>\
				<type>boolean</type>\
				<help>Define if we will generate a fingerprint file based on the findings made during this execution.</help>\
			</Option>\
		</OptionList>\
		'

	def setOptions( self, optionsMap ):
		'''
		This method sets all the options that are configured using the user interface 
		generated by the framework using the result of getOptionsXML().
		
		@parameter OptionList: A dictionary with the options for the plugin.
		@return: No value is returned.
		'''	
		self._genFpF = optionsMap['genFpF']

	def getPluginDeps( self ):
		'''
		@return: A list with the names of the plugins that should be runned before the
		current one.
		'''
		# I dont really use the serverType plugin here, but it is nice to have two
		# opinions about what we are dealing with.
		return ['discovery.serverHeader']
	
	def getLongDesc( self ):
		'''
		@return: A DETAILED description of the plugin functions and features.
		'''
		return '''
		This plugin fingerprints the remote web server and tries to determine the
		server type, version and patch level.
		
		One configurable parameters exist:
			- genFpF
		'''
