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. # Default values. You can change these to adjust package
  27. # configuration
  28. #
  29. # apt_proxy_file specifies the name of the file that
  30. # poisson_vpn will use as configuration file for the
  31. # apt proxy. It will created on connection and deleted
  32. # on disconnection
  33. apt_proxy_file = "/etc/apt/apt.conf.d/99poisson_proxy"
  34.  
  35. # mac_addresses is a list of unicode strings containing the
  36. # mac addresses of access point that are in the local
  37. # subnet where the VPN is available
  38. mac_addresses = [ u"00:0d:54:a9:cf:36",
  39. u'00:13:64:2a:10:00' ]
  40.  
  41. # using_notify controls if notifications of
  42. # a successful conection should be showed to
  43. # logged user.
  44. using_notify = True
  45.  
  46. # notify_body is the content of the notification that
  47. # will be displayed in alle the gnome active sessions
  48. # when the connection is established.
  49. notify_body = "La connessione VPN a poisson è stata effettuata ed è ora possibile navigare in Internet."
  50.  
  51. #
  52. # START OF THE CODE; DON'T MODIFY THE SCRIPT BEYOND THIS LINE
  53. #
  54.  
  55. import dbus, sys, os, subprocess, re, time
  56. from dbus.mainloop.glib import DBusGMainLoop
  57.  
  58. DBusGMainLoop(set_as_default=True)
  59.  
  60. def init():
  61. """
  62. Istruzioni da eseguire prima di fare ogni altra cosa. In poche
  63. parole otteniamo il bus di sistema che ci servirà abbondantemente
  64. in tutto lo script.
  65. """
  66. global bus
  67. bus = dbus.SystemBus()
  68.  
  69. def is_poisson_vpn(settings):
  70. """
  71. Questa funzione riconosce la vpn per connettersi alla rete esterna
  72. tramite poisson facendo un check su nome dell'host remote e sulla
  73. porta. Nonostante il nome non sia un fqdn, penso che il test sia
  74. abbastanza deterministico.
  75. """
  76. if settings['connection']['type'] != "vpn":
  77. return False
  78. if settings['vpn']['data']['remote'] != "poisson.phc-priv":
  79. return False
  80.  
  81. # 1194 è la porta di default per la vpn, quindi può anche essere non
  82. # specificata nel file di configurazione. Controlliamo se è così, oppure
  83. # se è stata specificata ed impostata a 1194.
  84. if settings['vpn']['data'].has_key("port") and settings['vpn']['data']['port'] != "1194":
  85. return False
  86.  
  87. # Se siamo arrivati a questo punto significa che questa è davvero
  88. # la VPN per connettersi alla rete esterna da poisson
  89. return True
  90.  
  91. def get_poisson_vpn():
  92. """
  93. Ottiene la vpn per poisson tramite dbus
  94. """
  95.  
  96. # Tentiamo di caricare la configurazione dell'utente.
  97. proxy = bus.get_object("org.freedesktop.NetworkManagerUserSettings",
  98. "/org/freedesktop/NetworkManagerSettings")
  99. interface = dbus.Interface(proxy, "org.freedesktop.NetworkManagerSettings")
  100.  
  101. # Ritorniamo None se non siamo in grado di trovare la VPN oppure
  102. # se è già attiva
  103. c = None
  104.  
  105. # Controlliamo tutte le connessione salvate nelle connessione dell'utente
  106. # sperando di trovare la VPN. Se questa è specificata nelle connessioni di sistema,
  107. # beh.. questa è una feature per la prossima versione.
  108. for connection in interface.ListConnections():
  109. proxy = bus.get_object("org.freedesktop.NetworkManagerUserSettings",
  110. connection)
  111. settings = proxy.GetSettings(dbus_interface="org.freedesktop.NetworkManagerSettings.Connection")
  112.  
  113. # Check per determinare se questa è la connessione giusta
  114. if is_poisson_vpn (settings):
  115. c = connection
  116.  
  117. # Controlliamo se la VPN è già attiva...
  118. proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
  119. interface = dbus.Interface(proxy, "org.freedesktop.DBus.Properties")
  120.  
  121. # ...provando a confrontarla con tutte le connessioni attive
  122. for connection in interface.Get("org.freedesktop.NetworkManager", "ActiveConnections"):
  123. proxy = bus.get_object("org.freedesktop.NetworkManager", connection)
  124. interface = dbus.Interface(proxy, "org.freedesktop.DBus.Properties")
  125. connection = interface.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection")
  126. if connection == c:
  127. return None
  128.  
  129. # Ritorniamo la connessione VPN o None se non c'è bisogno di fare nulla
  130. return c
  131.  
  132. def get_base_connection():
  133. """
  134. Otteniamo la connessione su cui attivare la VPN (i.e. PHC-wifi o CDCWL1)
  135. """
  136.  
  137. # Otteniamo la lista di tutte le connessioni attive al momento
  138. proxy = bus.get_object("org.freedesktop.NetworkManager",
  139. "/org/freedesktop/NetworkManager")
  140. interface = dbus.Interface(proxy, "org.freedesktop.DBus.Properties")
  141. active_connections = interface.Get('org.freedesktop.NetworkManager', 'ActiveConnections')
  142.  
  143. # Esaminiamo ogni connessione attiva e verifichiamo se è una connessione wireless
  144. # e se lo è se l'AP ha lo stesso MAC di PHC-wifi o di CDCWL1
  145. for connection in active_connections:
  146. proxy = bus.get_object("org.freedesktop.NetworkManager",
  147. connection)
  148. interface = dbus.Interface(proxy, "org.freedesktop.DBus.Properties")
  149. path = interface.Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection')
  150.  
  151. proxy = bus.get_object('org.freedesktop.NetworkManagerUserSettings',
  152. path)
  153. interface = dbus.Interface(proxy, 'org.freedesktop.NetworkManagerSettings.Connection')
  154. settings = interface.GetSettings()
  155.  
  156. if settings.has_key("802-11-wireless"):
  157.  
  158. # Rimuoviamo dalla lista gli access point che non sono
  159. # all'interno del Dipartimento di Matematica
  160. intersection = filter(lambda x : x in mac_addresses,
  161. settings['802-11-wireless']['seen-bssids'])
  162.  
  163. # Se ne è rimasto qualcuno ritorniamo la connessione
  164. if len(intersection) != 0:
  165. return connection
  166.  
  167. # Se siamo arrivati a questo punto significa che la connessione attiva
  168. # non è direttamente connessa a poisson.phc-priv e qunidi possiamo
  169. # anche lasciar perdere
  170. reset_apt_proxy ()
  171. return None
  172.  
  173. def has_default_route():
  174. """Return True if exists a default route"""
  175. p = subprocess.Popen(["ip", "route", "show"], stdout = subprocess.PIPE)
  176. output = p.communicate()[0]
  177. if "default" in output:
  178. return True
  179. else:
  180. return False
  181.  
  182. def activate_connection(connection):
  183. """
  184. Attiva la connessione
  185. """
  186. proxy = bus.get_object("org.freedesktop.NetworkManager",
  187. "/org/freedesktop/NetworkManager")
  188. interface = dbus.Interface (proxy, "org.freedesktop.NetworkManager")
  189.  
  190. # Otteniamo la connessione di base su cui attivare la VPN
  191. base_connection = get_base_connection ()
  192.  
  193. if base_connection is not None:
  194. interface.ActivateConnection('org.freedesktop.NetworkManagerUserSettings',
  195. connection,
  196. dbus.ObjectPath("/"),
  197. base_connection)
  198.  
  199. # Setup apt proxy on poisson:3142
  200. setup_apt_proxy ()
  201.  
  202. # If configured to try notification, make a bubble appear
  203. # in the user desktop
  204. if using_notify:
  205.  
  206. # Wait for the connection to be completed. We should test
  207. # that user has internet access
  208. starting_time = time.time()
  209. while(time.time() < starting_time + 10):
  210. if has_default_route():
  211. continue
  212. else:
  213. time.sleep(0.5)
  214.  
  215. if not has_default_route():
  216. return
  217.  
  218. # To get user Session bus we should get the content
  219. # of DBUS_SESSION_BUS_ADDRESS of user
  220. # so we can start getting the pid of gnome-session
  221. p = subprocess.Popen(["ps", "-C", "gnome-session", "-o", "pid="],
  222. stdout = subprocess.PIPE)
  223. output = p.communicate()[0]
  224. environments = []
  225. for pid in output.split("\n"):
  226. try:
  227. pid = int(pid.strip())
  228. except:
  229. continue
  230. with open("/proc/%d/environ" % pid, "r") as handle:
  231. env = {}
  232. content = handle.read()
  233. for pair in content.split("\0"):
  234. pieces = pair.split("=")
  235. key = pieces[0]
  236. value = "=".join(pieces[1:])
  237. env[key] = value
  238. environments.append(env)
  239.  
  240. # Copy environment of users so we can send graphical notifications
  241. # to them. Quite hack, but...
  242. for env in environments:
  243.  
  244. for key, value in env.items():
  245. os.putenv(key, value)
  246.  
  247. # Get SessionBus
  248. mybus = dbus.SessionBus()
  249. notifyService = mybus.get_object("org.freedesktop.Notifications",
  250. "/org/freedesktop/Notifications")
  251. interface = dbus.Interface(notifyService, "org.freedesktop.Notifications")
  252. interface.Notify('poisson-vpn', 0,
  253. 'poisson-vpn', "Connessione effettuata",
  254. notify_body, [], {}, 15000)
  255.  
  256.  
  257. else:
  258. reset_apt_proxy ()
  259.  
  260. def reset_apt_proxy():
  261. """Delete apt proxy configuration file"""
  262. if os.path.exists(apt_proxy_file):
  263. os.remove(apt_proxy_file)
  264.  
  265. def setup_apt_proxy():
  266. if not os.path.exists(apt_proxy_file):
  267. with open(apt_proxy_file, "w") as handle:
  268. handle.write("""Acquire::http { Proxy "http://poisson:3142"; };""")
  269. handle.write("\n")
  270.  
  271.  
  272. if __name__ == "__main__":
  273.  
  274. # Se hai appena staccato una VPN probabilmente non hai bisogno
  275. # che ti riattivi quella per poisson (anche perché potresti stare
  276. # cercando di liberartente).
  277. if sys.argv[2] == "vpn-down":
  278. sys.exit (0)
  279.  
  280. # Se è appena stata attivata una VPN non ha senso cercare di
  281. # attivarne un'altra (se non altro perché NM non ne supporta più
  282. # di una nello stesso momento)
  283. if sys.argv[2] == "vpn-up":
  284. sys.exit (0)
  285.  
  286. # Se hai appena deconfigurato un'interfaccia probabilmente non
  287. # desideri attivare la VPN
  288. if sys.argv[2] == "down":
  289. reset_apt_proxy()
  290. sys.exit (0)
  291.  
  292. # Otteniamo il bus
  293. init ()
  294.  
  295. # ...e la VPN per poisson
  296. poisson_vpn = get_poisson_vpn ()
  297.  
  298. # Se non l'abbiamo trovata oppure è
  299. # già attiva possiamo anche uscire
  300. if (poisson_vpn is None):
  301. reset_apt_proxy ()
  302. sys.exit (0)
  303.  
  304. # Altrimenti la attiviamo, e poi usciamo :)
  305. activate_connection (poisson_vpn)
  306.  
  307. sys.exit (0)
  308.  
  309.