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. return None
  149.  
  150. def has_default_route():
  151. """Return True if exists a default route"""
  152. p = subprocess.Popen(["ip", "route", "show"], stdout = subprocess.PIPE)
  153. output = p.communicate()[0]
  154. if "default" in output:
  155. return True
  156. else:
  157. return False
  158.  
  159. def activate_connection(connection):
  160. """
  161. Attiva la connessione
  162. """
  163. proxy = bus.get_object("org.freedesktop.NetworkManager",
  164. "/org/freedesktop/NetworkManager")
  165. interface = dbus.Interface (proxy, "org.freedesktop.NetworkManager")
  166.  
  167. # Otteniamo la connessione di base su cui attivare la VPN
  168. base_connection = get_base_connection ()
  169.  
  170. if base_connection is not None:
  171. interface.ActivateConnection('org.freedesktop.NetworkManagerUserSettings',
  172. connection,
  173. dbus.ObjectPath("/"),
  174. base_connection)
  175.  
  176. # Setup apt proxy on poisson:3142
  177. setup_apt_proxy ()
  178.  
  179. # If configured to try notification, make a bubble appear
  180. # in the user desktop
  181. if using_notify:
  182.  
  183. # Wait for the connection to be completed. We should test
  184. # that user has internet access
  185. starting_time = time.time()
  186. while(time.time() < starting_time + 10):
  187. if has_default_route():
  188. continue
  189. else:
  190. time.sleep(0.5)
  191.  
  192. if not has_default_route():
  193. return
  194.  
  195. # To get user Session bus we should get the content
  196. # of DBUS_SESSION_BUS_ADDRESS of user
  197. # so we can start getting the pid of gnome-session
  198. p = subprocess.Popen(["ps", "-C", "gnome-session", "-o", "pid="],
  199. stdout = subprocess.PIPE)
  200. output = p.communicate()[0]
  201. environments = []
  202. for pid in output.split("\n"):
  203. try:
  204. pid = int(pid.strip())
  205. except:
  206. continue
  207. with open("/proc/%d/environ" % pid, "r") as handle:
  208. env = {}
  209. content = handle.read()
  210. for pair in content.split("\0"):
  211. pieces = pair.split("=")
  212. key = pieces[0]
  213. value = "=".join(pieces[1:])
  214. env[key] = value
  215. environments.append(env)
  216.  
  217. # Copy environment of users so we can send graphical notifications
  218. # to them. Quite hack, but...
  219. for env in environments:
  220.  
  221. for key, value in env.items():
  222. os.putenv(key, value)
  223.  
  224. # Get SessionBus
  225. mybus = dbus.SessionBus()
  226. notifyService = mybus.get_object("org.freedesktop.Notifications",
  227. "/org/freedesktop/Notifications")
  228. interface = dbus.Interface(notifyService, "org.freedesktop.Notifications")
  229. interface.Notify('poisson-vpn', 0,
  230. 'poisson-vpn', "Connessione effettuata",
  231. notify_body, [], {}, 15000)
  232.  
  233.  
  234. else:
  235. reset_apt_proxy ()
  236.  
  237. def reset_apt_proxy():
  238. if os.path.exists(apt_proxy_file):
  239. os.path.remove(apt_proxy_file)
  240.  
  241. def setup_apt_proxy():
  242. if not os.path.exists(apt_proxy_file):
  243. with open(apt_proxy_file, "w") as handle:
  244. handle.write("""Acquire::http { Proxy "http://poisson:3142"; };""")
  245. handle.write("\n")
  246.  
  247.  
  248. if __name__ == "__main__":
  249.  
  250. # Se hai appena staccato una VPN probabilmente non hai bisogno
  251. # che ti riattivi quella per poisson (anche perché potresti stare
  252. # cercando di liberartente).
  253. if sys.argv[2] == "vpn-down":
  254. delete_apt_proxy()
  255. sys.exit (0)
  256.  
  257. # Se è appena stata attivata una VPN non ha senso cercare di
  258. # attivarne un'altra (se non altro perché NM non ne supporta più
  259. # di una nello stesso momento)
  260. if sys.argv[2] == "vpn-up":
  261. sys.exit (0)
  262.  
  263. # Se hai appena deconfigurato un'interfaccia probabilmente non
  264. # desideri attivare la VPN
  265. if sys.argv[2] == "down":
  266. delete_apt_proxy()
  267. sys.exit (0)
  268.  
  269. # Otteniamo il bus
  270. init ()
  271.  
  272. # ...e la VPN per poisson
  273. poisson_vpn = get_poisson_vpn ()
  274.  
  275. # Se non l'abbiamo trovata oppure è
  276. # già attiva possiamo anche uscire
  277. if (poisson_vpn is None):
  278. sys.exit (0)
  279.  
  280. # Altrimenti la attiviamo, e poi usciamo :)
  281. activate_connection (poisson_vpn)
  282.  
  283. sys.exit (0)
  284.  
  285.