#!/usr/bin/env python2

"""
Module WebServer for Inguma
Copyright (c) 2008 Hugo Teso <hugo.teso@gmail.com>

License is GPL
"""

import sys, os, urllib2, SimpleHTTPServer, SocketServer, re

from lib.libexploit import CIngumaModule

name = "webserver"
brief_description = "A simple Web Server and Crawler, usefull if used with DnsSpoof module"
type = "gather" # The type of a module, currently, can only be 'gather', 'exploit', 'discover', 'fuzz' or 'brute'

globals = ["crawl",  "path"]

class CWebServer(CIngumaModule):
    """ The example module. The main class will always starts with the character "C". Any other class will be ignored """

    crawl = False
    target = ""
    port = 80
    path = "data/web/"

    def help(self):
        """ This is the entry point for info <module> """
        print "crawl = <True/False>"
        print "target = <target URL to crawl if True>"
        print "port = <server port>"
        #print "directory = <path to web files>"

    def run(self):
        """ This is the main entry point of the module """
        print "Crawl %s" % self.crawl
        if self.crawl:
            print "Crawling page: " + self.target
            page = urllib2.urlopen(self.target)
            text = page.read()
            page.close()
            
            #Parse some links
            href = '<a href="(?!http://)'
            src = '<img src=(?!http://)'
            #Parse image links
            print "Parsing image links..."
            objRe = re.compile(src, re.IGNORECASE)
            text = objRe.sub('<img src=' + self.target, text)
            #Parse href links
            print "Parsing href links..."
            objRe = re.compile(src, re.IGNORECASE)
            text = objRe.sub('<a href=' + self.target, text)
            
            #FIXME: Hugo Fixme!!!
            os.chdir('./data/web/')
            file = open("index.html",  'w')
            print "Crawled page saved at " + os.getcwd() + "/index.html"
            file.write(text)
            os.chdir('../../')
            file.close()
        
        os.chdir('./data/web/')
        Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
        httpd = SocketServer.TCPServer(("", self.port), Handler)
        print "serving at port", self.port
        httpd.serve_forever()
        os.chdir('../../')
        
        return False

    def printSummary(self):
        """ If the method run of the module returns True printSummary will called after """
        pass
