Vote/Hub Proxy

Dieses Thema im Forum "Programmierung" wurde erstellt von Crafter6432, 15. März 2013.

  1. Crafter6432
    Offline

    Crafter6432

    Registriert seit:
    22. Dezember 2011
    Beiträge:
    686
    Ich hab mir, weil ich nun 3 Server betreibe und die Liste nur 1 Vote/Tag zulässt ein Proxy geschrieben, dass einen Vote dupliziert und an alle in der Config eingestellten Server weiterleitet. Außerdem wird verhindert, dass wenn die Liste spinnt nicht jeder X-mal etwas für das voten bekommt.Sollte mal einer der Ziel Server offline sein wird so lange versucht den Vote zu senden, bis das Timeout erreicht wird oder Vote ankommt

    proxy.py
    Code (Text):
    1.  
    2. import SocketServer
    3. import re
    4. import traceback
    5. import socket
    6. import sys
    7. import time
    8. import datetime
    9. import ConfigParser, os
    10. from thread import start_new_thread
    11. import threading, Queue
    12. from warnings import filterwarnings
    13. from Crypto.PublicKey import RSA
    14. class VoteProxy(SocketServer.ThreadingTCPServer):
    15.     def __init__(self, server_address, RequestHandlerClass, decrypt,encrypt, targets,voteoptions):
    16.         self.decrypt = decrypt
    17.         self.encrypt = encrypt
    18.         self.targets = targets
    19.         self.delivertimeout = datetime.timedelta(seconds=voteoptions[0])
    20.         self.voteinterval = datetime.timedelta(seconds=voteoptions[1])
    21.         self.voters = {}
    22.         SocketServer.ThreadingTCPServer.__init__(self, server_address, RequestHandlerClass)
    23.     def shutdown(self):
    24.       self.delivertimeout = datetime.timedelta(seconds=1)
    25.       self.__shutdown_request = True
    26.       SocketServer.ThreadingTCPServer.shutdown(self)
    27. class VoteCatcher(SocketServer.BaseRequestHandler):  
    28.     def readString(self,s,pos):
    29.         n=""
    30.         for i in range(pos,len(s)):
    31.                 if s[i] == '\n':
    32.                         return n
    33.                 n=n+s[i]
    34.     def handle(self):
    35.         self.request.send("VOTIFIER 1.9")
    36.         data = self.request.recv(256)
    37.         #print self.server.decrypt.decrypt(data)
    38.         block = self.server.decrypt.decrypt(data)
    39.         pos = 0
    40.         optcode = ""
    41.         trys=0
    42.         while not"VOTE" in optcode and trys<10:
    43.                 optcode = self.readString(block,pos)
    44.                 pos=pos+len(optcode)+1
    45.                 trys=trys+1
    46.         if trys == 10:
    47.                 print "Invalid vote dump:"
    48.                 print block.encode('base64')
    49.                 return
    50.         #print optcode
    51.         service = self.readString(block,pos)
    52.         pos=pos+len(service)+1
    53.         #print service
    54.         username = self.readString(block,pos)
    55.         pos=pos+len(username)+1
    56.         #print username
    57.         address = self.readString(block,pos)
    58.         pos=pos+len(address)+1
    59.         timestamp = self.readString(block,pos)
    60.         #print timestamp
    61.         voter = self.server.voters.get(username)
    62.         if not voter == None:
    63.                 if voter.has_key(service):
    64.                         if datetime.datetime.now()-voter.get(service)<self.server.voteinterval:
    65.                                 print username + " Votes too fast!"
    66.                                 return
    67.                         voter.update({service:datetime.datetime.now()})                              
    68.         else:
    69.                         voter = {service:datetime.datetime.now()}
    70.                         self.server.voters.update({username:voter})            
    71.         if timestamp == None or len(timestamp) == 0:
    72.                 timestamp = time.time()                        
    73.         print str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))+" Vote from: " + str(service) + " player: " + str(username) + " ip: " + str(address)
    74.         for t in self.server.targets:
    75.                      if(len(t.split(":")) == 2):
    76.                         #self.forwardVote(user,userip,service,timestamp,t.split(":")[0],int(t.split(":")[1]))
    77.                         self.forwardVote(data,t.split(":")[0],int(t.split(":")[1]))
    78.                      else:
    79.                         #self.forwardVote(user,userip,service,timestamp,t.split(":")[0],8192)
    80.                         self.forwardVote(data,t.split(":")[0],8192)  
    81.     #def forwardVote(self,user,userip,service,timestamp,destip,destport):
    82.     def forwardVote(self,data,destip,destport):
    83.         start_time = datetime.datetime.now()
    84.         while (datetime.datetime.now()-start_time)<self.server.delivertimeout:
    85.                 try:
    86.                   con = socket.create_connection((destip,destport), socket.AF_INET)
    87.                   con.send(data)
    88.                   con.close()
    89.                   return
    90.                 except Exception, e:
    91.                   if datetime.datetime.now()-start_time < datetime.timedelta(seconds=1):
    92.                         print "Failed to connect " + destip+":"+str(destport)
    93.                   time.sleep(1.05)
    94. def file_get_contents(filename):
    95.     with open(filename) as f:
    96.         return f.read()
    97. def file_exists(filename):
    98.         try:
    99.                 with open(filename) as f: pass
    100.         except IOError as e:
    101.                 return False
    102.         return True
    103. if not file_exists('proxy.cfg'):
    104.         print "proxy.cfg not found"
    105.         sys.exit(0)
    106. config = ConfigParser.ConfigParser()
    107. config.readfp(open('proxy.cfg'))
    108. vinterval = config.getint("Proxy","vote-interval")
    109. bind = (config.get("Proxy","address"),config.getint("Proxy","port"))
    110. keys = (config.get("Proxy","public-key"),config.get("Proxy","private-key"))
    111. dtimeout = config.getint("Proxy","deliver-timeout")
    112. vinterval = config.getint("Proxy","vote-interval")
    113. targets = []
    114. for t in config.get("Proxy","targets").split(","):
    115.         targets.append(t)
    116. print str(len(targets)) + " targets loaded!"
    117. if not file_exists(keys[0]):
    118.         print "Public key not found"
    119.         sys.exit(0)
    120. if not file_exists(keys[1]):
    121.         print "Private key not found"
    122.         sys.exit(0)
    123. pub = "-----BEGIN PUBLIC KEY-----\n" + file_get_contents(keys[0]) + "\n\n-----END PUBLIC KEY-----"
    124. priv = "-----BEGIN PRIVATE KEY-----\n"+ file_get_contents(keys[1]) + "\n\n-----END PRIVATE KEY-----"
    125. decrypt = RSA.importKey(priv)
    126. encrypt = RSA.importKey(pub)
    127. server = None
    128. try:
    129.         server = VoteProxy((bind[0], bind[1]),VoteCatcher,decrypt,encrypt,targets,(dtimeout,vinterval))
    130.         print "Listening on: " + bind[0] + ":" + str(bind[1])
    131. except Exception, e:
    132.         print "Can't bind server to: " + bind[0] + ":" + str(bind[1])    
    133.         sys.exit(0)  
    134. try:                                
    135.         server.serve_forever()
    136. except KeyboardInterrupt, e:
    137.         server.shutdown()
    138.         print ""
    139.         sys.exit(0)
    140.  
    proxy.cfg
    Code (Text):
    1.  
    2. [Proxy]
    3. address: 0.0.0.0
    4. port: 8192
    5. public-key: public.key
    6. private-key: private.key
    7. targets: 127.0.0.1:8193,127.0.0.1:8194,127.0.0.1:8195
    8. deliver-timeout: 3600
    9. vote-interval: 3600
    10.  
    Voraussetzungen:
    Python 2.7.3 (3.3 wird nicht unterstützt!)
    pycrypto-2.6 (Die Version aus dem Ubuntu Repo ist zu alt!)
     
    #1
    1 Person gefällt das.