views:

70

answers:

1

I try to make two servers in a file, but they are fighting each other visibly have anyone an idea to make them peace ? here is my code :

# -*- coding: utf-8 -*-
import socket
import sys
import re
import base64
import binascii
import time
import zlib
import sys
import StringIO
import contextlib
import smtplib
from threading import Thread
"""
Thanks to :
People from irc :
Flox,Luyt
People from stack Overflow :
Philippe Leybaert,Platinum Azure,methodin,Suresh Kumar,S.Lott,MatTheCat,
kevpie,Ignacio Vazquez-Abrams,adamk,Frédéric Hamidi,THC4k,THC4k,Blam
"""
def sendmail(exp,dest,msg):
    server = dest.split("@")[1]
    s = smtplib.SMTP("localhost")
    s.sendmail(exp,dest,msg)


@contextlib.contextmanager
def stdoutIO(stdout=None):
    old = sys.stdout
    if stdout is None:
        stdout = StringIO.StringIO()
    sys.stdout = stdout
    yield stdout
    sys.stdout = old



class Serversmtp(Thread):
    def __init__self(self):
        Thread.__init__(self)
    def run(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_address = ('localhost', 25)
        print >>sys.stderr, 'starting up on %s port %s' % server_address
        self.sock.bind(server_address)

        # Listen for incoming connections
        self.sock.listen(1)
        self.message = ""
        while True:
            # Wait for a connection
            print >>sys.stderr, 'waiting for a connection'
            connection, client_address = self.sock.accept()
            try:
                print >>sys.stderr, 'connection from', client_address

                # Receive the data in small chunks and retransmit it
                while True:
                    data = connection.recv(1024)
                    print >>sys.stderr, 'received "%s"' % data
                    if data:
                        self.message = self.traitement(data)
                        connection.sendall(self.message)
                        connection.close()
                        connection, client_address = self.sock.accept()

                    else:
                        print >>sys.stderr, 'no more data from', client_address
                        break

            finally:
                # Clean up the connection
                connection.close()
                self.sock.close()
class Pages :

    def root(self,cgi=None):
        return """eNqtVV1zqkgQfedX3MrrbNVREBnu5ubWCCoajPiRaHyTxEGNiAKC8uu3B7Nb+7JvO1QNNAOnT5/u
6Xnc5vHhSXsMk8/bk5bv7tdjmNK7XRz9yNKP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1s7jcFdL7+5rryHx5Pjkf
SMxaS/t/sGom2c/mkX7PNvf6NC40lhFaqTj7TArfPmlyprpU58ANyLr7J2669QcyFjSTkdnGDI/0
izmIMrqF7PYHtAd8/LhWeBtNTj1l0rlzja6DO1asvESKmpDzYKmkrOPS+39hmT3Td2zbtG26kzMb
FF0bFd+XKi58We6mr3uvqGgAQyVQ1hSGkRCNMdEIi0a/2yDa57HyFYTWKDo2mHzz9Cxif/+h76L7
lzipaVfkbBLLcITnxo9LPhHxMKD/QeQfHOrtILg+k88eTeH8kUqxlGQ0miCv8KT2aZqTWsNU03yl
RjR3s6H+93C5/wIoQoi6"""

class Serverhttp(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.Pages = Pages()
        self.GET = re.compile("GET.*?HTTP")
        self.POST = re.compile("POST.*?HTTP")
        self.balisep = re.compile("<\?.*\?>",re.DOTALL)

    def run(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_address = ('localhost', 41000)
        print >>sys.stderr, 'starting up on %s port %s' % server_address
        self.sock.bind(server_address)

        # Listen for incoming connections
        self.sock.listen(1)
        self.message = ""
        while True:
            # Wait for a connection
            print >>sys.stderr, 'waiting for a connection'
            connection, client_address = self.sock.accept()
            try:
                print >>sys.stderr, 'connection from', client_address

                # Receive the data in small chunks and retransmit it
                while True:
                    data = connection.recv(1024)
                    print >>sys.stderr, 'received "%s"' % data
                    if data:
                        self.message = self.traitement(data)
                        connection.sendall(self.message)
                        connection.close()
                        connection, client_address = self.sock.accept()

                    else:
                        print >>sys.stderr, 'no more data from', client_address
                        break

            finally:
                # Clean up the connection
                connection.close()
                self.sock.close()

    def decompress_img(self,img):
        img = zlib.decompress(base64.decodestring(img))
        return img
    def decompress_html(self,html) :
        page = "HTTP/1.0 200 OK\r\nContent-type:text/html;charset=utf8\r\n\r\n"
        page+=zlib.decompress(base64.decodestring(html))
        commands = self.balisep.findall(page)
        print commands
        for c in commands :
            command = c.replace("<? ","")
            command = c.replace("<?","")
            command = command.replace(" ?>","")
            command = command.replace("?>","")
            print command
            with stdoutIO() as s:
                exec(command)
            page = page.replace(c,s.getvalue())
        return page

    def traitement(self,data):

        url = self.POST.findall(data)
        print url
        print len(url)
        url = self.GET.findall(data)
        print url
        url = url[0].replace("GET","")
        url = url.replace("POST","")
        url = url.replace("HTTP","")
        url = url.replace(" ","")
        print url
        if url == "/favicon.ico":
            return self.decompress_img(self.Pages.favico())
        else :
            return self.decompress_html(self.Pages.root())
if __name__ == "__main__":
    swww = Serverhttp()
    swww.start()
    ssmtp = Serversmtp()
    ssmtp.start()
    sendmail("[email protected]","[email protected]","hello")
    print "toto"

Regards and thanks all people

A: 

it was better to use : SocketServer.BaseRequestHandler with handler and one for each server :

as seen here :

# MetaProject v 0.21
# -*- coding: utf-8 -*-
import socket
import sys
import re
import base64
import binascii
import time
import zlib
import sys
import StringIO
import contextlib
import smtplib
import threading
import SocketServer
SocketServer.TCPServer.allow_reuse_address = True 

"""
Thanks to :
People from irc :
Flox,Luyt
People from stack Overflow (http://stackoverflow.com/):
Philippe Leybaert,Platinum Azure,methodin,Suresh Kumar,S.Lott,MatTheCat,
kevpie,Ignacio Vazquez-Abrams,adamk,Frédéric Hamidi,THC4k,THC4k,Blam,bstpierre
"""

def sendmail(exp,dest,msg):
    server = dest.split("@")[1]
    s = smtplib.SMTP("localhost")
    s.sendmail(exp,dest,msg)



@contextlib.contextmanager
def stdoutIO(stdout=None):
    old = sys.stdout
    if stdout is None:
        stdout = StringIO.StringIO()
    sys.stdout = stdout
    yield stdout
    sys.stdout = old





class Serversmtp(SocketServer.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024)
        socket = self.request
        print "%s wrote:" % self.client_address[0]
        self.data = self.traitement(self.data)
        socket.sendto(self.data, self.client_address)

    def traitement(self,data):
        return "toto"


class Pages :
    def __init__(self):
        self.balisep = re.compile("<\?.*\?>",re.DOTALL)
    def root(self,cgi=None):
        return self.decompress_html("""eNqzySjJzbHjsknKT6m04yrJhECbpCKgWGZuukJxUbKtUlpiWWZyfp4ekFCyg8jZcxUUZeaVKCiV
5JfkK2krgUSVuOztuLhs9CFm2eiDjQYAG5wecg==""")

    def faviconico(self):
        return self.decompress_img("""eNqdk39MVWUYx99zDrZkJJc/dGtqsVZKFmttFhcuF0wXC1bTZmq0qVuWa8t+/NXPW1MQCk3FMBKs
LNauoq6AAr2zsFLLHAN1YQXJryzJewXuhV29HO759JyX//uj9933vOe8e7/f5/k+73OUMmR6PEqe
meq5FKXmKKWyBLIlO9P7/zUiEzaB02GWt43ycHOUx2St6YwTtxP0DZ6n+LV5LH5DURgwWRJQ5L+p
eEi+Xa4zZbP+aD9pByLMaR5jdkuUuV9NcNuhKIFTI4DD0bON3P+Kha/coLDMouAtRYHwl72u6IvE
mNvwG57QddJCUdJbY6S3jGmN+w5fYTwhCnackor55FZK3AqTfFmXbDbxSx4T9g1ygh2or0cxTzuk
nrSZ2R5HHbpKSVMvjuPAlMOq3XexuErh26HwC3/ZlhmShwFJOPfPON6mTlKb+lGtf2J+McSixov8
Hom6VAaGf6Ww8hZyq8X7exb+KpOCCvGwRXHueJDkSFj77B6bpOnSMLVdfVwdv4477KlJXggWs2iH
gbdG4otG7nbx8K5oicbO4jv4eJ2XlrdX8131i4z0dIlSUqZDOBbm+YNFZAs3v1a4NdPw7xJsE2xV
NJQu5PNV8/ik5Gb2PpJBdLhfe74cGeTx+gVk75F4H5r4BF55970vddtl4JccvFKPg6tn89FyD8GX
ltLesFX7tSXvn3tOcPurJg/sU+TUCeol3z2GhteNv92g4B2D/esWcrH9CI7UMREbpe/Ep1wb6tEe
6o5VcG+ZxKy3yNtrkSMecgV5u6UPxMdS4V8b7NW1i0eHad2UxfEnFKG1s7jcFdL7+5rryHx5Pjkf
SMxaS/t/sGom2c/mkX7PNvf6NC40lhFaqTj7TArfPmlyprpU58ANyLr7J2669QcyFjSTkdnGDI/0
izmIMrqF7PYHtAd8/LhWeBtNTj1l0rlzja6DO1asvESKmpDzYKmkrOPS+39hmT3Td2zbtG26kzMb
FF0bFd+XKi58We6mr3uvqGgAQyVQ1hSGkRCNMdEIi0a/2yDa57HyFYTWKDo2mHzz9Cxif/+h76L7
lzipaVfkbBLLcITnxo9LPhHxMKD/QeQfHOrtILg+k88eTeH8kUqxlGQ0miCv8KT2aZqTWsNU03yl
RjR3s6H+93C5/wIoQoi6""")




    def toto(self):
        return self.decompress_html("""eNqzySjJzbHjsknKT6m04yrLLy1WSC1JLVZIVCjJL8nnstGHSNjog9UBAGolDzo=""")

    def p404(self):
        return self.decompress_html("""eNqzySjJzbHjsknKT6m04zIxMFFIScwrVihJVEhLTE5VUOSy0YdI2eiDVQIAZBgOeA==""")

    def decompress_img(self,img):
        img = zlib.decompress(base64.decodestring(img))
        return img

    def decompress_html(self,html) :
        page = "HTTP/1.0 200 OK\r\nContent-type:text/html;charset=utf8\r\n\r\n"
        page+=zlib.decompress(base64.decodestring(html))
        commands = self.balisep.findall(page)
        print commands
        for c in commands :
            command = c.replace("<? ","")
            command = c.replace("<?","")
            command = command.replace(" ?>","")
            command = command.replace("?>","")
            print command
            with stdoutIO() as s:
                exec(command)
            page = page.replace(c,s.getvalue())
        return page

class Serverhttp(SocketServer.BaseRequestHandler):
    def handle(self):
        self.Pages = Pages()
        self.GET = re.compile("GET.*?HTTP")
        self.POST = re.compile("POST.*?HTTP")
        self.data = self.request.recv(1024)
        socket = self.request
        print "%s wrote:" % self.client_address[0]
        self.data = self.traitement(self.data)
        socket.sendto(self.data, self.client_address)             

    def traitement(self,data):
        url = self.POST.findall(data)
        url = self.GET.findall(data)
        url = url[0].replace("GET","")
        url = url.replace("POST","")
        url = url.replace("HTTP","")
        url = url.replace(" ","")
        url = re.sub(r"^/","",url)
        url = re.sub(r"\.","",url)
        if url != "":
            urls = url.split("/")
            if len(urls) != 0 :
                print urls
                url = urls[0]
        print "url %s"%url
        if url == "" :
            return self.Pages.root()
        elif url in dir(self.Pages) and url != "":
            return getattr(self.Pages,url)()
        else :
            return self.Pages.p404()

def serve_thread(host, port):
    if port == 4242 :
        server = SocketServer.TCPServer((host, port), Serverhttp,bind_and_activate=True)
    elif port == 25 :
        server = SocketServer.TCPServer((host, port), Serversmtp,bind_and_activate=True)
    server.serve_forever()





if __name__ == "__main__":
    threading.Thread(target=serve_thread,args=('localhost', 4242)).start()
    threading.Thread(target=serve_thread,args=('localhost', 25)).start()
    print "toto"