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. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Questo è un semplice script che attiva automaticamente
  5. # la VPN verso poisson per chi si connette ad una rete wireless
  6. # dall'interno del dipartimenti di Matematica di Pisa.
  7. #
  8. # Io lo uso per evitare di dover fare un clic di troppo ;)
  9. #
  10. # Ringrazio Tambet Ingo-2 dal cui script ho preso ispirazione
  11. # per cominciare questo.
  12. #
  13. # Potete trovare la sua versione di uno script in python per fare
  14. # una cosa simile in questo thread:
  15. # http://old.nabble.com/dbus-and-OpenVPN-Autostart-td21905375.html
  16. #
  17. # Questo codice è rilasciato sotto licenza GPL3 che si trova nel
  18. # file LICENSE nell'archivio dei sorgenti che potete trovare clonando
  19. # il repository git su http://poisson.phc.unipi.it/~robol/gits/AutoVPN.git
  20. #
  21. #
  22.  
  23.  
  24. __author__ = "Leonardo Robol <robol@poisson.phc.unipi.it>"
  25.  
  26. # Defaults
  27. apt_proxy_file = "/etc/apt/apt.conf.d/99poisson_proxy"
  28.  
  29.  
  30. import dbus, sys, os, subprocess, re, time
  31. from dbus.mainloop.glib import DBusGMainLoop
  32.  
  33.  
  34. notify_body = "La connessione VPN a poisson è stata effettuata ed è ora possibile navigare in Internet."
  35. using_notify = True
  36.  
  37. DBusGMainLoop(set_as_default=True)
  38.  
  39. def init():
  40. """
  41. Istruzioni da eseguire prima di fare ogni altra cosa. In poche
  42. parole otteniamo il bus di sistema che ci servirà abbondantemente
  43. in tutto lo script.
  44. """
  45. global bus
  46. bus = dbus.SystemBus()
  47.  
  48. def is_poisson_vpn(settings):
  49. """
  50. Questa funzione riconosce la vpn per connettersi alla rete esterna
  51. tramite poisson facendo un check su nome dell'host remote e sulla
  52. porta. Nonostante il nome non sia un fqdn, penso che il test sia
  53. abbastanza deterministico.
  54. """
  55. if settings['connection']['type'] != "vpn":
  56. return False
  57. if settings['vpn']['data']['remote'] != "poisson.phc-priv":
  58. return False
  59.  
  60. # 1194 è la porta di default per la vpn, quindi può anche essere non
  61. # specificata nel file di configurazione. Controlliamo se è così, oppure
  62. # se è stata specificata ed impostata a 1194.
  63. if settings['vpn']['data'].has_key("port") and settings['vpn']['data']['port'] != 1194:
  64. return False
  65.  
  66. # Se siamo arrivati a questo punto significa che questa è davvero
  67. # la VPN per connettersi alla rete esterna da poisson
  68. return True
  69.  
  70. def get_poisson_vpn():
  71. """
  72. Ottiene la vpn per poisson tramite dbus
  73. """
  74.  
  75. # Tentiamo di caricare la configurazione dell'utente.
  76. proxy = bus.get_object("org.freedesktop.NetworkManagerUserSettings",
  77. "/org/freedesktop/NetworkManagerSettings")
  78. interface = dbus.Interface(proxy, "org.freedesktop.NetworkManagerSettings")
  79.  
  80. # Ritorniamo None se non siamo in grado di trovare la VPN oppure
  81. # se è già attiva
  82. c = None
  83.  
  84. # Controlliamo tutte le connessione salvate nelle connessione dell'utente
  85. # sperando di trovare la VPN. Se questa è specificata nelle connessioni di sistema,
  86. # beh.. questa è una feature per la prossima versione.
  87. for connection in interface.ListConnections():
  88. proxy = bus.get_object("org.freedesktop.NetworkManagerUserSettings",
  89. connection)
  90. settings = proxy.GetSettings(dbus_interface="org.freedesktop.NetworkManagerSettings.Connection")
  91.  
  92. # Check per determinare se questa è la connessione giusta
  93. if is_poisson_vpn (settings):
  94. c = connection
  95.  
  96. # Controlliamo se la VPN è già attiva...
  97. proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
  98. interface = dbus.Interface(proxy, "org.freedesktop.DBus.Properties")
  99.  
  100. # ...provando a confrontarla con tutte le connessioni attive
  101. for connection in interface.Get("org.freedesktop.NetworkManager", "ActiveConnections"):
  102. proxy = bus.get_object("org.freedesktop.NetworkManager", connection)
  103. interface = dbus.Interface(proxy, "org.freedesktop.DBus.Properties")
  104. connection = interface.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection")
  105. if connection == c:
  106. return None
  107.  
  108. # Ritorniamo la connessione VPN o None se non c'è bisogno di fare nulla
  109. return c
  110.  
  111. def get_base_connection():
  112. """
  113. Otteniamo la connessione su cui attivare la VPN (i.e. PHC-wifi o CDCWL1)
  114. """
  115.  
  116. # Otteniamo la lista di tutte le connessioni attive al momento
  117. proxy = bus.get_object("org.freedesktop.NetworkManager",
  118. "/org/freedesktop/NetworkManager")
  119. interface = dbus.Interface(proxy, "org.freedesktop.DBus.Properties")
  120. active_connections = interface.Get('org.freedesktop.NetworkManager', 'ActiveConnections')
  121.  
  122. # Esaminiamo ogni connessione attiva e verifichiamo se è una connessione wireless
  123. # e se lo è se l'AP ha lo stesso MAC di PHC-wifi o di CDCWL1
  124. for connection in active_connections:
  125. proxy = bus.get_object("org.freedesktop.NetworkManager",
  126. connection)
  127. interface = dbus.Interface(proxy, "org.freedesktop.DBus.Properties")
  128. path = interface.Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection')
  129.  
  130. proxy = bus.get_object('org.freedesktop.NetworkManagerUserSettings',
  131. path)
  132. interface = dbus.Interface(proxy, 'org.freedesktop.NetworkManagerSettings.Connection')
  133. settings = interface.GetSettings()
  134.  
  135. if settings.has_key("802-11-wireless"):
  136.  
  137. # MAC address of CDCWL1 ap
  138. if settings['802-11-wireless']['seen-bssids'][0] == u'00:12:0E:8C:AE:A0':
  139. return connection
  140.  
  141. # MAC address of PHC-wifi ap
  142. if settings['802-11-wireless']['seen-bssids'][0] == u'00:0f:cb:aa:16:52':
  143. return connection
  144.  
  145. # Se siamo arrivati a questo punto significa che la connessione attiva
  146. # non è direttamente connessa a poisson.phc-priv e qunidi possiamo
  147. # anche lasciar perdere
  148. reset_apt_proxy ()
  149. return None
  150.  
  151. def has_default_route():
  152. """Return True if exists a default route"""
  153. p = subprocess.Popen(["ip", "route", "show"], stdout = subprocess.PIPE)
  154. output = p.communicate()[0]
  155. if "default" in output:
  156. return True
  157. else:
  158. return False
  159.  
  160. def activate_connection(connection):
  161. """
  162. Attiva la connessione
  163. """
  164. proxy = bus.get_object("org.freedesktop.NetworkManager",
  165. "/org/freedesktop/NetworkManager")
  166. interface = dbus.Interface (proxy, "org.freedesktop.NetworkManager")
  167.  
  168. # Otteniamo la connessione di base su cui attivare la VPN
  169. base_connection = get_base_connection ()
  170.  
  171. if base_connection is not None:
  172. interface.ActivateConnection('org.freedesktop.NetworkManagerUserSettings',
  173. connection,
  174. dbus.ObjectPath("/"),
  175. base_connection)
  176.  
  177. # Setup apt proxy on poisson:3142
  178. setup_apt_proxy ()
  179.  
  180. # If configured to try notification, make a bubble appear
  181. # in the user desktop
  182. if using_notify:
  183.  
  184. # Wait for the connection to be completed. We should test
  185. # that user has internet access
  186. starting_time = time.time()
  187. while(time.time() < starting_time + 10):
  188. if has_default_route():
  189. continue
  190. else:
  191. time.sleep(0.5)
  192.  
  193. if not has_default_route():
  194. return
  195.  
  196. # To get user Session bus we should get the content
  197. # of DBUS_SESSION_BUS_ADDRESS of user
  198. # so we can start getting the pid of gnome-session
  199. p = subprocess.Popen(["ps", "-C", "gnome-session", "-o", "pid="],
  200. stdout = subprocess.PIPE)
  201. output = p.communicate()[0]
  202. environments = []
  203. for pid in output.split("\n"):
  204. try:
  205. pid = int(pid.strip())
  206. except:
  207. continue
  208. with open("/proc/%d/environ" % pid, "r") as handle:
  209. env = {}
  210. content = handle.read()
  211. for pair in content.split("\0"):
  212. pieces = pair.split("=")
  213. key = pieces[0]
  214. value = "=".join(pieces[1:])
  215. env[key] = value
  216. environments.append(env)
  217.  
  218. # Copy environment of users so we can send graphical notifications
  219. # to them. Quite hack, but...
  220. for env in environments:
  221.  
  222. for key, value in env.items():
  223. os.putenv(key, value)
  224.  
  225. # Get SessionBus
  226. mybus = dbus.SessionBus()
  227. notifyService = mybus.get_object("org.freedesktop.Notifications",
  228. "/org/freedesktop/Notifications")
  229. interface = dbus.Interface(notifyService, "org.freedesktop.Notifications")
  230. interface.Notify('poisson-vpn', 0,
  231. 'poisson-vpn', "Connessione effettuata",
  232. notify_body, [], {}, 15000)
  233.  
  234.  
  235. else:
  236. reset_apt_proxy ()
  237.  
  238. def reset_apt_proxy():
  239. """Delete apt proxy configuration file"""
  240. if os.path.exists(apt_proxy_file):
  241. os.remove(apt_proxy_file)
  242.  
  243. def setup_apt_proxy():
  244. if not os.path.exists(apt_proxy_file):
  245. with open(apt_proxy_file, "w") as handle:
  246. handle.write("""Acquire::http { Proxy "http://poisson:3142"; };""")
  247. handle.write("\n")
  248.  
  249.  
  250. if __name__ == "__main__":
  251.  
  252. # Se hai appena staccato una VPN probabilmente non hai bisogno
  253. # che ti riattivi quella per poisson (anche perché potresti stare
  254. # cercando di liberartente).
  255. if sys.argv[2] == "vpn-down":
  256. sys.exit (0)
  257.  
  258. # Se è appena stata attivata una VPN non ha senso cercare di
  259. # attivarne un'altra (se non altro perché NM non ne supporta più
  260. # di una nello stesso momento)
  261. if sys.argv[2] == "vpn-up":
  262. sys.exit (0)
  263.  
  264. # Se hai appena deconfigurato un'interfaccia probabilmente non
  265. # desideri attivare la VPN
  266. if sys.argv[2] == "down":
  267. reset_apt_proxy()
  268. sys.exit (0)
  269.  
  270. # Otteniamo il bus
  271. init ()
  272.  
  273. # ...e la VPN per poisson
  274. poisson_vpn = get_poisson_vpn ()
  275.  
  276. # Se non l'abbiamo trovata oppure è
  277. # già attiva possiamo anche uscire
  278. if (poisson_vpn is None):
  279. reset_apt_proxy ()
  280. sys.exit (0)
  281.  
  282. # Altrimenti la attiviamo, e poi usciamo :)
  283. activate_connection (poisson_vpn)
  284.  
  285. sys.exit (0)
  286.  
  287.