viewgit/index.php:465 Only variables should be passed by reference [2048]

viewgit/index.php:466 Non-static method GeSHi::get_language_name_from_extension() should not be called statically [2048]

  1. #
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Whois module for the pywhoisd server
  5.  
  6. import SocketServer, re, math, syslog, threading
  7. from socket import socket, AF_INET, SOCK_STREAM
  8. from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
  9. from ipcalc import IP, Network
  10.  
  11. def FormatOutput(field, value):
  12. """
  13. Format a field, value pair for the output
  14. from the server.
  15. """
  16. output = (field + ":").ljust(24)
  17. output += value + "\n"
  18. return " "*4 + output
  19.  
  20. def FormatMessage(message):
  21. """
  22. Prepare a message to be written from the
  23. server.
  24. """
  25. output = ""
  26. for line in message.split("\n"):
  27. line = line.strip()
  28. output += """\n :: """ + line
  29. return output + "\n"
  30.  
  31.  
  32. class Logger():
  33. """
  34. Logger class that allow pywhoisd to log
  35. everything on syslog.
  36. """
  37. def __init__(self, verbose = False):
  38. self.verbose = verbose
  39.  
  40. def Log(self, message):
  41. """Log a message to syslog"""
  42. syslog.syslog ("[pywhoisd] " + message)
  43. if self.verbose:
  44. print message
  45.  
  46. def __call__(self, message):
  47. self.Log (message)
  48.  
  49. class Config():
  50. """
  51. Config class manage configuration contained
  52. in the config file and acts like a dictionary
  53. that provides data to other classes
  54. """
  55. def __init__(self, config_file):
  56. """
  57. Load config file and save data in memory
  58. """
  59. self.config = {}
  60. f = open(config_file, 'r')
  61. content = f.read()
  62. f.close()
  63. for (key, value) in re.findall(r"([^\s]+)\s*=\s*([^;]+)\s*;", content):
  64. self.config[key] = value
  65.  
  66. def __getitem__(self, key):
  67. if self.config.has_key(key):
  68. return self.config[key]
  69. else:
  70. return None
  71.  
  72. def has_key(self, key):
  73. return self.config.has_key(key)
  74.  
  75.  
  76. class WhoisRequestHandler(SocketServer.StreamRequestHandler):
  77. """
  78. This handler answers to the whois request that
  79. arrives to the WhoisServer.
  80. """
  81.  
  82. def handle(self, ):
  83. # Come prima cosa salutiamo
  84. hello = self.server.config['welcome_banner']
  85. if hello:
  86. response = FormatMessage(hello)
  87. else:
  88. response = ""
  89.  
  90. # Obtain the whois request
  91. request = self.rfile.readline().strip()
  92.  
  93. if re.search(r"\d+\.\d+\.\d+\.\d+", request.strip()):
  94. response += self.server.ResolveAddress(request.split("/")[0])
  95. else:
  96. response += self.server.ResolveDomain(request)
  97. response += FormatMessage("Bye")
  98.  
  99. self.request.send (response)
  100. return
  101.  
  102.  
  103. class WhoisServer(SocketServer.ThreadingTCPServer):
  104. """
  105. The real server. We allow reusing of address
  106. so we can stop and start in a moment.
  107. """
  108. allow_reuse_address = True
  109. def __init__(self, (host, port), logger, config):
  110.  
  111. SocketServer.ThreadingTCPServer.__init__(self, (host, port),
  112. WhoisRequestHandler)
  113. self.logger = logger
  114. self.config = config
  115. self.ip_database = {}
  116. self.domain_database = {}
  117. self.LoadDatabase(config['database_file'])
  118.  
  119. def LoadDatabase(self, database_file):
  120. """
  121. Populate server database with the data in the database
  122. file
  123. """
  124. self.logger.Log ("Populating database with entry in %s" % database_file)
  125. try:
  126. f = open(database_file, 'r')
  127. database_data = f.read()
  128. except IOError:
  129. self.logger.Log ("Error while loading config file. exiting")
  130.  
  131. nets = re.findall (r"net\s+(\d+\.\d+\.\d+\.\d+[/\d]*)[\s|\n]+\{([^\}]+)\};",
  132. database_data)
  133. for net in nets:
  134. self.logger.Log ("Loading net %s" % net[0])
  135. fields = re.findall(r"(\w+)\s*=\s*([^;]+);", net[1])
  136. name, owner, ns = None, None, None
  137. data = {}
  138. for field, value in fields:
  139. if field.lower() == 'name':
  140. name = value.strip()
  141. elif field.lower() == 'owner':
  142. owner = value.strip()
  143. elif field.lower() == 'ns':
  144. ns = value.strip()
  145. else:
  146. data[field] = value
  147. self.ip_database[net[0]] = Net(name = name, owner = owner, ns = ns,
  148. data = data)
  149.  
  150. domains = re.findall(r"domain\s+([^\s]+)[\s|\n]+\{([^\}]+)\};",
  151. database_data)
  152. for domain in domains:
  153. self.logger.Log ("Loading domain %s" % domain[0])
  154. fields = re.findall(r"(\w+)\s*=\s*([^;]+);", domain[1])
  155. name, owner, ns = None, None, None
  156. data = {}
  157. for field, value in fields:
  158. if field.lower() == 'name':
  159. name = value.strip()
  160. elif field.lower() == 'owner':
  161. owner = value.strip()
  162. elif field.lower() == 'ns':
  163. ns = value.strip()
  164. else:
  165. data[field] = value
  166. self.domain_database[domain[0]] = Domain(name = name,
  167. owner = owner,
  168. ns = ns,
  169. data = data)
  170.  
  171. def ResolveDomain(self, domain):
  172. """
  173. Find domain data and return them ready for output
  174. for the server
  175. """
  176. domain = domain.strip(".")
  177. output = ""
  178. domains = self.GetParentDomains(domain)
  179. for d in domains:
  180. output += FormatMessage("GNet whoisd answering for domain %s" % d)
  181. output += FormatOutput ("Domain", d)
  182. domain = self.domain_database[d]
  183. if domain.name is not None:
  184. output += FormatOutput ("Name", domain.name)
  185. if domain.owner is not None:
  186. output += FormatOutput ("Owner", domain.owner)
  187. if domain.ns is not None:
  188. output += FormatOutput ("Nameserver", domain.ns)
  189. if len(domain.data.items()) > 0:
  190. output += FormatMessage("Additional data")
  191. for k, v in domain.data.items():
  192. output += FormatOutput (k.capitalize(),v)
  193. if len(domains) == 0:
  194. return FormatMessage("No domain found for %s" % domain)
  195. return output
  196.  
  197.  
  198. def GetParentDomains(self, domain):
  199. """
  200. Return a list of domains that contain the domain
  201. passed as argument
  202. """
  203. interesting_domains = []
  204. for domain_name, domain_data in self.domain_database.items():
  205. if domain.endswith(domain_name):
  206. interesting_domains.append (domain_name)
  207. return interesting_domains
  208.  
  209. def ResolveAddress(self, ip):
  210. """
  211. Resolve an ip: it searches all the data that match it
  212. (i.e. all the subnets that contain it) and return
  213. output text ready for the server response.
  214. """
  215. output = ""
  216. nets = self.GetParentNetworks(ip)
  217. for net in nets:
  218. output += FormatMessage("GNet whoisd answering for ip %s" % ip)
  219. output += FormatOutput ("Range", net)
  220. net = self.ip_database[net]
  221. if net.name is not None:
  222. output += FormatOutput ("Name", net.name)
  223. if net.owner is not None:
  224. output += FormatOutput ("Owner", net.owner)
  225. if net.ns is not None:
  226. output += FormatOutput ("Nameserver", net.ns)
  227. if len(net.data.items()) > 0:
  228. output += FormatMessage("Additional data")
  229. for k, v in net.data.items():
  230. output += FormatOutput (k.capitalize(),v)
  231. if len(nets) == 0:
  232. output = FormatMessage("Address %s not found\n" % ip)
  233. return output
  234.  
  235. def GetParentNetworks(self, ip):
  236. """
  237. Get network in which the given ip is
  238. """
  239. interesting_networks = []
  240. for (address, net) in self.ip_database.items():
  241. try:
  242. if IP(ip) in Network(address):
  243. interesting_networks.append (address)
  244. except:
  245. continue
  246. return interesting_networks
  247.  
  248. class Net():
  249. """
  250. Net is a class representing the network
  251. contained in the local database and the
  252. net obtained from other whois server.
  253. It act as a C struct containing only the
  254. data and no method.
  255. """
  256. def __init__(self, name, owner, ns, data):
  257. self.name = name
  258. self.owner = owner
  259. self.ns = ns
  260. self.data = data
  261.  
  262. class Domain():
  263. """
  264. The same of Net, but with the domain names.
  265. """
  266. def __init__(self, name, owner, ns, data):
  267. self.name, self.owner, self.ns = name, owner, ns
  268. self.data = data
  269.  
  270. class WhoisHTTPRequestHandler(BaseHTTPRequestHandler):
  271.  
  272. def do_GET(self):
  273. print self.path[1:]
  274. request = self.path[1:].strip()
  275. s = socket(AF_INET, SOCK_STREAM)
  276. s.connect(("127.0.0.1", 43))
  277. s.send (request + "\n")
  278. response = s.recv(1024)
  279. s.close ()
  280. self.send_response(200)
  281. self.send_header('Content-type', 'text/html')
  282. self.end_headers()
  283. self.wfile.write(re.sub("\n", "<br>\n", response))
  284. return
  285.  
  286. class BackgroundWhoisHTTPServer(threading.Thread):
  287.  
  288. def __init__(self, whoisserver):
  289. threading.Thread.__init__(self)
  290.  
  291. def run(self):
  292. self.server = HTTPServer(("0.0.0.0", 80), WhoisHTTPRequestHandler)
  293. self.server.serve_forever()
  294.  
  295. def shutdown(self):
  296. self.server.socket.close ()
  297. self.server.shutdown()
  298.  
  299.  
  300.  
  301.  
  302.  
  303.