#Masterserver v0.3 by Arsegg - 13.10.12
#(c) Arsegg, 2012
#Support HL&CS list + log file added by jesuspunk 27.12.2012
#Monitoring + VIP mod upgraded by xakep7 29.12.2012, fix sql query for amxmon 1.3.x 05.01.2013 by jesuspunk
#Mysql LOG and fix Errno 10054, some my erros... by jesuspunk - 28.01.13 - 0.3.5 beta 2
#Some MYSQL & CODE FIX by jesuspunk - 31.01.13 - 0.3.5 beta 3
#Some MYSQL FIX for support amxmon 1.4.09 by jesuspunk - 11.02.13 - 0.3.5 beta 4
#MONENGINE support, support for "turbo boost" technology(experemental only for monengine) by jesuspunk - 18.02.13 - 0.3.6 alpha 1
#socket.gaierror fix? + some fix in code by jesuspunk - 27.02.13 - 0.3.6 alpha 3
#add error log, fix crash than error start new thread. by jesuspunk - 01.03.13 - 0.3.6 alpha 4
#more stable code? + more erros logs 12.03.13 - 0.3.6 alpha 5
#remove experemental code of boost technology. fix console mesages - 27.03.13 - 0.3.6 beta 1
#cut packets for list of 5000 servers - 25.04.13 - 0.3.7 alpha 1
#add support for css and hl2, all list now can have about 5000 servers - 28.04.13 - 0.3.8 alpha 1 and alpha 2
#in amxmon mode if vip mode 0 first in list will be vip and top servers, fix cfg load - 12.05.13 -0.3.9 alpha 3
#NO PING for amxmon + corrects logs and new system of send data - 12.05.13 -0.3.9 alfa 4 experimental version
#update for anti flood system - 13.05.13 -0.3.9 alpha 4 experimental version 2
#update to support lightmon, add Random load of servers list for MYSQL, AMXMON, lightmon - 06.06.13 -0.4.0 alpha 1
#update to support lightmon - fix sql, add Random load of servers list for FILE mode - 07.06.13 -0.4.1 alpha 1
#update to support lightmon - fix sql query - 20.06.13 -0.4.1 alpha 2
#update to support monengine, add spport for webscript boost from miRror, add in config function to off cs 1.6, css or q3 list load and bind port see config. UPDATE CONFIG!!!! - 19.08.13 -0.4.2 alpha 1
#fix errors this monengine and webscript boost from miRror - 20.08.13 0.4.2 alpha 2
#fix sql query for webscript boost from miRror, add new mode: Custom Mysql Query(CMQ) and URL(list of servers recive by url). See config. UPDATE CONFIG!!!! - 26.08.13 v0.4.3 alpha 1
#critical fix, fix crash than add bad adress to database - - 31.08.13 0.4.3 beta 1
#custom addon(vip 2 for LM),small updates - 10.09.13 0.4.4 alpha 1
#custom addon(FILE2 mode), alpha 2 fix limit of 500 servers for FILE2 mode - 23.09.13 - 0.4.5 alpha 2
#Update code to lower case from config, add LM PLUS mode - 23.09.13 - 0.4.6 alpha 1
#Add console commands reload and stop, update critical fix from 0.4.3 beta 1 - 25.09.13 - 0.4.7 alpha 1
#fix mistakes - 0.4.7 alpha 2
#add stats threads - 0.4.7 alpha 3
#lm+ url fix - 0.4.7 alpha 4
#add cvar checknew version to config - 0.4.7 alpha 5
#add amxmon+ & cmq+ - 0.4.8 alpha 1
import pygeoip
global SigTerm
global SigTermGS
global SigTermS
global SigTermQ3
global SigTermC
global SigTermF
global Sigtermall
Sigtermall = 0
SigTerm = "0"
SigTermGS = 0
SigTermS = 0
SigTermQ3 = 0
SigTermC = 0
SigTermF = 0
global MassivIP
MassivIP = []
global cssdnewpacket
cssdnewpacket = []

try:
        import socket,MySQLdb,ConfigParser,sys,thread,threading,time,datetime,urllib2,random
except Exception, e:
        import socket,ConfigParser,sys,thread,time,datetime,urllib2
        cfg = ConfigParser.ConfigParser()
	cfg.read("ms.cfg")
        mode = cfg.get("OPTIONS","MODE")
        logerr = cfg.get("LOG","LOGERR")
	if mode == "file":
                error = str(e)
                logerrfile = open('err.log', 'a')
                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                logerrfile.write(error)
                logerrfile.write("\n")
                logerrfile.close()
                pass
        else:
                error = str(e)
                logerrfile = open('err.log', 'a')
                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                logerrfile.write(error)
                logerrfile.write("\n")
                logerrfile.close() 
                exit
def CHECKNEWVERSION():
        try:
                urld="http://non-steam.ru/mspyurldown.html"
                reqd = urllib2.Request(urld)
                datad = urllib2.urlopen(reqd)
                datadp = str(datad.read())
                url="http://non-steam.ru/mspyversioncheck.html"
                req = urllib2.Request(url)
                data = urllib2.urlopen(req)
                version = str(cfg.get("OPTIONS","VERSION")) + "\n"
                versioncheck = str(data.read())
                if versioncheck.decode('utf8') != version:
                        print "\n"+"New version available:"
                        print versioncheck
                        print "Download from:" + datadp
                else:
                        print "\n"+"You have last version of masterserver."
                thread.exit()
        except Exception, e:
                print "\n"+"Error: %s" %e
                print "\n"+" Error check for new version."
                if logerr == "1":
                        error = str(e) + " Error check for new version."
                        logerrfile = open('err.log', 'a')
                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                        logerrfile.write(error)
                        logerrfile.write("\n")
                        logerrfile.close()
                thread.exit()
                pass
        thread.exit()

def mysql_logscs(ipcs, portcs):
        timey = datetime.datetime.now().strftime('%Y')
        timem = datetime.datetime.now().strftime('%m')
        timed = datetime.datetime.now().strftime('%d')
        timeh = datetime.datetime.now().strftime('%H')
        timemin = datetime.datetime.now().strftime('%M')
        times = datetime.datetime.now().strftime('%S')
        attempts = 0
        gi = pygeoip.GeoIP('GeoLiteCity.dat')

        while attempts < 1:
                try:
			host,name,user,password,table = cfg.get("LOG","HOST"),cfg.get("LOG","NAME"),cfg.get("LOG","USER"),cfg.get("LOG","PASSWORD"),cfg.get("LOG","TABLE")
                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                        c = db.cursor()
                        tara = ipcs.split(',')[0].strip()
                        try:
                                gir = gi.record_by_name(tara)
                                country_code = gir['country_code']
                                country_name = gir['country_name']
                        except geoip2.errors.AddressNotFoundError:
                                country_code = None
                                country_name = None
                        c.execute("INSERT INTO mslog (timeyear, timemonth, timeday, timehour, timeminute, timesecond, ip, port, type, isocode, fullname) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", (timey, timem, timed, timeh, timemin, times, ipcs, portcs, "cs", country_code, country_name))
                        c.close()
			attempts += 1
                except MySQLdb.Error, e:
                        print "Not successfully connected and update log data. Retry to connect...5 Seconds."
                        print "Error: %s" %e
                        time.sleep(5)
        thread.exit()

def mysql_logscss(ipcs, portcs):
        timey = datetime.datetime.now().strftime('%Y')
        timem = datetime.datetime.now().strftime('%m')
        timed = datetime.datetime.now().strftime('%d')
        timeh = datetime.datetime.now().strftime('%H')
        timemin = datetime.datetime.now().strftime('%M')
        times = datetime.datetime.now().strftime('%S')
        attempts = 0
        while attempts < 1:
                try:
			host,name,user,password,table = cfg.get("LOG","HOST"),cfg.get("LOG","NAME"),cfg.get("LOG","USER"),cfg.get("LOG","PASSWORD"),cfg.get("LOG","TABLE")
                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                        c = db.cursor()
                        c.execute("INSERT INTO mslog (timeyear, timemonth, timeday, timehour, timeminute, timesecond, ip, port, type) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", (timey, timem, timed, timeh, timemin, times, ipcs, portcs, "css"))
                        c.close()
			attempts += 1
                except MySQLdb.Error, e:
                        print "Not successfully connected and update log data. Retry to connect...5 Seconds."
                        print "Error: %s" %e
                        time.sleep(5)
        thread.exit()

def mysql_logshl(ipcs, portcs):
        timey = datetime.datetime.now().strftime('%Y')
        timem = datetime.datetime.now().strftime('%m')
        timed = datetime.datetime.now().strftime('%d')
        timeh = datetime.datetime.now().strftime('%H')
        timemin = datetime.datetime.now().strftime('%M')
        times = datetime.datetime.now().strftime('%S')
        attempts = 0
        while attempts < 1:
                try:
			host,name,user,password,table = cfg.get("LOG","HOST"),cfg.get("LOG","NAME"),cfg.get("LOG","USER"),cfg.get("LOG","PASSWORD"),cfg.get("LOG","TABLE")
                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                        c = db.cursor()
                        c.execute("INSERT INTO mslog (timeyear, timemonth, timeday, timehour, timeminute, timesecond, ip, port, type) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", (timey, timem, timed, timeh, timemin, times, ipcs, portcs, "hl"))
                        c.close()
			attempts += 1
                except MySQLdb.Error, e:
                        print "Not successfully connected and update log data. Retry to connect...5 Seconds."
                        print "Error: %s" %e
                        time.sleep(5)
        thread.exit()

def mysql_logshl2(ipcs, portcs):
        timey = datetime.datetime.now().strftime('%Y')
        timem = datetime.datetime.now().strftime('%m')
        timed = datetime.datetime.now().strftime('%d')
        timeh = datetime.datetime.now().strftime('%H')
        timemin = datetime.datetime.now().strftime('%M')
        times = datetime.datetime.now().strftime('%S')
        attempts = 0
        while attempts < 1:
                try:
			host,name,user,password,table = cfg.get("LOG","HOST"),cfg.get("LOG","NAME"),cfg.get("LOG","USER"),cfg.get("LOG","PASSWORD"),cfg.get("LOG","TABLE")
                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                        c = db.cursor()
                        c.execute("INSERT INTO mslog (timeyear, timemonth, timeday, timehour, timeminute, timesecond, ip, port, type) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", (timey, timem, timed, timeh, timemin, times, ipcs, portcs, "hl 2"))
                        c.close()
			attempts += 1
                except MySQLdb.Error, e:
                        print "Not successfully connected and update log data. Retry to connect...5 Seconds."
                        print "Error: %s" %e
                        time.sleep(5)
        thread.exit()

def mysql_logsq368(ipcs, portcs):
        timey = datetime.datetime.now().strftime('%Y')
        timem = datetime.datetime.now().strftime('%m')
        timed = datetime.datetime.now().strftime('%d')
        timeh = datetime.datetime.now().strftime('%H')
        timemin = datetime.datetime.now().strftime('%M')
        times = datetime.datetime.now().strftime('%S')
        attempts = 0
        while attempts < 1:
                try:
			host,name,user,password,table = cfg.get("LOG","HOST"),cfg.get("LOG","NAME"),cfg.get("LOG","USER"),cfg.get("LOG","PASSWORD"),cfg.get("LOG","TABLE")
                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                        c = db.cursor()
                        c.execute("INSERT INTO mslog (timeyear, timemonth, timeday, timehour, timeminute, timesecond, ip, port, type) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", (timey, timem, timed, timeh, timemin, times, ipcs, portcs, "Q368"))
                        c.close()
			attempts += 1
                except MySQLdb.Error, e:
                        print "Not successfully connected and update log data. Retry to connect...5 Seconds."
                        print "Error: %s" %e
                        time.sleep(5)
        thread.exit()
                        
def file_logshl(iphl, porthl):
        logfile = open('ms.log', 'a')
        logfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
        logfile.write(str(iphl) + "  " + str(porthl) + "  ")
        logfile.write(" hl")
        logfile.write("\n")
        logfile.close()
        thread.exit()

def file_logshl2(iphl, porthl):
        logfile = open('ms.log', 'a')
        logfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
        logfile.write(str(iphl) + "  " + str(porthl) + "  ")
        logfile.write(" hl 2")
        logfile.write("\n")
        logfile.close()
        thread.exit()

def file_logsq368(iphl, porthl):
        logfile = open('ms.log', 'a')
        logfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
        logfile.write(str(iphl) + "  " + str(porthl) + "  ")
        logfile.write(" Q3 68")
        logfile.write("\n")
        logfile.close()
        thread.exit()

def file_logscs(ipcs, portcs):
        logfile = open('ms.log', 'a')
        logfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
        logfile.write(str(ipcs) + "  " + str(portcs) + "  ")
        logfile.write(" cs")
        logfile.write("\n")
        logfile.close()
        thread.exit()

def file_logscss(ipcs, portcs):
        logfile = open('ms.log', 'a')
        logfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
        logfile.write(str(ipcs) + "  " + str(portcs) + "  ")
        logfile.write(" cs:s")
        logfile.write("\n")
        logfile.close()
        thread.exit()

def file_logsspam(ipspam, portspam):
        logfile = open('ms.log', 'a')
        logfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
        logfile.write(str(ipspam) + "  " + str(portspam) + "  ")
        logfile.write(" spam.flood")
        logfile.write("\n")
        logfile.close()
        thread.exit()

       
def q3send(adrcs,portcs):
        if str(mysqldata) == "1":
                q3dsendnewpacket = q3dnewpacket
        for i3cs in q3dsendnewpacket:
                q3s.sendto(i3cs,(adrcs,portcs))
                time.sleep(0.25)
        q3s.close
        thread.exit()

def cssend(adrcs,portcs):
        global csdsendnewpacket
        for i3cs in csdsendnewpacket:
                gss.sendto(i3cs,(adrcs,portcs))
                time.sleep(0.85)
        global MassivIP
        MassivIP = filter(lambda i:i==[adrcs],MassivIP)
        #print MassivIP
        global mode
        if mode.lower() == "file2" or mode.lower() == "lmplus" or mode.lower() == "amxmonplus" or mode.lower() == "cmqplus":
                global file2time
                global csdsendnewpacket2
                if cfg.get("FILE","SECONDLISTRATESEND") == "1" or cfg.get("LMPLUS","SECONDLISTRATESEND") == "1" or cfg.get("AMXMONPLUS","SECONDLISTRATESEND") == "1" or cfg.get("CMQPLUS","SECONDLISTRATESEND") == "1":
                        rate = float(float(cfg.get("OPTIONS","SECONDRATE"))/100)
                        x = random.random()
                        if x <= rate:
                                time.sleep(int(file2time))
                                #print " sec enable and sended good"
                                for i4cs in csdsendnewpacket2:
                                        gss.sendto(i4cs,(adrcs,portcs))
                                        time.sleep(0.85)
                        else:
                                #print " sec enable but not good"
                                thread.exit()
                else:                

                        time.sleep(int(file2time))
                        #print " sec sended without rate"
                        for i4cs in csdsendnewpacket2:
                                gss.sendto(i4cs,(adrcs,portcs))
                                time.sleep(0.85)
        thread.exit()

def csssend(adrcs,portcs):
        global cssdsendnewpacket
        for i3css in cssdsendnewpacket:
                if cfg.get("OPTIONS","DEBUG") == "1":
                        print "Send other packets"
                        print i3css
                s.sendto(i3css,(adrcs,portcs))
                time.sleep(0.85)
        global MassivIP
        MassivIP = filter(lambda i:i==[adrcs],MassivIP)
        global mode
        if mode.lower() == "cmqplus":
                global file2time
                time.sleep(int(file2time))
                print "send 2"
                global cssdsendnewpacket2
                for i4cs in cssdsendnewpacket2:
                        s.sendto(i4cs,(adrcs,portcs))
                        time.sleep(0.85)
        s.close
        thread.exit()

def hl2send(adrcs,portcs):
        global hl2dsendnewpacket
        for i3hl2 in hl2dsendnewpacket:
                s.sendto(i3hl2,(adrcs,portcs))
                time.sleep(0.85)
        global MassivIP
        MassivIP = filter(lambda i:i==[adrcs],MassivIP)
        s.close
        thread.exit()

def hl1send(adrcs,portcs):
        global hl1dsendnewpacket
        for i3hl in hldsendnewpacket:
                gss.sendto(i3hl,(adrcs,portcs))
                time.sleep(0.25)
        global MassivIP
        MassivIP = filter(lambda i:i==[adrcs],MassivIP)
        gss.close
        thread.exit()

def q368send(adrcs,portcs):
        global q368dsendpacket
        q3s.sendto(q368dsenpacket,(adrcs,portcs))
        global MassivIP
        MassivIP = filter(lambda i:i==[adrcs],MassivIP)
        q3s.close
        thread.exit()

def massiviper():
        print "\n"+"Simple DOS protection started..."
        global SigTerm
        while SigTerm == "0":
                time.sleep(3)
                #print MassivIP
                global MassivIP
                MassivIP = [0]
                #print MassivIP
        global SigTermF
        SigTermF = 1
        thread.exit()

def parserecvdatags(addr,data):
        log = cfg.get("LOG","LOG")
        logmode = cfg.get("LOG","MODE")
        logconsole = cfg.get("LOG","CONSOLE")
        if data.find('valve') > 1 and data.find('0.0.0.0:0') > 1:
                mode = cfg.get("OPTIONS","MODE").lower()
                if mode != "monengine":
                        if logconsole == "1":
                                print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S ')) + (str(addr).strip("(").strip(")").replace(",", "").replace("'","", 2)) + " - hl1 client detected."
                        try:
                                thread.start_new_thread(hl1send, (addr))
                        except Exception, e:
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e) + " HL 1 data send"
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                        thread.exit()
                                        pass
                        if log == "1":
                                if logmode == "MYSQL":
                                        try:
                                                thread.start_new_thread(mysql_logshl, (addr))
                                        except Exception, e:
                                                print "Error: %s" %e
                                                if logerr == "1":
                                                        error = str(e)
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                        pass                                                        
                                else:
                                        try:
                                                thread.start_new_thread(file_logshl, (addr))
                                        except Exception, e:
                                                print "Error: %s" %e
                                                if logerr == "1":
                                                        error = str(e)
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                pass
                                        
        elif data.find('hl2') > 1 and data.find('0.0.0.0:0') > 1:
                mode = cfg.get("OPTIONS","MODE").lower()
                if mode != "monengine":
                        if logconsole == "1":
                                print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S ')) + (str(addr).strip("(").strip(")").replace(",", "").replace("'","", 2)) + " - hl2 client detected."
                        try:
                                thread.start_new_thread(hl2send, (addr))
                        except Exception, e:
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e) + " HL 2 data send"
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                        thread.exit()
                                        pass
                        if log == "1":
                                if logmode == "MYSQL":
                                        try:
                                                thread.start_new_thread(mysql_logshl2, (addr))
                                        except Exception, e:
                                                print "Error: %s" %e
                                                if logerr == "1":
                                                        error = str(e)
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                        pass                                                        
                                else:
                                        try:
                                                thread.start_new_thread(file_logshl2, (addr))
                                        except Exception, e:
                                                print "Error: %s" %e
                                                if logerr == "1":
                                                        error = str(e)
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                pass
        elif data.find('cstrike') > 1 and data.find('0.0.0.0:0') > 1:
                if logconsole == "1":
                        print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S ')) + (str(addr).strip("(").strip(")").replace(",", "").replace("'","", 2)) + " - cs client detected."
                try:
                        thread.start_new_thread(cssend, (addr))
                except Exception, e:
                        print "Error: %s" %e
                        if logerr == "1":
                                error = str(e) + " CS data send"
                                logerrfile = open('err.log', 'a')
                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                logerrfile.write(error)
                                logerrfile.write("\n")
                                logerrfile.close()
                        thread.exit()
                        pass
                if log == "1":
                        if logmode == "MYSQL":
                                try:
                                        thread.start_new_thread(mysql_logscs, (addr))
                                except Exception, e:
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e) + " CS client log to mysql"
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        thread.exit()
                                        pass
                        else:
                                try:
                                        thread.start_new_thread(file_logscs, (addr))
                                except Exception, e:
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e) + " CS client log to file"
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        thread.exit()
                                        pass
        else:
                thread.exit()
                pass
        
def parserecvdatas(addr,data):
        log = cfg.get("LOG","LOG")
        logmode = cfg.get("LOG","MODE")
        logconsole = cfg.get("LOG","CONSOLE")
        if data.find('hl2') > 1 and data.find('0.0.0.0:0') > 1:
                mode = cfg.get("OPTIONS","MODE").lower()
                if mode != "monengine":
                        if logconsole == "1":
                                print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S ')) + (str(addr).strip("(").strip(")").replace(",", "").replace("'","", 2)) + " - hl2 client detected."
                        try:
                                thread.start_new_thread(hl2send, (addr))
                        except Exception, e:
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e) + " HL 2 data send"
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                        thread.exit()
                                        pass
                        if log == "1":
                                if logmode == "MYSQL":
                                        try:
                                                thread.start_new_thread(mysql_logshl2, (addr))
                                        except Exception, e:
                                                print "Error: %s" %e
                                                if logerr == "1":
                                                        error = str(e)
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                        pass                                                        
                                else:
                                        try:
                                                thread.start_new_thread(file_logshl2, (addr))
                                        except Exception, e:
                                                print "Error: %s" %e
                                                if logerr == "1":
                                                        error = str(e)
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                pass
        elif data.find('cstrike') > 1 and data.find('0.0.0.0:0') > 1:
                if logconsole == "1":
                        print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S ')) + (str(addr).strip("(").strip(")").replace(",", "").replace("'","", 2)) + " - cs:s client detected."
                try:
                        thread.start_new_thread(csssend, (addr))
                except Exception, e:
                        print "Error: %s" %e
                        if logerr == "1":
                                error = str(e) + " CS:S data send"
                                logerrfile = open('err.log', 'a')
                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                logerrfile.write(error)
                                logerrfile.write("\n")
                                logerrfile.close()
                        thread.exit()
                        pass
                if log == "1":
                        if logmode == "MYSQL":
                                try:
                                        thread.start_new_thread(mysql_logscss, (addr))
                                except Exception, e:
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e) + " CS:S client log to mysql"
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        thread.exit()
                                        pass
                        else:
                                try:
                                        thread.start_new_thread(file_logscss, (addr))
                                except Exception, e:
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e) + " CS:S client log to file"
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        thread.exit()
                                        pass
        else:
                thread.exit()
                pass


def parserecvdataq3(addr,data):
        log = cfg.get("LOG","LOG")
        logmode = cfg.get("LOG","MODE")
        logconsole = cfg.get("LOG","CONSOLE")
        if data.find('getservers 68') > 1:
                mode = cfg.get("OPTIONS","MODE").lower()
                if mode != "monengine":
                        if logconsole == "1":
                                print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S ')) + (str(addr).strip("(").strip(")").replace(",", "").replace("'","", 2)) + " - Q3 68 protocol client detected."
                        try:
                                thread.start_new_thread(q368send, (addr))
                        except Exception, e:
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e) + " Q3 68 data send"
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                        thread.exit()
                                        pass
                        if log == "1":
                                if logmode == "MYSQL":
                                        try:
                                                thread.start_new_thread(mysql_logsq368, (addr))
                                        except Exception, e:
                                                print "Error: %s" %e
                                                if logerr == "1":
                                                        error = str(e)
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                        pass                                                        
                                else:
                                        try:
                                                thread.start_new_thread(file_logsq368, (addr))
                                        except Exception, e:
                                                print "Error: %s" %e
                                                if logerr == "1":
                                                        error = str(e)
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                pass
def serve_forevergs():
        host,port = cfg.get("OPTIONS","HOST"),cfg.getint("OPTIONS","PORTGS")
        global gss
        global MassivIP
        gss = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        gss.bind((host,port))
        global skiperrnogs54
        skiperrnogs54 = "0"
        global SigTerm
        while SigTerm == "0":
                #print SigTerm
                try:
                        data,addr = gss.recvfrom(1024)
                except Exception, e:
                    print str(e) + "Connection reset by peer" + "\n"
                    gss.close
                    if logerr == "1":
                            error = str(e) + "Connection reset by peer "
                            logerrfile = open('err.log', 'a')
                            logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                            logerrfile.write(error)
                            logerrfile.write("\n")
                            logerrfile.close()
                    skiperrnogs54 = "1"
                    pass
                if skiperrnogs54 == "1":
                        skiperrnogs54 = "0"
                else:
                        if addr[0] in MassivIP:
                                pass
                        else:
                                #print MassivIP
                                MassivIP = MassivIP + [addr[0]]
                                #print data
                                #print MassivIP
                                #
                                try:
                                        thread.start_new_thread(parserecvdatags, (addr,data))
                                except Exception, e:
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e) + "Thread parserecvdatags"
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        pass
	global SigTermGS
	SigTermGS = 1
        thread.exit()
def serve_foreverq3():
	host,port = cfg.get("OPTIONS","HOST"),cfg.getint("OPTIONS","PORTQ3")
        global q3s
	q3s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
	q3s.bind((host,port))
	global skiperrnogs54
	skiperrnogs54 = "0"
        global SigTerm
        while SigTerm == "0":
                try:
                        data,addr = q3s.recvfrom(1024)
                except Exception, e:
                    print str(e) + "Connection reset by peer" + "\n"
                    q3s.close
                    if logerr == "1":
                            error = str(e) + "Connection reset by peer "
                            logerrfile = open('err.log', 'a')
                            logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                            logerrfile.write(error)
                            logerrfile.write("\n")
                            logerrfile.close()
                    skiperrnogs54 = "1"
                    pass
                if skiperrnogs54 == "1":
                        skiperrnogs54 = "0"
                else:
                        try:
                                thread.start_new_thread(parserecvdataq3, (addr,data))
                        except Exception, e:
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e) + "Thread parserecvdataq3"
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                pass
	global SigTermQ3
	SigTermQ3 = 1
        thread.exit()
def serve_forevers():
	host,port = cfg.get("OPTIONS","HOST"),cfg.getint("OPTIONS","PORTS")
        global s
	s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
	s.bind((host,port))
	global skiperrno54
	skiperrno54 = "0"
        global SigTerm
        while SigTerm == "0":
                try:
                        data,addr = s.recvfrom(1024)
                except Exception, e:
                    print str(e) + "Connection reset by peer \n"
                    s.close
                    if logerr == "1":
                            error = str(e) + "Connection reset by peer "
                            logerrfile = open('err.log', 'a')
                            logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                            logerrfile.write(error)
                            logerrfile.write("\n")
                            logerrfile.close()
                    skiperrno54 = "1"
                    pass
                if skiperrno54 == "1":
                        skiperrno54 = "0"
                else:
                        try:
                                print data
                                thread.start_new_thread(parserecvdatas, (addr,data))
                        except Exception, e:
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e) + "Thread parserecvdatas"
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                pass
	global SigTermS
	SigTermS = 1
        thread.exit()	
def load_servers():
        global mysqldata
        global logerr
        global mode
        logerr = cfg.get("LOG","LOGERR")
	mode = cfg.get("OPTIONS","MODE").lower()
	if mode == "file" or mode == "file2":
		filecs = cfg.get("FILE","FILECS")
		if cfg.get("OPTIONS","MODE").lower() == "file2":
                        filecs2 = cfg.get("FILE","FILECS2")
                        global file2time
                        file2time = cfg.get("FILE","FILECS2TIME")
		filehl = cfg.get("FILE","FILEHL")
		filecss = cfg.get("FILE","FILECSS")
		filehl2 = cfg.get("FILE","FILEHL2")
		fileq368 = cfg.get("FILE","FILEQ368")
                random = cfg.get("FILE","RANDOM")
		if random == "1":
                        import random
                        srvcsn = [ics.strip("\n") for ics in open(filecs)]
                        srvhln = [ihl.strip("\n") for ihl in open(filehl)]
                        srvcssn = [icss.strip("\n") for icss in open(filecss)]
                        srvhl2n = [ihl2.strip("\n") for ihl2 in open(filehl2)]
                        srvq368n = [iq368.strip("\n") for iq368 in open(fileq368)]
#cs
                        sizecsn = len(srvcsn)
                        srvcs = []
                        while sizecsn:
                                sizecsn = sizecsn - 1
                                indexcsn = random.randrange(0, sizecsn + 1, 1)
                                elemcsn = srvcsn[indexcsn]
                                srvcs.append([elemcsn]) 
                                srvcsn[indexcsn] = srvcsn[sizecsn]
#hl
                        sizehln = len(srvhln)
                        srvhl = []
                        while sizehln:
                                sizehln = sizehln - 1
                                indexhln = random.randrange(0, sizehln + 1, 1)
                                elemhln = srvhln[indexhln]
                                srvhl.append([elemhln]) 
                                srvhln[indexhln] = srvhln[sizehln]
#css
                        sizecssn = len(srvcssn)
                        srvcss = []
                        while sizecssn:
                                sizecssn = sizecssn - 1
                                indexcssn = random.randrange(0, sizecssn + 1, 1)
                                elemcssn = srvcssn[indexcssn]
                                srvcss.append([elemcssn]) 
                                srvcssn[indexcssn] = srvcssn[sizecssn]
#hl2
                        sizehl2n = len(srvhl2n)
                        srvhl2 = []
                        while sizehl2n:
                                sizehl2n = sizehl2n - 1
                                indexhl2n = random.randrange(0, sizehl2n + 1, 1)
                                elemhl2n = srvhl2n[indexhl2n]
                                srvhl2.append([elemhl2n]) 
                                srvhl2n[indexhl2n] = srvhl2n[sizehl2n]
#q368
                        sizeq368n = len(srvq368n)
                        srvq368 = []
                        while sizeq368n:
                                sizeq368n = sizeq368n - 1
                                indexq368n = random.randrange(0, sizeq368n + 1, 1)
                                elemq368n = srvq368n[indexq368n]
                                srvq368.append([elemq368n]) 
                                srvq368n[indexq368n] = srvq368n[sizeq368n]
                        print "Randomize the server list is ok =)"
                else:
                        srvcs = [ics.strip("\n") for ics in open(filecs)]
                        if cfg.get("OPTIONS","MODE").lower() == "file2":
                                srvcs2 = [ics2.strip("\n") for ics2 in open(filecs2)]
                        srvhl = [ihl.strip("\n") for ihl in open(filehl)]
                        srvcss = [icss.strip("\n") for icss in open(filecss)]
                        srvhl2 = [ihl2.strip("\n") for ihl2 in open(filehl2)]
                        srvq368 = [iq368.strip("\n") for iq368 in open(fileq368)]
		print "Files this list of servers opened ok!"
		mysqldata =1
	elif mode == "mysql":
                attempts = 0
                mysqldata = 0
                while attempts < 1:
                        print "Trying connect to mysql and take list of servers from custom MYSQL Table..."
                        try:
                                random = cfg.get("MYSQL","RANDOM")
                                if random == "1":
                                        host,name,user,password,table = cfg.get("MYSQL","HOST"),cfg.get("MYSQL","NAME"),cfg.get("MYSQL","USER"),cfg.get("MYSQL","PASSWORD"),cfg.get("MYSQL","TABLE")
                                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                        c = db.cursor()
                                        c.execute("SELECT ipport FROM %s WHERE type = 'cs' ORDER BY RAND()"%table)
                                        srvcs = [ics[0] for ics in c.fetchall()]
                                        c.execute("SELECT ipport FROM %s WHERE type = 'hl' ORDER BY RAND()"%table)
                                        srvhl = [ihl[0] for ihl in c.fetchall()]
                                        c.execute("SELECT ipport FROM %s WHERE type = 'hl2' ORDER BY RAND()"%table)
                                        srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                        c.execute("SELECT ipport FROM %s WHERE type = 'css' ORDER BY RAND()"%table)
                                        srvcss = [icss[0] for icss in c.fetchall()]
                                        c.execute("SELECT ipport FROM %s WHERE type = 'q368' ORDER BY RAND()"%table)
                                        srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                        c.close()
                                        attempts += 1
                                        mysqldata = 1
                                        print "Get RANDOM list of servers from mysql... OK"
                                else:
                                        host,name,user,password,table = cfg.get("MYSQL","HOST"),cfg.get("MYSQL","NAME"),cfg.get("MYSQL","USER"),cfg.get("MYSQL","PASSWORD"),cfg.get("MYSQL","TABLE")
                                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                        c = db.cursor()
                                        c.execute("SELECT ipport FROM %s WHERE type = 'cs'"%table)
                                        srvcs = [ics[0] for ics in c.fetchall()]
                                        c.execute("SELECT ipport FROM %s WHERE type = 'hl'"%table)
                                        srvhl = [ihl[0] for ihl in c.fetchall()]
                                        c.execute("SELECT ipport FROM %s WHERE type = 'hl2'"%table)
                                        srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                        c.execute("SELECT ipport FROM %s WHERE type = 'css'"%table)
                                        srvcss = [icss[0] for icss in c.fetchall()]
                                        c.execute("SELECT ipport FROM %s WHERE type = 'q368'"%table)
                                        srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                        c.close()
                                        attempts += 1
                                        mysqldata = 1
                                        print "Get list of servers from mysql... OK"
                        except MySQLdb.Error, e:
                                print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e)
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                time.sleep(5)
                                
                                
	elif mode == "lightmon":
		vip = cfg.get("LIGHTMON","VIP")
		if vip == "1":
                        attempts = 0
                        mysqldata = 0
                        while attempts < 1:
                                print "Trying connect to mysql and take list of servers from LIGHTMON..."
                                try:
                                        random = cfg.get("LIGHTMON","RANDOM")
                                        if random == "1":
                                                host,name,user,password,table = cfg.get("LIGHTMON","HOST"),cfg.get("LIGHTMON","NAME"),cfg.get("LIGHTMON","USER"),cfg.get("LIGHTMON","PASSWORD"),cfg.get("LIGHTMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvcs = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                print "Get Random list of VIP servers from Lightmon ... OK"
                                        else:
                                                host,name,user,password,table = cfg.get("LIGHTMON","HOST"),cfg.get("LIGHTMON","NAME"),cfg.get("LIGHTMON","USER"),cfg.get("LIGHTMON","PASSWORD"),cfg.get("LIGHTMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvcs = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                print "Get list of VIP servers from Lightmon... OK"
                                        c.close()
                                        attempts += 1
                                        mysqldata = 1
                                except MySQLdb.Error, e:
                                        print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e)
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        time.sleep(5)
#vip 2
		if vip == "2":
                        attempts = 0
                        mysqldata = 0
                        while attempts < 1:
                                print "Trying connect to mysql and take list of servers from LIGHTMON..."
                                try:
                                        random = cfg.get("LIGHTMON","RANDOM")
                                        if random == "1":
                                                host,name,user,password,table = cfg.get("LIGHTMON","HOST"),cfg.get("LIGHTMON","NAME"),cfg.get("LIGHTMON","USER"),cfg.get("LIGHTMON","PASSWORD"),cfg.get("LIGHTMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND month = '1' ORDER BY RAND()"%table)
                                                srvcstop = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (golos = '9999' AND (line_col != NULL OR line_col != '')) ORDER BY RAND()"%table)
                                                srvcsvipc = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (golos = '9999' AND (line_col = '' OR line_col = NULL)) ORDER BY RAND()"%table)
                                                srvcsvip = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (line_col != '' OR line_col != NULL) ORDER BY RAND()"%table)
                                                srvcsc = [ics[0] for ics in c.fetchall()]
                                                srvcs = srvcs + srvcstop + srvcsvipc + srvcsvip + srvcsc
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                print "Get Random list of VIP servers from Lightmon ... OK"
                                        else:
                                                host,name,user,password,table = cfg.get("LIGHTMON","HOST"),cfg.get("LIGHTMON","NAME"),cfg.get("LIGHTMON","USER"),cfg.get("LIGHTMON","PASSWORD"),cfg.get("LIGHTMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND month = '1'"%table)
                                                srvcstop = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (golos = '9999' AND (line_col != NULL OR line_col != ''))"%table)
                                                srvcsvipc = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (golos = '9999' AND (line_col = '' OR line_col = NULL))"%table)
                                                srvcsvip = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (line_col != '' OR line_col != NULL)"%table)
                                                srvcsc = [ics[0] for ics in c.fetchall()]
                                                srvcs = srvcstop + srvcsvipc + srvcsvip + srvcsc
                                                print srvcs
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                print "Get list of VIP servers from Lightmon... OK"
                                        c.close()
                                        attempts += 1
                                        mysqldata = 1
                                except MySQLdb.Error, e:
                                        print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e)
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        time.sleep(5)
#vip 2 end
		elif vip == "0":
                        attempts = 0
                        mysqldata = 0
                        while attempts < 1:
                                print "Trying connect to mysql and take list of ALL servers from LIGHTMON..."
                                try:
                                        random = cfg.get("LIGHTMON","RANDOM")
                                        if random == "2":
                                                host,name,user,password,table = cfg.get("LIGHTMON","HOST"),cfg.get("LIGHTMON","NAME"),cfg.get("LIGHTMON","USER"),cfg.get("LIGHTMON","PASSWORD"),cfg.get("LIGHTMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvcs = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                #----
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'cs' ORDER BY RAND()"%table)
                                                allsrvcs = [aics[0] for aics in c.fetchall()]
                                                srvcs = srvcs + allsrvcs
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css' ORDER BY RAND()"%table)
                                                allsrvcss = [aicss[0] for aicss in c.fetchall()]
                                                srvcss = srvcss + allsrvcss
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1' ORDER BY RAND()"%table)
                                                allsrvhl = [aihl[0] for aihl in c.fetchall()]
                                                srvhl = srvhl + allsrvhl
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm' ORDER BY RAND()"%table)
                                                allsrvhl2 = [aihl2[0] for aihl2 in c.fetchall()]
                                                srvhl2 = srvhl2 + allsrvhl2
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3' ORDER BY RAND()"%table)
                                                allsrvq368 = [aiq368[0] for aiq368 in c.fetchall()]
                                                srvq368 = srvq368 + allsrvq368
                                                c.close()
                                                attempts += 1
                                                mysqldata = 1
                                                print "Get list of servers from LIGHTMON... OK"
                                        elif random == "3":
                                                host,name,user,password,table = cfg.get("LIGHTMON","HOST"),cfg.get("LIGHTMON","NAME"),cfg.get("LIGHTMON","USER"),cfg.get("LIGHTMON","PASSWORD"),cfg.get("LIGHTMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvcs = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                #----
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'cs'"%table)
                                                allsrvcs = [aics[0] for aics in c.fetchall()]
                                                srvcs = srvcs + allsrvcs
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css'"%table)
                                                allsrvcss = [aicss[0] for aicss in c.fetchall()]
                                                srvcss = srvcss + allsrvcss
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1'"%table)
                                                allsrvhl = [aihl[0] for aihl in c.fetchall()]
                                                srvhl = srvhl + allsrvhl
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm'"%table)
                                                allsrvhl2 = [aihl2[0] for aihl2 in c.fetchall()]
                                                srvhl2 = srvhl2 + allsrvhl2
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3'"%table)
                                                allsrvq368 = [aiq368[0] for aiq368 in c.fetchall()]
                                                srvq368 = srvq368 + allsrvq368
                                                c.close()
                                                attempts += 1
                                                mysqldata = 1
                                                print "Get list of servers from LIGHTMON... OK"
                                        elif random == "4":
                                                host,name,user,password,table = cfg.get("LIGHTMON","HOST"),cfg.get("LIGHTMON","NAME"),cfg.get("LIGHTMON","USER"),cfg.get("LIGHTMON","PASSWORD"),cfg.get("LIGHTMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvcs = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                #----
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'cs' ORDER BY RAND()"%table)
                                                allsrvcs = [aics[0] for aics in c.fetchall()]
                                                srvcs = srvcs + allsrvcs
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css' ORDER BY RAND()"%table)
                                                allsrvcss = [aicss[0] for aicss in c.fetchall()]
                                                srvcss = srvcss + allsrvcss
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1' ORDER BY RAND()"%table)
                                                allsrvhl = [aihl[0] for aihl in c.fetchall()]
                                                srvhl = srvhl + allsrvhl
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm' ORDER BY RAND()"%table)
                                                allsrvhl2 = [aihl2[0] for aihl2 in c.fetchall()]
                                                srvhl2 = srvhl2 + allsrvhl2
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3' ORDER BY RAND()"%table)
                                                allsrvq368 = [aiq368[0] for aiq368 in c.fetchall()]
                                                srvq368 = srvq368 + allsrvq368
                                                c.close()
                                                attempts += 1
                                                mysqldata = 1
                                                print "Get list of servers from LIGHTMON... OK"
                                        else:
                                                host,name,user,password,table = cfg.get("LIGHTMON","HOST"),cfg.get("LIGHTMON","NAME"),cfg.get("LIGHTMON","USER"),cfg.get("LIGHTMON","PASSWORD"),cfg.get("LIGHTMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvcs = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                #----
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'cs'"%table)
                                                allsrvcs = [aics[0] for aics in c.fetchall()]
                                                srvcs = srvcs + allsrvcs
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css'"%table)
                                                allsrvcss = [aicss[0] for aicss in c.fetchall()]
                                                srvcss = srvcss + allsrvcss
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1'"%table)
                                                allsrvhl = [aihl[0] for aihl in c.fetchall()]
                                                srvhl = srvhl + allsrvhl
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm'"%table)
                                                allsrvhl2 = [aihl2[0] for aihl2 in c.fetchall()]
                                                srvhl2 = srvhl2 + allsrvhl2
                                                c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3'"%table)
                                                allsrvq368 = [aiq368[0] for aiq368 in c.fetchall()]
                                                srvq368 = srvq368 + allsrvq368
                                                c.close()
                                                attempts += 1
                                                mysqldata = 1
                                                print "Get list of servers from LIGHTMON... OK"
                                except MySQLdb.Error, e:
                                        print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e)
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        time.sleep(5)
#lm plus start
	elif mode == "lmplus":
                attempts = 0
                mysqldata = 0
                while attempts < 1:
                        print "Trying connect to mysql and take list of servers from LIGHTMON +..."
                        try:
                                random = cfg.get("LMPLUS","RANDOM")
                                if random == "1":
                                        host,name,user,password,table = cfg.get("LMPLUS","HOST"),cfg.get("LMPLUS","NAME"),cfg.get("LMPLUS","USER"),cfg.get("LMPLUS","PASSWORD"),cfg.get("LMPLUS","TABLE")
                                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                        c = db.cursor()
                                        c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND month = '1' ORDER BY RAND()"%table)
                                        srvcstop = [ics[0] for ics in c.fetchall()]
                                        c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (golos = '9999' AND (line_col != NULL OR line_col != '')) ORDER BY RAND()"%table)
                                        srvcsvipc = [ics[0] for ics in c.fetchall()]
                                        c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (golos = '9999' AND (line_col = '' OR line_col = NULL)) ORDER BY RAND()"%table)
                                        srvcsvip = [ics[0] for ics in c.fetchall()]
                                        c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (line_col != '' OR line_col != NULL) ORDER BY RAND()"%table)
                                        srvcsc = [ics[0] for ics in c.fetchall()]
                                        srvcs = srvcstop + srvcsvipc + srvcsvip + srvcsc
                                        c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1' ORDER BY RAND()"%table)
                                        srvhl = [ihl[0] for ihl in c.fetchall()]
                                        c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                        srvcss = [icss[0] for icss in c.fetchall()]
                                        c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                        srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                        c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1') ORDER BY RAND()"%table)
                                        srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                        print "Get Random list of VIP servers from Lightmon + ... OK"
                                else:
                                        host,name,user,password,table = cfg.get("LMPLUS","HOST"),cfg.get("LMPLUS","NAME"),cfg.get("LMPLUS","USER"),cfg.get("LMPLUS","PASSWORD"),cfg.get("LMPLUS","TABLE")
                                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                        c = db.cursor()
                                        c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND month = '1'"%table)
                                        srvcstop = [ics[0] for ics in c.fetchall()]
                                        c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (golos = '9999' AND (line_col != NULL OR line_col != ''))"%table)
                                        srvcsvipc = [ics[0] for ics in c.fetchall()]
                                        c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (golos = '9999' AND (line_col = '' OR line_col = NULL))"%table)
                                        srvcsvip = [ics[0] for ics in c.fetchall()]
                                        c.execute("SELECT CONCAT(ip,':',q_port) AS TEXT FROM %s WHERE type = 'cs' AND (line_col != '' OR line_col != NULL)"%table)
                                        srvcsc = [ics[0] for ics in c.fetchall()]
                                        srvcs = srvcstop + srvcsvipc + srvcsvip + srvcsc
                                        c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl1'"%table)
                                        srvhl = [ihl[0] for ihl in c.fetchall()]
                                        c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'css' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                        srvcss = [icss[0] for icss in c.fetchall()]
                                        c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'hl2dm' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                        srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                        c.execute("SELECT CONCAT(ip,':',q_port) as text FROM %s WHERE type = 'q3' AND (line =  '1' OR golos =  '9999' OR line_col != NULL OR month = '1')"%table)
                                        srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                        print "Get list of VIP servers from Lightmon + ... OK"
                                if cfg.get("LMPLUS","LMPMODE").lower() == "url":
                                        try:
                                                urlcs = cfg.get("LMPLUS","LMPURL").lower()
                                                reqcs = urllib2.Request(urlcs)
                                                datacs = urllib2.urlopen(reqcs)
                                                srvcsreadcs = str(datacs.read())
                                                srvcs2 = srvcsreadcs.split("\n")
                                                file2time = cfg.get("LMPLUS","LMPTIME")
                                        except Exception, e:
                                                print "Error: %s" %e
                                                print " Error load url."
                                                if logerr == "1":
                                                        error = str(e) + " Error load url."
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                pass
                                elif cfg.get("LMPLUS","LMPMODE").lower() == "txt":
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "LMPTXT start - OK!"
                                        filecs2 = cfg.get("LMPLUS","LMPTXT")
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "LMPTXT conf 1 - OK!"
                                        file2time = cfg.get("LMPLUS","LMPTIME")
                                        srvcs2 = [ics2.strip("\n") for ics2 in open(filecs2)]
                                elif cfg.get("LMPLUS","LMPMODE").lower() == "sql":
                                        host,name,user,password,table,cmqcs = cfg.get("LMPLUS","HOST"),cfg.get("LMPLUS","NAME"),cfg.get("LMPLUS","USER"),cfg.get("LMPLUS","PASSWORD"),cfg.get("LMPLUS","TABLE"),cfg.get("LMPLUS","LMPSQL")
                                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                        c.execute(cmqcs)
                                        srvcs2 = [ics[0] for ics in c.fetchall()]
                                        file2time = cfg.get("LMPLUS","LMPTIME")
                                c.close()
                                attempts += 1
                                mysqldata = 1
                        except MySQLdb.Error, e:
                                print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e)
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                time.sleep(5)
#lm plus end
	elif mode == "amxmon":
		vip = cfg.get("AMXMON","VIP")
		if vip == "1":
                        attempts = 0
                        mysqldata = 0
                        while attempts < 1:
                                print "Trying connect to mysql and take list of VIP servers AMXMON..."
                                try:
                                        random = cfg.get("AMXMON","RANDOM")
                                        if random == "1":
                                                host,name,user,password,table = cfg.get("AMXMON","HOST"),cfg.get("AMXMON","NAME"),cfg.get("AMXMON","USER"),cfg.get("AMXMON","PASSWORD"),cfg.get("AMXMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND (server_vip =  '1' OR server_top =  '1') AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                                srvcs = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'source' AND (server_vip =  '1' OR server_top =  '1') AND server_status = 1 AND server_off = '0'"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'halflife' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1 ORDER BY RAND()"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'hl2dm' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1 ORDER BY RAND()"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'q3' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1 ORDER BY RAND()"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                c.close()
                                                attempts += 1
                                                mysqldata = 1
                                        else:
                                                host,name,user,password,table = cfg.get("AMXMON","HOST"),cfg.get("AMXMON","NAME"),cfg.get("AMXMON","USER"),cfg.get("AMXMON","PASSWORD"),cfg.get("AMXMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND (server_vip =  '1' OR server_top =  '1') AND server_status = 1 AND server_off = '0'"%table)
                                                srvcs = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'source' AND (server_vip =  '1' OR server_top =  '1') AND server_status = 1 AND server_off = '0'"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'halflife' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'hl2dm' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'q3' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                c.close()
                                                attempts += 1
                                                mysqldata = 1
                                except MySQLdb.Error, e:
                                        print "Not successfully connected and taked 0 server Retry to connect...5 Seconds."
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e)
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        time.sleep(5)
		elif vip == "0":
                        attempts = 0
                        mysqldata = 0
                        while attempts < 1:
                                print "Trying connect to mysql and take list of servers ALL from AMXMON..."
                                try:
                                        random = cfg.get("AMXMON","RANDOM")
                                        if random == "2":
                                                host,name,user,password,table = cfg.get("AMXMON","HOST"),cfg.get("AMXMON","NAME"),cfg.get("AMXMON","USER"),cfg.get("AMXMON","PASSWORD"),cfg.get("AMXMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND (server_vip =  '1' OR server_top =  '1') AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                                srvcs = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'source' AND (server_vip =  '1' OR server_top =  '1') AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'halflife' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1 ORDER BY RAND()"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'hl2dm' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1 ORDER BY RAND()"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'q3' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1 ORDER BY RAND()"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                #----
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                                allsrvcs = [aics[0] for aics in c.fetchall()]
                                                srvcs = srvcs + allsrvcs
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'source' AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                                allsrvcss = [aicss[0] for aicss in c.fetchall()]
                                                srvcss = srvcss + allsrvcss
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'halflife' OR server_game = 'hl' AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                                allsrvhl = [aihl[0] for aihl in c.fetchall()]
                                                srvhl = srvhl + allsrvhl
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'hl2dm' OR server_game = 'hl' AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                                allsrvhl2 = [aihl2[0] for aihl2 in c.fetchall()]
                                                srvhl2 = srvhl2 + allsrvhl2
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'q3' OR server_game = 'hl' AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                                allsrvq368 = [aiq368[0] for aiq368 in c.fetchall()]
                                                srvq368 = srvq368 + allsrvq368
                                                c.close()
                                                attempts += 1
                                                mysqldata = 1
                                        elif random == "3":
                                                host,name,user,password,table = cfg.get("AMXMON","HOST"),cfg.get("AMXMON","NAME"),cfg.get("AMXMON","USER"),cfg.get("AMXMON","PASSWORD"),cfg.get("AMXMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND (server_vip =  '1' OR server_top =  '1') AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                                srvcs = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'source' AND (server_vip =  '1' OR server_top =  '1') AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'halflife' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1 ORDER BY RAND()"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'hl2dm' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1 ORDER BY RAND()"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'q3' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1 ORDER BY RAND()"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                #----
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvcs = [aics[0] for aics in c.fetchall()]
                                                srvcs = srvcs + allsrvcs
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'source' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvcss = [aicss[0] for aicss in c.fetchall()]
                                                srvcss = srvcss + allsrvcss
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'halflife' OR server_game = 'hl' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvhl = [aihl[0] for aihl in c.fetchall()]
                                                srvhl = srvhl + allsrvhl
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'hl2dm' OR server_game = 'hl' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvhl2 = [aihl2[0] for aihl2 in c.fetchall()]
                                                srvhl2 = srvhl2 + allsrvhl2
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'q3' OR server_game = 'hl' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvq368 = [aiq368[0] for aiq368 in c.fetchall()]
                                                srvq368 = srvq368 + allsrvq368
                                                c.close()
                                                attempts += 1
                                                mysqldata = 1
                                        elif random == "4":
                                                host,name,user,password,table = cfg.get("AMXMON","HOST"),cfg.get("AMXMON","NAME"),cfg.get("AMXMON","USER"),cfg.get("AMXMON","PASSWORD"),cfg.get("AMXMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND (server_vip =  '1' OR server_top =  '1') AND server_status = 1 AND server_off = '0'"%table)
                                                srvcs = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'source' AND (server_vip =  '1' OR server_top =  '1') AND server_status = 1 AND server_off = '0'"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'halflife' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'hl2dm' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'q3' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                #----
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvcs = [aics[0] for aics in c.fetchall()]
                                                srvcs = srvcs + allsrvcs
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'source' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvcss = [aicss[0] for aicss in c.fetchall()]
                                                srvcss = srvcss + allsrvcss
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'halflife' OR server_game = 'hl' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvhl = [aihl[0] for aihl in c.fetchall()]
                                                srvhl = srvhl + allsrvhl
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'hl2dm' OR server_game = 'hl' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvhl2 = [aihl2[0] for aihl2 in c.fetchall()]
                                                srvhl2 = srvhl2 + allsrvhl2
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'q3' OR server_game = 'hl' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvq368 = [aiq368[0] for aiq368 in c.fetchall()]
                                                srvq368 = srvq368 + allsrvq368
                                                c.close()
                                                attempts += 1
                                                mysqldata = 1
                                        else:
                                                host,name,user,password,table = cfg.get("AMXMON","HOST"),cfg.get("AMXMON","NAME"),cfg.get("AMXMON","USER"),cfg.get("AMXMON","PASSWORD"),cfg.get("AMXMON","TABLE")
                                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                                c = db.cursor()
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND (server_vip =  '1' OR server_top =  '1') AND server_status = 1 AND server_off = '0'"%table)
                                                srvcs = [ics[0] for ics in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'source' AND (server_vip =  '1' OR server_top =  '1') AND server_status = 1 AND server_off = '0'"%table)
                                                srvcss = [icss[0] for icss in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'halflife' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1"%table)
                                                srvhl = [ihl[0] for ihl in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'hl2dm' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1"%table)
                                                srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'q3' OR server_game = 'hl' AND (server_vip =  '1' OR server_top =  '1' AND server_off = '0') AND server_status = 1"%table)
                                                srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                                #----
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                                allsrvcs = [aics[0] for aics in c.fetchall()]
                                                srvcs = srvcs + allsrvcs
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'source' AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                                allsrvcss = [aicss[0] for aicss in c.fetchall()]
                                                srvcss = srvcss + allsrvcss
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'halflife' OR server_game = 'hl' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvhl = [aihl[0] for aihl in c.fetchall()]
                                                srvhl = srvhl + allsrvhl
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'hl2dm' OR server_game = 'hl' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvhl2 = [aihl2[0] for aihl2 in c.fetchall()]
                                                srvhl2 = srvhl2 + allsrvhl2
                                                c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'q3' OR server_game = 'hl' AND server_status = 1 AND server_off = '0'"%table)
                                                allsrvq368 = [aiq368[0] for aiq368 in c.fetchall()]
                                                srvq368 = srvq368 + allsrvq368
                                                c.close()
                                                attempts += 1
                                                mysqldata = 1
                                except MySQLdb.Error, e:
                                        print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e)
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        time.sleep(5)
#amxmon+
	elif mode == "amxmonplus":
                attempts = 0
                mysqldata = 0
                while attempts < 1:
                        print "Trying connect to mysql and take list of servers ALL from AMXMONPLUS..."
                        try:
                                random = cfg.get("AMXMONPLUS","RANDOM")
                                if random == "3":
                                        host,name,user,password,table = cfg.get("AMXMONPLUS","HOST"),cfg.get("AMXMONPLUS","NAME"),cfg.get("AMXMONPLUS","USER"),cfg.get("AMXMONPLUS","PASSWORD"),cfg.get("AMXMONPLUS","TABLE")
                                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                        c = db.cursor()
                                        c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND server_top =  '1' AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                        srvcst = [ics[0] for ics in c.fetchall()]
                                        c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND server_vip =  '1' AND server_status = 1 AND server_off = '0' ORDER BY RAND()"%table)
                                        srvcsv = [ics[0] for ics in c.fetchall()]
                                        srvcs = srvcst + srvcsv
                                        c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'source' AND server_status = 1 AND server_off = '0'"%table)
                                        srvcss = [icss[0] for icss in c.fetchall()]
                                        c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'halflife' OR server_game = 'hl' AND server_off = '0' AND server_status = 1"%table)
                                        srvhl = [ihl[0] for ihl in c.fetchall()]
                                        c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'hl2dm' OR server_game = 'hl' AND server_off = '0' AND server_status = 1"%table)
                                        srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                        c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'q3' OR server_game = 'hl' AND server_off = '0' AND server_status = 1"%table)
                                        srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                else:
                                        host,name,user,password,table = cfg.get("AMXMONPLUS","HOST"),cfg.get("AMXMONPLUS","NAME"),cfg.get("AMXMONPLUS","USER"),cfg.get("AMXMONPLUS","PASSWORD"),cfg.get("AMXMONPLUS","TABLE")
                                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                        c = db.cursor()
                                        c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND server_top =  '1' AND server_status = 1 AND server_off = '0'"%table)
                                        srvcst = [ics[0] for ics in c.fetchall()]
                                        c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'cs' AND server_vip =  '1' AND server_status = 1 AND server_off = '0'"%table)
                                        srvcsv = [ics[0] for ics in c.fetchall()]
                                        srvcs = srvcst + srvcsv
                                        c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'source' AND server_status = 1 AND server_off = '0'"%table)
                                        srvcss = [icss[0] for icss in c.fetchall()]
                                        c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'halflife' OR server_game = 'hl' AND server_off = '0' AND server_status = 1"%table)
                                        srvhl = [ihl[0] for ihl in c.fetchall()]
                                        c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'hl2dm' OR server_game = 'hl' AND server_off = '0' AND server_status = 1"%table)
                                        srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                        c.execute("SELECT CONCAT(server_ip,':',server_port) AS TEXT FROM %s WHERE server_game = 'q3' OR server_game = 'hl' AND server_off = '0' AND server_status = 1"%table)
                                        srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                if cfg.get("AMXMONPLUS","AMXPMODE").lower() == "url":
                                        try:
                                                urlcs = cfg.get("AMXMONPLUS","AMXPURL").lower()
                                                reqcs = urllib2.Request(urlcs)
                                                datacs = urllib2.urlopen(reqcs)
                                                srvcsreadcs = str(datacs.read())
                                                srvcs2 = srvcsreadcs.split("\n")
                                                file2time = cfg.get("AMXMONPLUS","AMXPTIME")
                                        except Exception, e:
                                                print "Error: %s" %e
                                                print " Error load url."
                                                if logerr == "1":
                                                        error = str(e) + " Error load url."
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                pass
                                elif cfg.get("AMXMONPLUS","AMXPMODE").lower() == "txt":
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "AMXMONPLUSTXT start - OK!"
                                        filecs2 = cfg.get("AMXMONPLUS","AMXPTXT")
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "AMXMONPLUSTXT conf 1 - OK!"
                                        file2time = cfg.get("AMXMONPLUS","AMXPTIME")
                                        srvcs2 = [ics2.strip("\n") for ics2 in open(filecs2)]
                                elif cfg.get("AMXMONPLUS","AMXPMODE").lower() == "sql":
                                        host,name,user,password,table,cmqcs = cfg.get("AMXMONPLUS","HOST"),cfg.get("AMXMONPLUS","NAME"),cfg.get("AMXMONPLUS","USER"),cfg.get("AMXMONPLUS","PASSWORD"),cfg.get("AMXMONPLUS","TABLE"),cfg.get("AMXMONPLUS","AMXPSQL")
                                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                        c.execute(cmqcs)
                                        srvcs2 = [ics[0] for ics in c.fetchall()]
                                        file2time = cfg.get("AMXMONPLUS","AMXPTIME")
                                c.close()
                                attempts += 1
                                mysqldata = 1
                        except MySQLdb.Error, e:
                                print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e)
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                time.sleep(5)
                           
#amxmon+ end
        elif mode  == "monengine":
                vip = cfg.get("MONENGINE","VIP")
                if vip == "1":
                        attempts = 0
                        mysqldata = 0
                        while attempts < 1:
                                print "Trying connect to mysql and take VIP list of servers from MONENGINE..."
                                try:
                                        host,name,user,password,table = cfg.get("MONENGINE","HOST"),cfg.get("MONENGINE","NAME"),cfg.get("MONENGINE","USER"),cfg.get("MONENGINE","PASSWORD"),cfg.get("MONENGINE","TABLE")
                                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                        c = db.cursor()
                                        c.execute("SELECT server_ip AS TEXT FROM %s WHERE server_game = 'cs16' AND (server_vip =  '1' OR server_top <> '0') AND server_status = 1 AND server_off = 0"%table)
                                        srvcs = [ics[0] for ics in c.fetchall()]
                                        c.close()
                                        attempts += 1
                                        mysqldata = 1
                                except MySQLdb.Error, e:
                                        print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e)
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        time.sleep(5)
                elif vip == "0":
                        attempts = 0
                        mysqldata = 0
                        while attempts < 1:
                                print "Trying connect to mysql and take list of servers from MONENGINE..."
                                try:
                                        host,name,user,password,table = cfg.get("MONENGINE","HOST"),cfg.get("MONENGINE","NAME"),cfg.get("MONENGINE","USER"),cfg.get("MONENGINE","PASSWORD"),cfg.get("MONENGINE","TABLE")
                                        db = MySQLdb.connect(host=socket.gethostbyname(host),user=user,passwd=password,db=name)
                                        c = db.cursor()
                                        c.execute("SELECT `server_ip` AS TEXT FROM %s WHERE server_game = 'cs16' AND server_status = '1' AND server_off = '0'"%table)
                                        srvcs = [ics[0] for ics in c.fetchall()]
                                        c.close()
                                        attempts += 1
                                        mysqldata = 1
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "Take list of server for MONENGINE - OK!"
                                except MySQLdb.Error, e:
                                        print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e)
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        time.sleep(5)
        elif mode == "boostbymirror":
                attempts = 0
                mysqldata = 0
                while attempts < 1:
                        print "Trying connect to mysql and take list of servers from BOOSTBYMIRROR..."
                        try:
                                host,name,user,password,table = cfg.get("BOOSTBYMIRROR","HOST"),cfg.get("BOOSTBYMIRROR","NAME"),cfg.get("BOOSTBYMIRROR","USER"),cfg.get("BOOSTBYMIRROR","PASSWORD"),cfg.get("BOOSTBYMIRROR","TABLE")
                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                c = db.cursor()
                                c.execute("(SELECT DISTINCT address FROM "+table+" WHERE game = 'cs16' AND type = 1 AND date_end >  unix_timestamp(now()) ORDER BY date_end DESC) UNION (SELECT DISTINCT address FROM "+table+" WHERE game = 'cs16' AND type = 2 ORDER BY date_create DESC)")
                                srvcs = [ics[0] for ics in c.fetchall()]
                                c.close()
                                attempts += 1
                                mysqldata = 1
                        except MySQLdb.Error, e:
                                print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e)
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                time.sleep(5)
        elif mode == "cmq":
                attempts = 0
                mysqldata = 0
                while attempts < 1:
                        print "Trying connect to mysql and take list of servers from Custom Mysql query..."
                        try:
                                host,name,user,password,cmqcs,cmqhl,cmqcss,cmqhl2,cmqq3 = cfg.get("CMQ","HOST"),cfg.get("CMQ","NAME"),cfg.get("CMQ","USER"),cfg.get("CMQ","PASSWORD"),cfg.get("CMQ","CMQCS"),cfg.get("CMQ","CMQHL1"),cfg.get("CMQ","CMQCSS"),cfg.get("CMQ","CMQHL2"),cfg.get("CMQ","CMQQ3")
                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                c = db.cursor()
                                if cmqcs == "NOQUERY":
                                        srvcs = []
                                else:
                                        c.execute(cmqcs)
                                        srvcs = [ics[0] for ics in c.fetchall()]
                                if cmqhl == "NOQUERY":
                                        srvhl = []
                                else:
                                        c.execute(cmqhl)
                                        srvhl = [ihl[0] for ihl in c.fetchall()]
                                if cmqcss == "NOQUERY":
                                        srvcss = []
                                else:
                                        c.execute(cmqcss)
                                        srvcss = [icss[0] for icss in c.fetchall()]
                                if cmqhl2 == "NOQUERY":
                                        srvhl2 = []
                                else:
                                        c.execute(cmqhl2)
                                        srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                if cmqq3 == "NOQUERY":
                                        srvq368 = []
                                else:
                                        c.execute(cmqhl)
                                        srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                c.close()
                                attempts += 1
                                mysqldata = 1
                        except MySQLdb.Error, e:
                                print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e)
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                time.sleep(5)
#cmqplus
        elif mode == "cmqplus":
                attempts = 0
                mysqldata = 0
                while attempts < 1:
                        print "Trying connect to mysql and take list of servers from Custom Mysql query..."
                        try:
                                host,name,user,password,cmqcs,cmqhl,cmqcss,cmqhl2,cmqq3 = cfg.get("CMQPLUS","HOST"),cfg.get("CMQPLUS","NAME"),cfg.get("CMQPLUS","USER"),cfg.get("CMQPLUS","PASSWORD"),cfg.get("CMQPLUS","CMQCS"),cfg.get("CMQPLUS","CMQHL1"),cfg.get("CMQPLUS","CMQCSS"),cfg.get("CMQPLUS","CMQHL2"),cfg.get("CMQPLUS","CMQQ3")
                                db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                c = db.cursor()
                                if cmqcs == "NOQUERY":
                                        srvcs = []
                                else:
                                        c.execute(cmqcs)
                                        srvcs = [ics[0] for ics in c.fetchall()]
                                if cmqhl == "NOQUERY":
                                        srvhl = []
                                else:
                                        c.execute(cmqhl)
                                        srvhl = [ihl[0] for ihl in c.fetchall()]
                                if cmqcss == "NOQUERY":
                                        srvcss = []
                                else:
                                        c.execute(cmqcss)
                                        srvcss = [icss[0] for icss in c.fetchall()]
                                if cmqhl2 == "NOQUERY":
                                        srvhl2 = []
                                else:
                                        c.execute(cmqhl2)
                                        srvhl2 = [ihl2[0] for ihl2 in c.fetchall()]
                                if cmqq3 == "NOQUERY":
                                        srvq368 = []
                                else:
                                        c.execute(cmqhl)
                                        srvq368 = [iq368[0] for iq368 in c.fetchall()]
                                if cfg.get("CMQPLUS","CMQPCSMODE").lower() == "url":
                                        
                                        try:
                                                urlcs = cfg.get("CMQPLUS","CMQPCSURL").lower()
                                                reqcs = urllib2.Request(urlcs)
                                                datacs = urllib2.urlopen(reqcs)
                                                srvcsreadcs = str(datacs.read())
                                                srvcs2 = srvcsreadcs.split("\n")
                                                file2time = cfg.get("CMQPLUS","CMQPCSTIME")
                                        except Exception, e:
                                                print "Error: %s" %e
                                                print " Error load url."
                                                if logerr == "1":
                                                        error = str(e) + " Error load url."
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                pass
                                if cfg.get("CMQPLUS","CMQPCSMODE").lower() == "txt":
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "CMQPLUSTXT start - OK!"
                                        filecs2 = cfg.get("CMQPLUS","CMQPCSTXT")
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "CMQPLUSTXT conf 1 - OK!"
                                        file2time = cfg.get("CMQPLUS","CMQPCSTIME")
                                        srvcs2 = [ics2.strip("\n") for ics2 in open(filecs2)]
                                if cfg.get("CMQPLUS","CMQPCSMODE").lower() == "sql":
                                        host,name,user,password,table,cmqcs = cfg.get("CMQPLUS","HOST"),cfg.get("CMQPLUS","NAME"),cfg.get("CMQPLUS","USER"),cfg.get("CMQPLUS","PASSWORD"),cfg.get("CMQPLUS","TABLE"),cfg.get("CMQPLUS","CMQCSSQL")
                                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                        c.execute(cmqcs)
                                        srvcs2 = [ics[0] for ics in c.fetchall()]
                                        file2time = cfg.get("CMQPLUS","CMQPCSTIME")
                                if cfg.get("CMQPLUS","CMQPCSSMODE").lower() == "url":
                                        
                                        try:
                                                urlcs = cfg.get("CMQPLUS","CMQPCSSURL").lower()
                                                reqcs = urllib2.Request(urlcs)
                                                datacs = urllib2.urlopen(reqcs)
                                                srvcsreadcs = str(datacs.read())
                                                srvcss2 = srvcsreadcs.split("\n")
                                                file2time = cfg.get("CMQPLUS","CMQPCSSTIME")
                                        except Exception, e:
                                                print "Error: %s" %e
                                                print " Error load url."
                                                if logerr == "1":
                                                        error = str(e) + " Error load url."
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                pass
                                elif cfg.get("CMQPLUS","CMQPCSSMODE").lower() == "txt":
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "CMQPLUSTXT start - OK!"
                                        filecs2 = cfg.get("CMQPLUS","CMQPCSSTXT")
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "CMQPLUSTXT conf 1 - OK!"
                                        file2time = cfg.get("CMQPLUS","CMQPCSSTIME")
                                        srvcss2 = [ics2.strip("\n") for ics2 in open(filecs2)]
                                elif cfg.get("CMQPLUS","CMQCPSSMODE").lower() == "sql":
                                        host,name,user,password,table,cmqcs = cfg.get("CMQPLUS","HOST"),cfg.get("CMQPLUS","NAME"),cfg.get("CMQPLUS","USER"),cfg.get("CMQPLUS","PASSWORD"),cfg.get("CMQPLUS","TABLE"),cfg.get("CMQPLUS","CMQCSSSQL")
                                        db = MySQLdb.connect(host=host,user=user,passwd=password,db=name)
                                        c.execute(cmqcs)
                                        srvcss2 = [ics[0] for ics in c.fetchall()]
                                        file2time = cfg.get("CMQPLUS","CMQPCSSTIME")
                                c.close()
                                attempts += 1
                                mysqldata = 1
                        except MySQLdb.Error, e:
                                print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e)
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                time.sleep(5)
#cmqplus
        elif mode == "url":
                attempts = 0
                mysqldata = 0
                while attempts < 1:
                        print "Trying connect to web server and take list of servers from urlfile..."
                        try:
                                urlcs = cfg.get("URL","URLFILECS").lower()
                                if urlcs == "nourl":
                                        srvcs = []
                                else:
                                        reqcs = urllib2.Request(urlcs)
                                        datacs = urllib2.urlopen(reqcs)
                                        srvcsreadcs = str(datacs.read())
                                        srvcs = srvcsreadcs.split("\n")
                                urlhl = cfg.get("URL","URLFILEHL1").lower()
                                if urlhl == "nourl":
                                        srvhl = []
                                else:
                                        reqhl = urllib2.Request(urlhl)
                                        datahl = urllib2.urlopen(reqhl)
                                        srvcsreadhl = str(datahl.read())
                                        srvhl = srvcsreadhl.split("\n")
                                urlhl2 = cfg.get("URL","URLFILEHL2").lower()
                                if urlhl2 == "nourl":
                                        srvhl2 = []
                                else:
                                        reqhl2 = urllib2.Request(urlhl2)
                                        datahl2 = urllib2.urlopen(reqhl2)
                                        srvcsreadhl2 = str(datahl2.read())
                                        srvhl2 = srvcsreadhl2.split("\n")
                                urlcss = cfg.get("URL","URLFILECSS").lower()
                                if urlcss == "nourl":
                                        srvcss = []
                                else:
                                        reqcss = urllib2.Request(urlcss)
                                        datacss = urllib2.urlopen(reqcss)
                                        srvcsreadcss = str(datacss.read())
                                        srvcss = srvcsreadcss.split("\n")
                                urlq368 = cfg.get("URL","URLFILEQ3").lower()
                                if urlq368 == "nourl":
                                        srvq368 = []
                                else:
                                        reqq368 = urllib2.Request(urlq368)
                                        dataq368 = urllib2.urlopen(reqq368)
                                        srvcsreadq368 = str(dataq368.read())
                                        srvq368 = srvcsreadq368.split("\n")
                                attempts += 1
                                mysqldata = 1
                        except Exception, e:
                                print "Not successfully connected and taked 0 servers. Retry to connect...5 Seconds."
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e)
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                time.sleep(5)
        global csd
        global hld
        global csdnewpacket
        global cssdnewpacket
        global hldnewpacket
        global hl2dnewpacket
        global q368d
        global csdsendnewpacket
        global cssdsendnewpacket
        global q368dsendpacket
        global hl2dsendnewpacket
        global hldsendnewpacket
#update 0.4.5 a2
        global csd2
        global cs_d2
        global csdnewpacket2
        global csdsendnewpacket2
        cs_d2 = [0xFF,0xFF,0xFF,0xFF,0x66,0x0A]
        csdnewpacket2 = []

#update 0.4.8 a1
        global cssd2
        global css_d2
        global cssdnewpacket2
        global cssdsendnewpacket2
        css_d2 = [0xFF,0xFF,0xFF,0xFF,0x66,0x0A]
        cssdnewpacket2 = []
#
        cs_d = [0xFF,0xFF,0xFF,0xFF,0x66,0x0A]
        hl_d = [0xFF,0xFF,0xFF,0xFF,0x66,0x0A]
        css_d = [0xFF,0xFF,0xFF,0xFF,0x66,0x0A]
        hl2_d = [0xFF,0xFF,0xFF,0xFF,0x66,0x0A]
        q368_d = [0xFF,0xFF,0xFF,0xFF,0x67,0x65,0x74,0x73,0x65,0x72,0x76,0x65,0x72,0x73,0x52,0x65,0x73,0x70,0x6F,0x6E,0x73,0x65]
        csdnewpacket = []
        cssdnewpacket = []
        hldnewpacket = []
        hl2dnewpacket = []
        q368newpacket = []
	
        noping = cfg.get("OPTIONS","NOPING")
        if cfg.get("OPTIONS","MODE").lower() == "monengine" or cfg.get("OPTIONS","MODE").lower() == "boostbymirror":
                cscalc = 0
                print "Start load CS 1.6 Servers..."
                for ics in srvcs:
                        if cfg.get("OPTIONS","DEBUG") == "1":
                                print "After for ics in srvcs load - OK!"
                        try:
                                ip,port = ics.split(":")
                        except Exception, e:
                                print "Error: %s" %e
                                print " Error in adress " + ics
                                if logerr == "1":
                                        error = str(e) + " Error at:" + ics
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                continue
                        try:
                                ip = [int(j) for j in socket.gethostbyname(ip).split(".")]
                        except socket.gaierror, e:
                                print "Dns error? :", ip
                                print "Error: %s" %e
                                if logerr == "1":
                                        error = str(e) + " Error at:" + ip
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                continue
                        if cfg.get("OPTIONS","DEBUG") == "1":
                                print "IP load - OK!"
                        try:
                                port = int(port)
                        except Exception, e:
                                print "Error: %s" %e
                                print " Error in adress " + ics
                                if logerr == "1":
                                        error = str(e) + " Error at:" + ics
                                        logerrfile = open('err.log', 'a')
                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                        logerrfile.write(error)
                                        logerrfile.write("\n")
                                        logerrfile.close()
                                continue
                        if cfg.get("OPTIONS","DEBUG") == "1":
                                print "Port load - OK!"
                        port = [port>>8&0xFF,port&0xFF]
                        map(cs_d.append,ip)
                        map(cs_d.append,port)
                        cscalc = cscalc + 1
                noping = cfg.get("OPTIONS","NOPING")
                if noping == "1":
                        print "No ping mode is ON"
                else:
                        print "No ping mode is OFF or no"
                        cs_d2 += [0x00,0x00,0x00,0x00,0x00,0x00]
                csd = "".join([chr(i2cs) for i2cs in cs_d])
                csdnewpacket = csdnewpacket + [csd]
                print "CS 1.6 load - ok!" 
	else:
                randomf = cfg.get("FILE","RANDOM")
                if cfg.get("OPTIONS","PORTGS").lower() == "off":
                        pass
                else:
                        print "Start load CS 1.6 Servers..."
                        cscalc = 0
                        for ics in srvcs:
                                if (cscalc == 200) or (cscalc == 400) or (cscalc == 600) or (cscalc == 800) or (cscalc == 1000) or (cscalc == 1200) or (cscalc == 1400) or (cscalc == 1600) or (cscalc == 1800) or (cscalc == 2000) or (cscalc == 2200) or (cscalc == 2400) or (cscalc == 2600) or (cscalc == 2800) or (cscalc == 3000) or (cscalc == 3200) or (cscalc == 3400) or (cscalc == 3600) or (cscalc == 3800) or (cscalc == 4000) or (cscalc == 4200) or (cscalc == 4400) or (cscalc == 4600) or (cscalc == 4800) or (cscalc == 5000) or (cscalc == 5200) or (cscalc == 5400) or (cscalc == 5600) or (cscalc == 5800) or (cscalc == 6000) or (cscalc == 6200) or (cscalc == 6400) or (cscalc == 6600) or (cscalc == 6800) or (cscalc == 7000) or (cscalc == 7200) or (cscalc == 7400) or (cscalc == 7800) or (cscalc == 8000) or (cscalc == 8200) or (cscalc == 8400) or (cscalc == 8600) or (cscalc == 8800) or (cscalc == 9000) or (cscalc == 9200) or (cscalc == 9400) or (cscalc == 9600) or (cscalc == 9800) or (cscalc == 10000):
                                        csd = "".join([chr(i2cs) for i2cs in cs_d])
                                        csdnewpacket = csdnewpacket + [csd]
                                        cs_d = [0xFF,0xFF,0xFF,0xFF,0x66,0x0A]
                                try:
                                        #print "ics2:5"+str(ics)[2:-2]
                                        if randomf == "1" and mode == "FILE":
                                                ip,port = str(ics)[2:-2].split(":")
                                        else:
                                                ip,port = ics.split(":")
                                except Exception, e:
                                        print "Error: %s" %e
                                        print " Error in adress " + ics
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + ics
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue
                                try:
                                        ip = [int(j) for j in socket.gethostbyname(ip).split(".")]
                                except socket.gaierror, e:
                                        print "Dns error? :", ip
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + ip
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue 
                                if cfg.get("OPTIONS","DEBUG") == "1":
                                        print "IP load - OK!"
                                try:
                                        port = int(port)
                                except Exception, e:
                                        print "Error: %s" %e
                                        print " Error in adress " + ics
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + ics
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue
                                if cfg.get("OPTIONS","DEBUG") == "1":
                                        print "Port load - OK!"
                                port = [port>>8&0xFF,port&0xFF]
                                map(cs_d.append,ip)
                                map(cs_d.append,port)
                                cscalc = cscalc + 1
                        noping = cfg.get("OPTIONS","NOPING")
                        if noping == "1" or cfg.get("OPTIONS","MODE").lower() == "file2" or cfg.get("OPTIONS","MODE").lower() == "lmplus" or cfg.get("OPTIONS","MODE").lower() == "amxmonplus":
                                print "No ping mode is ON (or MODE FILE2 or LM PLUS or AMXMON PLUS or CMQ+)"
                        else:
                                print "No ping mode is OFF or no FILE2 mode or no LM PLUS mode or no AMXMON PLUS or no CMQ+"
                                cs_d += [0x00,0x00,0x00,0x00,0x00,0x00]
                        csd = "".join([chr(i2cs) for i2cs in cs_d])
                        csdnewpacket = csdnewpacket + [csd]
                        print "CS 1.6 load - ok!"
                        #print csd

#update 0.4.5a1 //update 2 //up to 0.4.6 // up to 0.4.8
                        if cfg.get("OPTIONS","MODE").lower() == "file2" or cfg.get("OPTIONS","MODE").lower() == "lmplus" or cfg.get("OPTIONS","MODE").lower() == "amxmonplus" or cfg.get("OPTIONS","MODE").lower() == "cmqplus":
                                print "Start load CS2 1.6 Servers..."
                                cscalc2 = 0
                                for ics in srvcs2:
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "SRVCS2 passed - OK!"
                                        if (cscalc2 == 200) or (cscalc2 == 400) or (cscalc2 == 600) or (cscalc2 == 800) or (cscalc2 == 1000) or (cscalc2 == 1200) or (cscalc2 == 1400) or (cscalc2 == 1600) or (cscalc2 == 1800) or (cscalc2 == 2000) or (cscalc2 == 2200) or (cscalc2 == 2400) or (cscalc2 == 2600) or (cscalc2 == 2800) or (cscalc2 == 3000) or (cscalc2 == 3200) or (cscalc2 == 3400) or (cscalc2 == 3600) or (cscalc2 == 3800) or (cscalc2 == 4000) or (cscalc2 == 4200) or (cscalc2 == 4400) or (cscalc2 == 4600) or (cscalc2 == 4800) or (cscalc2 == 5000):
                                                csd2 = "".join([chr(i2cs) for i2cs in cs_d2])
                                                csdnewpacket2 = csdnewpacket2 + [csd2]
                                                cs_d2 = [0xFF,0xFF,0xFF,0xFF,0x66,0x0A]
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "CALC passed - OK!"

                                        try:
                                                #print "ics2:5"+str(ics)[2:-2]
                                                if randomf == "1" and mode == "FILE":
                                                        ip,port = str(ics)[2:-2].split(":")
                                                else:
                                                        ip,port = ics.split(":")
                                        except Exception, e:
                                                print "Error: %s" %e
                                                print " Error in adress " + ics
                                                if logerr == "1":
                                                        error = str(e) + " Error at:" + ics
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                continue
                                        try:
                                                ip = [int(j) for j in socket.gethostbyname(ip).split(".")]
                                        except socket.gaierror, e:
                                                print "Dns error? :", ip
                                                print "Error: %s" %e
                                                if logerr == "1":
                                                        error = str(e) + " Error at:" + ip
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                continue 
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "IP load - OK!"
                                        try:
                                                port = int(port)
                                        except Exception, e:
                                                print "Error: %s" %e
                                                print " Error in adress " + ics
                                                if logerr == "1":
                                                        error = str(e) + " Error at:" + ics
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                continue
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "Port load - OK!"
                                        port = [port>>8&0xFF,port&0xFF]
                                        map(cs_d2.append,ip)
                                        map(cs_d2.append,port)
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "Port & ip add to array - OK!"
                                        cscalc2 = cscalc2 + 1
                                noping = cfg.get("OPTIONS","NOPING")
                                if noping == "1":
                                        print "No ping mode is ON"
                                else:
                                        print "No ping mode is OFF"
                                        cs_d2 += [0x00,0x00,0x00,0x00,0x00,0x00]
                                csd2 = "".join([chr(i2cs) for i2cs in cs_d2])
                                if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "UPDATE csd2 - OK!"
                                csdnewpacket2 = csdnewpacket2 + [csd2]
                                print "CS2 1.6 load - ok!"
                                #print csd2
#
                csscalc = 0

                if cfg.get("OPTIONS","PORTS").lower() == "off":
                        pass
                else:
                        print "Start load CS Source Servers..."
                        for icss in srvcss:
                                if (csscalc == 200) or (csscalc == 400) or (csscalc == 600) or (csscalc == 800) or (csscalc == 1000) or (csscalc == 1200) or (csscalc == 1400) or (csscalc == 1600) or (csscalc == 1800) or (csscalc == 2000) or (csscalc == 2200) or (csscalc == 2400) or (csscalc == 2600) or (csscalc == 2800) or (csscalc == 3000) or (csscalc == 3200) or (csscalc == 3400) or (csscalc == 3600) or (csscalc == 3800) or (csscalc == 4000) or (csscalc == 4200) or (csscalc == 4400) or (csscalc == 4600) or (csscalc == 4800) or (csscalc == 5000):
                                        cssd = "".join([chr(i2css) for i2css in css_d])
                                        cssdnewpacket = csdnewpacket + [cssd]
                                        css_d = [0xFF,0xFF,0xFF,0xFF,0x66,0x0A]
                                try:
                                        if randomf == "1" and mode == "FILE":
                                                ip,port = str(icss)[2:-2].split(":")
                                        else:
                                                ip,port = icss.split(":")
                                except Exception, e:
                                        print "Error: %s" %e
                                        print " Error in adress " + icss
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + icss
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue
                                try:
                                        ip = [int(j) for j in socket.gethostbyname(ip).split(".")]
                                except socket.gaierror, e:
                                        print "Dns error? :", ip
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + ip
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue 
                                try:
                                        port = int(port)
                                except Exception, e:
                                        print "Error: %s" %e
                                        print " Error in adress " + ics
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + ics
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue
                                if cfg.get("OPTIONS","DEBUG") == "1":
                                        print "Port load - OK!"
                                port = [port>>8&0xFF,port&0xFF]
                                map(css_d.append,ip)
                                map(css_d.append,port)
                                csscalc = csscalc + 1
                        if noping == "1" or cfg.get("OPTIONS","MODE").lower() == "amxmonplus":
                                print "No ping mode is ON (or MODE CMQ+)"
                        else:
                                print "No ping mode is OFF (or no MODE CMQ+)"
                                css_d2 += [0x00,0x00,0x00,0x00,0x00,0x00]
                        cssd = "".join([chr(i2css) for i2css in css_d])
                        cssdnewpacket = cssdnewpacket + [cssd]
                        print "CS Source load - ok!"


#CSS2
                        if cfg.get("OPTIONS","MODE").lower() == "cmqplus":
                                print "Start load CS Source 2 Servers..."
                                css2calc = 0
                                for icss in srvcss2:
                                        if (css2calc == 200) or (css2calc == 400) or (css2calc == 600) or (css2calc == 800) or (css2calc == 1000) or (css2calc == 1200) or (css2calc == 1400) or (css2calc == 1600) or (css2calc == 1800) or (css2calc == 2000) or (css2calc == 2200) or (css2calc == 2400) or (css2calc == 2600) or (css2calc == 2800) or (css2calc == 3000) or (css2calc == 3200) or (css2calc == 3400) or (css2calc == 3600) or (css2calc == 3800) or (css2calc == 4000) or (css2calc == 4200) or (css2calc == 4400) or (css2calc == 4600) or (css2calc == 4800) or (css2calc == 5000):
                                                cssd2 = "".join([chr(i2css) for i2css in css_d2])
                                                cssdnewpacket2 = csdnewpacket2 + [cssd2]
                                                css_d2 = [0xFF,0xFF,0xFF,0xFF,0x66,0x0A]
                                        try:
                                                if randomf == "1" and mode == "FILE":
                                                        ip,port = str(icss)[2:-2].split(":")
                                                else:
                                                        ip,port = icss.split(":")
                                        except Exception, e:
                                                print "Error: %s" %e
                                                print " Error in adress " + icss
                                                if logerr == "1":
                                                        error = str(e) + " Error at:" + icss
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                continue
                                        try:
                                                ip = [int(j) for j in socket.gethostbyname(ip).split(".")]
                                        except socket.gaierror, e:
                                                print "Dns error? :", ip
                                                print "Error: %s" %e
                                                if logerr == "1":
                                                        error = str(e) + " Error at:" + ip
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                continue 
                                        try:
                                                port = int(port)
                                        except Exception, e:
                                                print "Error: %s" %e
                                                print " Error in adress " + ics
                                                if logerr == "1":
                                                        error = str(e) + " Error at:" + ics
                                                        logerrfile = open('err.log', 'a')
                                                        logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                        logerrfile.write(error)
                                                        logerrfile.write("\n")
                                                        logerrfile.close()
                                                continue
                                        if cfg.get("OPTIONS","DEBUG") == "1":
                                                print "Port load - OK!"
                                        port = [port>>8&0xFF,port&0xFF]
                                        map(css_d2.append,ip)
                                        map(css_d2.append,port)
                                        csscalc = csscalc + 1
                                if noping == "1":
                                        print "No ping mode is ON"
                                else:
                                        print "No ping mode is OFF"
                                        cs_d2 += [0x00,0x00,0x00,0x00,0x00,0x00]
                                cssd2 = "".join([chr(i2css) for i2css in css_d2])
                                cssdnewpacket2 = cssdnewpacket2 + [cssd2]
                                print "CS Source 2 load - ok!"                        
#CSS2 end
                if cfg.get("OPTIONS","PORTGS").lower() == "off":
                        pass
                else:
                        hlcalc = 0
                        print "Start load HL 1 servers..."
                        for ihl in srvhl:
                                if (hlcalc == 200) or (hlcalc == 400) or (hlcalc == 600) or (hlcalc == 800) or (hlcalc == 1000) or (hlcalc == 1200) or (hlcalc == 1400) or (hlcalc == 1600) or (hlcalc == 1800) or (hlcalc == 2000) or (hlcalc == 2200) or (hlcalc == 2400) or (hlcalc == 2600) or (hlcalc == 2800) or (hlcalc == 3000) or (hlcalc == 3200) or (hlcalc == 3400) or (hlcalc == 3600) or (hlcalc == 3800) or (hlcalc == 4000) or (hlcalc == 4200) or (hlcalc == 4400) or (hlcalc == 4600) or (hlcalc == 4800) or (hlcalc == 5000):
                                        hld = "".join([chr(i2hl) for i2hl in hl_d])
                                        hldnewpacket = hldnewpacket + [hld]
                                        hl_d = [0xFF,0xFF,0xFF,0xFF,0x66,0x0A]
                                try:
                                        if randomf == "1"and mode == "FILE":
                                                ip,port = str(ihl)[2:-2].split(":")
                                        else:
                                                ip,port = ihl.split(":")
                                except Exception, e:
                                        print "Error: %s" %e
                                        print " Error in adress " + ihl
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + ihl
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue
                                try:
                                        ip = [int(j) for j in socket.gethostbyname(ip).split(".")]
                                except socket.gaierror, e:
                                        print "Dns error? :", ip
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + ip
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue 
                                port = int(port)
                                port = [port>>8&0xFF,port&0xFF]
                                map(hl_d.append,ip)
                                map(hl_d.append,port)
                                hlcalc = hlcalc + 1
                        hl_d += [0x00,0x00,0x00,0x00,0x00,0x00]
                        hld = "".join([chr(ihl) for ihl in hl_d])
                        hldnewpacket = hldnewpacket + [hld]
                        print "HL 1 load - ok!"
                if cfg.get("OPTIONS","PORTS").lower() == "off":
                        pass
                else:
                        hl2calc = 0
                        print "Start load HL 2 servers..."
                        for ihl2 in srvhl2:
                                if (hl2calc == 200) or (hl2calc == 400) or (hl2calc == 600) or (hl2calc == 800) or (hl2calc == 1000) or (hl2calc == 1200) or (hl2calc == 1400) or (hl2calc == 1600) or (hl2calc == 1800) or (hl2calc == 2000) or (hl2calc == 2200) or (hl2calc == 2400) or (hl2calc == 2600) or (hl2calc == 2800) or (hl2calc == 3000) or (hl2calc == 3200) or (hl2calc == 3400) or (hl2calc == 3600) or (hl2calc == 3800) or (hl2calc == 4000) or (hl2calc == 4200) or (hl2calc == 4400) or (hl2calc == 4600) or (hl2calc == 4800) or (hl2calc == 5000):
                                        hl2d = "".join([chr(i2hl2) for i2hl2 in hl2_d])
                                        hl2dnewpacket = hl2dnewpacket + [hl2d]
                                        hl2_d = [0xFF,0xFF,0xFF,0xFF,0x66,0x0A]

                                try:
                                        if randomf == "1" and mode == "FILE":
                                                ip,port = str(ihl2)[2:-2].split(":")
                                        else:
                                                ip,port = ihl2.split(":")
                                except Exception, e:
                                        print "Error: %s" %e
                                        print " Error in adress " + ihl2
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + ihl2
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue
                                try:
                                        ip = [int(j) for j in socket.gethostbyname(ip).split(".")]
                                except socket.gaierror, e:
                                        print "Dns error? :", ip
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + ip
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue 
                                try:
                                        port = int(port)
                                except Exception, e:
                                        print "Error: %s" %e
                                        print " Error in adress " + ics
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + ics
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue
                                if cfg.get("OPTIONS","DEBUG") == "1":
                                        print "Port load - OK!"
                                port = [port>>8&0xFF,port&0xFF]
                                map(hl2_d.append,ip)
                                map(hl2_d.append,port)
                                hl2calc = hl2calc + 1
                        hl2_d += [0x00,0x00,0x00,0x00,0x00,0x00]
                        hl2d = "".join([chr(ihl2) for ihl2 in hl2_d])
                        hl2dnewpacket = hl2dnewpacket + [hl2d]
                        print "HL 2 load - ok!"
                if cfg.get("OPTIONS","PORTQ3").lower() == "off":
                        pass
                else:
                        q368calc = 0
                        stick = [0x5C]
                        print "Start load Q3 68 protocol servers..."
                        for iq368 in srvq368:
                                if (q368calc == 200) or (q368calc == 400) or (q368calc == 600) or (q368calc == 800) or (q368calc == 1000) or (q368calc == 1200) or (q368calc == 1400) or (q368calc == 1600) or (q368calc == 1800) or (q368calc == 2000) or (q368calc == 2200) or (q368calc == 2400) or (q368calc == 2600) or (q368calc == 2800) or (q368calc == 3000) or (q368calc == 3200) or (q368calc == 3400) or (q368calc == 3600) or (q368calc == 3800) or (q368calc == 4000) or (q368calc == 4200) or (q368calc == 4400) or (q368calc == 4600) or (q368calc == 4800) or (q368calc == 5000):
                                        q368d = "".join([chr(i2q368) for i2q368 in q368_d])
                                        q368dnewpacket = q368dnewpacket + [q368d]
                                        q368_d = [0x5C,0x45,0x4F,0x54]

                                try:
                                        if randomf == "1" and mode == "FILE":
                                                ip,port = str(iq368)[2:-2].split(":")
                                        else:
                                                ip,port = iq368.split(":")
                                except Exception, e:
                                        print "Error: %s" %e
                                        print " Error in adress " + iq368
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + iq368
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue
                                try:
                                        ip = [int(j) for j in socket.gethostbyname(ip).split(".")]
                                except socket.gaierror, e:
                                        print "Dns error? :", ip
                                        print "Error: %s" %e
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + ip
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue 
                                #print port, ip
                                try:
                                        port = int(port)
                                except Exception, e:
                                        print "Error: %s" %e
                                        print " Error in adress " + ics
                                        if logerr == "1":
                                                error = str(e) + " Error at:" + ics
                                                logerrfile = open('err.log', 'a')
                                                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                                                logerrfile.write(error)
                                                logerrfile.write("\n")
                                                logerrfile.close()
                                        continue
                                if cfg.get("OPTIONS","DEBUG") == "1":
                                        print "Port load - OK!"
                                port = [port>>8&0xFF,port&0xFF]
                                map(q368_d.append,stick)
                                map(q368_d.append,ip)
                                map(q368_d.append,port)
                                q368calc = q368calc + 1
                        #print q368_d
                        q368_d += [0x5C,0x45,0x4F,0x54]
                        q368d = "".join([chr(iq368) for iq368 in q368_d])
                        #print q368d
                        #print "q368dnewpacket" + q368dnewpacket
                        #q368dnewpacket = q368dnewpacket + [q368d]
                        #print q368dnewpacket
                        print "Q3 load - ok!"
        if cfg.get("OPTIONS","MODE").lower() == "monengine" or cfg.get("OPTIONS","MODE").lower() == "boostbymirror":
                if str(mysqldata) == "1":
                        csdsendnewpacket = csdnewpacket
        else:
                if cfg.get("OPTIONS","PORTGS").lower() == "off":
                        pass
                else:
                        if str(mysqldata) == "1":
                                csdsendnewpacket = csdnewpacket
                                if cfg.get("OPTIONS","MODE").lower() == "file2" or cfg.get("OPTIONS","MODE").lower() == "lmplus" or cfg.get("OPTIONS","MODE").lower() == "amxmonplus" or cfg.get("OPTIONS","MODE").lower() == "cmqplus":
                                        csdsendnewpacket2 = csdnewpacket2
                if cfg.get("OPTIONS","PORTS").lower() == "off":
                        pass
                else:
                        if str(mysqldata) == "1":
                                cssdsendnewpacket = cssdnewpacket
                                if cfg.get("OPTIONS","MODE").lower() == "cmqplus":
                                        cssdsendnewpacket2 = cssdnewpacket2
                if cfg.get("OPTIONS","PORTQ3").lower() == "off":
                        pass
                else:
                        if str(mysqldata) == "1":
                                q368dsendpacket = q368d
                if cfg.get("OPTIONS","PORTGS").lower() == "off":
                        pass
                else:
                        if str(mysqldata) == "1":
                                hldsendnewpacket = hldnewpacket
                if cfg.get("OPTIONS","PORTS").lower() == "off":
                        pass
                else:
                        if str(mysqldata) == "1":
                                hl2dsendnewpacket = hl2dnewpacket
#------                
	print "Masterserver v0.4.8 alpha 5 (04.11.13) Loaded OK.\n"
        if cfg.get("OPTIONS","MODE").lower() == "monengine" or cfg.get("OPTIONS","MODE").lower() == "boostbymirror":
              	print "Loaded CS 1.6 list with " + str(cscalc) + " servers."
        else:
                if cfg.get("OPTIONS","PORTGS").lower() == "off":
                        pass
                else:
                        print "Loaded CS 1.6 list with " + str(cscalc) + " servers."
                if cfg.get("OPTIONS","PORTS").lower() == "off":
                        pass
                else:
                        print "Loaded CS:S list with " + str(csscalc) + " servers."
                if cfg.get("OPTIONS","PORTGS").lower() == "off":
                        pass
                else:
                        print "Loaded hl 1 list with " + str(hlcalc) + " servers."
                if cfg.get("OPTIONS","PORTS").lower() == "off":
                        pass
                else:
                        print "Loaded hl 2 list with " + str(hl2calc) + " servers."
                if cfg.get("OPTIONS","PORTQ3").lower() == "off":
                        pass
                else:
                        print "Loaded Q3 (68 protocol) list with " + str(q368calc) + " servers."

        if str(cfg.get("OPTIONS","CHECKNEWVERSION")) == "1":
                thread.start_new_thread(CHECKNEWVERSION,())

		
def console():
        time.sleep(0.5)
        global SigTerm 
        while SigTerm == "0":
                str_in = raw_input("\n"+"Enter command(reload/stop):")
                if str_in.lower() == "reload" or str_in.lower() == "restart":
                        load_servers()
                elif str_in.lower() == "stop" or str_in.lower() == "exit":
                        SigTerm = "1"
                        if cfg.get("OPTIONS","PORTGS").lower() == "off":
                                pass
                        else:
                                s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
                                host,port = cfg.get("OPTIONS","HOST"),cfg.getint("OPTIONS","PORTGS")
                                s.sendto('111',(host,port))
                        time.sleep(0.1)
                        if cfg.get("OPTIONS","PORTS").lower() == "off":
                                pass
                        else:
                                s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
                                host,port = cfg.get("OPTIONS","HOST"),cfg.getint("OPTIONS","PORTS")
                                s.sendto('111',(host,port))
                        time.sleep(0.1)
                        if cfg.get("OPTIONS","PORTQ3").lower() == "off":
                                pass
                        else:
                                s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
                                host,port = cfg.get("OPTIONS","HOST"),cfg.getint("OPTIONS","PORTQ3")
                                s.sendto('111',(host,port))
                        time.sleep(0.1)
                elif str_in.lower() == "stats":
                        print "Threads: "+str(thread._count())
                elif str_in.lower() == "version":
                        print str(cfg.get("OPTIONS","VERSION"))
                elif str_in.lower() == "help":
                        print "You can write to author by e-mail jesuspunk13@yandex.ru, icq 2222674."
                else:
                        print "wrong input/command"
        global SigTermC
        SigTermC = 1
	thread.exit()
try:
	cfg = ConfigParser.ConfigParser()
	cfg.read("ms.cfg")
	refresh = cfg.getfloat("OPTIONS","REFRESH")
        print "Start load servers lists"
	load_servers()
        if cfg.get("OPTIONS","MODE").lower() == "monengine" or cfg.get("OPTIONS","MODE").lower() == "boostbymirror":
                thread.start_new_thread(serve_forevergs,())
        else:	
                if cfg.get("OPTIONS","PORTGS").lower() == "off":
                        pass
                else:
                        thread.start_new_thread(serve_forevergs,())
                if cfg.get("OPTIONS","PORTS").lower() == "off":
                        pass
                else:
                        thread.start_new_thread(serve_forevers,())
                if cfg.get("OPTIONS","PORTQ3").lower() == "off":
                        pass
                else:
                        thread.start_new_thread(serve_foreverq3,())
	thread.start_new_thread(massiviper,())
	thread.start_new_thread(console,())
        timeref = 0
	while SigTerm == "0":
		time.sleep(1)
                timeref = int(timeref) + 1
                if int(timeref) == int(refresh): 
                        print "\n"
                        load_servers()
                        timeref = 0
        SigTermGScheck = 0
        SigTermScheck = 0
        SigTermQ3check = 0
        SigTermFcheck = 0
        SigTermCcheck = 0
        while Sigtermall < int(5):
                time.sleep(0.1)
                if cfg.get("OPTIONS","PORTGS").lower() == "off":
                        Sigtermall = Sigtermall + 1
                if cfg.get("OPTIONS","PORTS").lower() == "off":
                        Sigtermall = Sigtermall + 1
                if cfg.get("OPTIONS","PORTQ3").lower() == "off":
                        Sigtermall = Sigtermall + 1
                if SigTermGS == 1 and SigTermGScheck == 0:
                        print "Server forever CS1.6/HL1 Stoped .. OK"
                        Sigtermall = Sigtermall + 1
                        SigTermGScheck = 1
                        time.sleep(0.1)
                if SigTermS == 1 and SigTermScheck == 0:
                        print "Server forever CSS/HL2 Stoped .. OK"
                        Sigtermall = Sigtermall + 1
                        SigTermScheck = 1
                        time.sleep(0.1)
                if SigTermQ3 == 1 and SigTermQ3check == 0:
                        print "Server forever Q3 Stoped .. OK"
                        Sigtermall = Sigtermall + 1
                        SigTermQ3check = 1
                        time.sleep(0.1)
                if SigTermC == 1 and SigTermCcheck == 0:
                        print "Console closed .. OK"
                        Sigtermall = Sigtermall + 1
                        SigTermCcheck = 1
                        time.sleep(0.1)
                if SigTermF == 1 and SigTermFcheck == 0:
                        print "Simple DOS protection (AntiFlood) stoped .. OK"
                        Sigtermall = Sigtermall + 1
                        SigTermFcheck = 1
                        time.sleep(0.1)
        time.sleep(0.5)
        print "Master server shutdown ... OK"
        sys.exit()

except:
	print sys.exc_info()[0]
	if logerr == "1":
                error = str(sys.exc_info()[0])
                logerrfile = open('err.log', 'a')
                logerrfile.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S '))
                logerrfile.write(error)
                logerrfile.write("\n")
                logerrfile.close()
