Timestamp the state monitor; don't boo.
[cnetworkmanager.git] / cnetworkmanager
blobd13ddfd8660ce21e5ec62ce561119eae0de57ba3
1 #! /usr/bin/python
2 # cnetworkmanager: Command Line Interface for NetworkManager
3 # by: http://en.opensuse.org/User:Mvidner
4 # license: http://www.gnu.org/licenses/gpl-2.0.html or later
6 VERSION = "0.8.3"
7 print "cnetworkmanager %s - Command Line Interface for NetworkManager" % VERSION
9 norpm = False
10 import sys
11 # find other modules in our prefix, if specified
12 if len(sys.argv) > 2 and sys.argv[1] == "--prefix":
13 prefix = sys.argv[2]
14 sys.argv[1:] = sys.argv[3:]
15 sys.path.append(prefix + "/share/cnetworkmanager");
17 import os
18 import string
19 import re
20 import time
21 import uuid
22 import math
23 import hashlib
24 import pbkdf2
25 from binascii import hexlify
26 import ConfigParser # knm config
27 from optparse import OptionParser
28 try:
29 import dbus
30 import dbus.service
31 import _dbus_bindings
32 except:
33 print "Install python-1-dbus.rpm or or python-dbus.rpm or python-dbus.deb"
34 norpm = True
35 import xml.dom.minidom
36 try:
37 import gobject
38 except:
39 # todo - only if loop wanted
40 print "Install python-gobject2.rpm or pygobject2.rpm or python-gobject.deb"
41 norpm = True
42 # python-gnome.rpm has gconf for nm-applet...
43 if norpm:
44 sys.exit(1)
46 from dbus.mainloop.glib import DBusGMainLoop
47 DBusGMainLoop(set_as_default=True)
49 LOOP = False
51 bus = dbus.SystemBus()
53 # FOOC = connection (service) string
54 # FOOI = interface string
55 # fooo = object
56 # fooi = interface
57 # foopi = property interface
58 NMC = 'org.freedesktop.NetworkManager'
59 NMI = NMC
60 PI = 'org.freedesktop.DBus.Properties'
61 SSC = "org.freedesktop.NetworkManagerSystemSettings"
62 USC = "org.freedesktop.NetworkManagerUserSettings"
63 NMIC = "org.freedesktop.NetworkManagerInfo"
65 def introspect(obj):
66 ii = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable')
67 print ii.Introspect()
69 class cNM:
70 # TODO: pull them from introspection.xml
71 NM_STATE = ["UNKNOWN", "ASLEEP", "CONNECTING", "CONNECTED", "DISCONNECTED",]
73 def __init__(self, opath):
74 self.opath = opath
75 self.nmo = bus.get_object(NMC, self.opath)
76 self.nmi = dbus.Interface(self.nmo, NMI)
77 self.nmpi = dbus.Interface(self.nmo, PI)
79 def Api(self):
80 return "common"
82 def Dump0(self):
83 "Dumps its own info (not owned objects)."
84 pass
86 def Dump(self):
87 self.Dump0()
88 if options.dev:
89 for device in self.Devices():
90 device.Dump()
92 if options.actcon:
93 print "Active Connections"
94 aconns = self.ActiveConnections()
95 for aconn in aconns:
96 aconn.Dump()
98 def ListNets(self):
99 print "Wifi Networks:"
100 for dev in self.Devices():
101 dev.ListNets()
103 def err_handler(self, *args):
104 print "ERR:", args
106 def silent_handler(self, *args):
107 pass
108 #print "BOO!:", args
110 def quitter_handler(self, *args):
111 # exit the loop that runs only because of us
112 print "padla"
113 sys.exit(0)
115 def WatchState(self):
116 bus.add_signal_receiver(self.state_changed_handler,
117 dbus_interface="org.freedesktop.NetworkManager",
118 signal_name="StateChanged")
120 def state_changed_handler(self, *args):
121 s = args[0]
122 ss = self.NM_STATE[s]
123 print time.strftime("(%X)"),
124 print "State:", ss
127 def make_nm(opath):
128 "Detects NM version and chooses appropriate class"
130 nmo = bus.get_object(NMC, opath)
131 nmi = dbus.Interface(nmo, NMI)
132 try:
133 dummy = nmi.getDevices()
134 return cNM_06(opath)
135 except dbus.exceptions.DBusException:
136 return cNM_07(opath)
138 class cNM_06(cNM):
139 def Api(self):
140 return "06"
142 def SetWifiEnabled(self, v):
143 # TODO: async call, catch the state signal and exit
144 # weird: synchronous call works, but times out
145 # asynchronous call does not work
146 self.nmi.setWirelessEnabled(v,
147 reply_handler=self.quitter_handler,
148 error_handler=self.quitter_handler)
149 global LOOP
150 LOOP = True
152 def SetOnline(self, v):
153 if v:
154 self.nmi.wake(True,
155 reply_handler=self.quitter_handler,
156 error_handler=self.quitter_handler)
157 else:
158 self.nmi.sleep(True,
159 reply_handler=self.quitter_handler,
160 error_handler=self.quitter_handler)
161 global LOOP
162 LOOP = True
164 def Dump0(self):
165 print "State:", self.NM_STATE[self.nmi.state()]
166 we = self.nmi.getWirelessEnabled()
167 if isinstance(we, tuple):
168 print "Wifi enabled:", bool(we[0])
169 print "Wifi HW enabled:", bool(we[1])
170 else:
171 print "Wifi enabled:", bool(we)
173 try:
174 dup = self.nmi.getDialup()
175 print "Dialup:", dup
176 except dbus.exceptions.DBusException, e:
177 #if e.get_dbus_name() == "org.freedesktop.NetworkManager.NoDialup":
178 # pass
179 #else:
180 print e
182 def Devices(self):
183 opaths = self.nmi.getDevices()
184 return map(cDevice_06, opaths)
186 def ActiveConnections(self):
187 return [] # at most one active connection, FIXME find it
189 def ActivateConnection(self, conn, device, ap):
190 # passing *_handler makes the call asynchronous
191 self.nmi.setActiveDevice(device.opath, ssid_str(conn.Ssid()),
192 reply_handler=self.silent_handler,
193 error_handler=self.err_handler,
196 class cNM_07(cNM):
197 def Api(self):
198 return "07"
200 def SetWifiEnabled(self, v):
201 self.nmpi.Set(NMI, "WirelessEnabled", v)
203 def SetOnline(self, v):
204 self.nmi.Sleep(not v)
206 def Dump0(self):
207 print "State:", self.NM_STATE[self.nmpi.Get(NMI, "State")]
208 print "Wifi enabled:", self.nmpi.Get(NMI, "WirelessEnabled")
209 print "Wifi HW enabled:", self.nmpi.Get(NMI, "WirelessHardwareEnabled")
211 def Devices(self):
212 opaths = self.nmi.GetDevices()
213 return map(cDevice_07, opaths)
215 def ActiveConnections(self):
216 aconns = self.nmpi.Get(NMI, "ActiveConnections")
217 return map(cActiveConnection, aconns)
219 def ActivateConnection(self, conn, device, ap):
220 # passing *_handler makes the call asynchronous
221 self.nmi.ActivateConnection(USC,
222 conn.__dbus_object_path__,
223 device.opath,
224 ap.opath,
225 reply_handler=self.silent_handler,
226 error_handler=self.err_handler,
230 class cActiveConnection:
231 def __init__(self, opath):
232 self.opath = opath
234 def Dump(self):
235 print self.opath
236 co = bus.get_object(NMC, self.opath)
237 copi = dbus.Interface(co, PI)
238 for P in ["ServiceName", "Connection", "SpecificObject",]:
239 print " %s: %s" % (P, copi.Get(NMI, P))
240 devs = copi.Get(NMI, "Devices")
241 print " Devices:"
242 for dev in devs:
243 print " ", dev
245 def bitmask_str(map, value):
246 ret = []
247 for mask in sorted(map.keys()):
248 if value & mask: ret.append(map[mask])
249 return ",".join(ret)
252 class cDevice:
253 def __init__(self, opath):
254 self.opath = opath
255 self.devo = bus.get_object(NMC, self.opath)
256 self.devi = dbus.Interface(self.devo, NMI + ".Device")
257 self.devpi = dbus.Interface(self.devo, PI)
258 self.dt = None
259 self.DeviceType0()
261 DEVICE_TYPE = ["UNKNOWN", "802_3_ETHERNET", "802_11_WIRELESS",
262 "GSM", "CDMA",] #OLPC: 3 is MESH
264 def DeviceType(self):
265 return self.DEVICE_TYPE[self.DeviceType0()]
267 def ip_str(self, i32):
268 ret = []
269 ret.append("%d" % (i32 % 256))
270 i32 /= 256
271 ret.append("%d" % (i32 % 256))
272 i32 /= 256
273 ret.append("%d" % (i32 % 256))
274 i32 /= 256
275 ret.append("%d" % (i32 % 256))
276 i32 /= 256
277 return ".".join(ret)
279 def DumpIp4Config(self, opath):
280 print " Ip4Config:", opath
281 o = bus.get_object(NMC, opath)
282 pi = dbus.Interface(o, PI)
283 try:
284 for P in ["Address", "Netmask", "Broadcast", "Gateway",]: # beta2?
285 print " %s: %s" % (P, self.ip_str(pi.Get(NMI, P)))
286 except:
287 print " Addresses:"
288 addrs = pi.Get(NMI, "Addresses")
289 for addr in addrs:
290 print " %s/%s via %s" % tuple(map(self.ip_str, addr))
291 nss = pi.Get(NMI, "Nameservers")
292 print " Nameservers:", " ".join(map(self.ip_str, nss))
293 doms = pi.Get(NMI, "Domains")
294 print " Domains:", " ".join(doms)
296 NM_DEVICE_CAP = {1: "NM_SUPPORTED", 2: "CARRIER_DETECT", 4: "SCANNING", }
299 def Dump(self):
300 print "Device:", self.opath
303 IW_MODE = ["AUTO", "ADHOC", "INFRA", "MASTER",
304 "REPEAT", "SECOND", "MONITOR",]
306 def APs(self):
307 return []
309 def ListNets(self):
310 for ap in self.APs():
311 ap.ListNets()
313 # mixin
314 class cDeviceEth:
315 pass
317 class cDevice_06(cDevice):
318 def DeviceType0(self):
319 if self.dt is None:
320 self.dt = self.devi.getProperties()[2]
321 if self.dt == 1:
322 self.__class__ = cDeviceEth_06
323 elif self.dt == 2:
324 self.__class__ = cDeviceWifi_06
325 return self.dt
327 NM_ACT_STAGE = [
328 "UNKNOWN", "DEVICE_PREPARE", "DEVICE_CONFIG", "NEED_USER_KEY",
329 "IP_CONFIG_START", "IP_CONFIG_GET", "IP_CONFIG_COMMIT",
330 "ACTIVATED", "FAILED", "CANCELLED", ]
332 def Dump(self):
333 cDevice.Dump(self)
334 print " Driver:", self.devi.getDriver()
335 props = self.devi.getProperties() # osusb ussss sssii biuus as
336 print " Self:", props[0] # o
337 print " Interface:", props[1] # s
338 print " Type:", self.DEVICE_TYPE[props[2]] # u
339 print " UDI:", props[3] # s
340 print " Active:", bool(props[4]) # b
341 print " Activation Stage:", self.NM_ACT_STAGE[props[5]] # u
342 print " IP:", props[6] # s
343 print " Mask:", props[7] # s
344 print " Bcast:", props[8] # s
345 print " HwAddress:", props[9] # s
346 print " GW:", props[10] # s
347 print " NS1:", props[11] # s
348 print " NS2:", props[12] # s
349 self.DumpMore()
351 def DumpMore(self):
352 print " (unknown device type, not dumping more)"
354 class cDeviceEth_06(cDevice_06, cDeviceEth):
355 def DumpMore(self):
356 props = self.devi.getProperties() # osusb ussss sssii biuus as
357 print " Link Active:", bool(props[15]) # b
358 print " Speed:", props[16] # i
359 print " Generic Capabilities:", bitmask_str(self.NM_DEVICE_CAP, props[17]) # u
361 class cDeviceWifi_06(cDevice_06):
362 NM_802_11_CAP = {
363 0x00000001: "PROTO_NONE",
364 0x00000002: "PROTO_WEP",
365 0x00000004: "PROTO_WPA",
366 0x00000008: "PROTO_WPA2",
367 0x00000010: "RESERVED1",
368 0x00000020: "RESERVED2",
369 0x00000040: "KEY_MGMT_PSK",
370 0x00000080: "KEY_MGMT_802_1X",
371 0x00000100: "RESERVED3",
372 0x00000200: "RESERVED4",
373 0x00000400: "RESERVED5",
374 0x00000800: "RESERVED6",
375 0x00001000: "CIPHER_WEP40",
376 0x00002000: "CIPHER_WEP104",
377 0x00004000: "CIPHER_TKIP",
378 0x00008000: "CIPHER_CCMP",
381 def APs(self):
382 self.wdevi = dbus.Interface(self.devo, NMI + ".Device.Wireless")
383 aps = self.devi.getProperties()[20]
384 return map(cAP_06, aps)
386 def DumpMore(self):
387 props = self.devi.getProperties() # osusb ussss sssii biuus as
388 print " Mode:", self.IW_MODE[props[13]] # i
389 print " Strength:", props[14] # i
390 print " Link Active:", bool(props[15]) # b
391 print " Speed:", props[16] # i
392 print " Generic Capabilities:", bitmask_str(self.NM_DEVICE_CAP, props[17]) # u
393 print " Capabilities:", bitmask_str(self.NM_802_11_CAP, props[18]) # u
394 print " Current net:", props[19] # s
395 nets = props[20] # as
396 print " Seen nets:", " ".join(nets)
397 if options.ap:
398 print " Access Points"
399 for ap in self.APs():
400 ap.Dump()
402 class cDevice_07(cDevice):
403 def DeviceType0(self):
404 if self.dt is None:
405 self.dt = self.devpi.Get(NMI, "DeviceType")
406 if self.dt == 1:
407 self.__class__ = cDeviceEth_07
408 elif self.dt == 2:
409 self.__class__ = cDeviceWifi_07
410 return self.dt
412 NM_DEVICE_STATE = [
413 "UNKNOWN", "UNMANAGED", "UNAVAILABLE", "DISCONNECTED", "PREPARE",
414 "CONFIG", "NEED_AUTH", "IP_CONFIG", "ACTIVATED", "FAILED",]
416 def Dump(self):
417 cDevice.Dump(self)
419 # "Ip4Config", only for NM_DEVICE_STATE_ACTIVATED
420 for P in ["Udi", "Interface", "Driver",]:
421 print " %s: %s" % (P, self.devpi.Get(NMI, P))
422 addr = self.devpi.Get(NMI, "Ip4Address")
423 print " Ip4Address:", self.ip_str(addr)
424 caps = self.devpi.Get(NMI, "Capabilities")
425 print " Capabilities:", bitmask_str(self.NM_DEVICE_CAP, caps)
426 state = self.NM_DEVICE_STATE[self.devpi.Get(NMI, "State")]
427 print " Dev State:", state
428 if state == "ACTIVATED":
429 self.DumpIp4Config(self.devpi.Get(NMI, "Ip4Config"))
431 dt = self.DeviceType()
432 print " Dev Type:", dt
433 self.DumpMore()
435 class cDeviceEth_07(cDevice_07, cDeviceEth):
436 def DumpMore(self):
437 for P in ["HwAddress", "Speed", "Carrier"]:
438 print " %s: %s" % (P, self.devpi.Get(NMI, P))
440 class cDeviceWifi_07(cDevice_07):
441 NM_802_11_DEVICE_CAP = {1:"CIPHER_WEP40", 2:"CIPHER_WEP104",
442 4:"CIPHER_TKIP", 8:"CIPHER_CCMP",
443 16:"WPA", 32:"RSN",}
445 def APs(self):
446 self.wdevi = dbus.Interface(self.devo, NMI + ".Device.Wireless")
447 aps = self.wdevi.GetAccessPoints()
448 return map(cAP_07, aps)
450 def DumpMore(self):
451 print " Dev Mode:", self.IW_MODE[self.devpi.Get(NMI, "Mode")]
452 wcaps = self.devpi.Get(NMI, "WirelessCapabilities")
453 print " Wifi Capabilities:", bitmask_str(self.NM_802_11_DEVICE_CAP, wcaps)
454 for P in ["HwAddress", "Bitrate", "ActiveAccessPoint"]:
455 print " %s: %s" % (P, self.devpi.Get(NMI, P))
456 if options.ap:
457 print " Access Points"
458 for ap in self.APs():
459 ap.Dump()
461 """An AP found around us"""
462 class cAP:
463 def __init__(self, opath):
464 self.opath = opath
465 self.apo = bus.get_object(NMC, self.opath)
466 self.appi = dbus.Interface(self.apo, PI)
467 # for _06
468 self.devi = dbus.Interface(self.apo, NMI + ".Devices")
470 NM_802_11_AP_FLAGS = {1: "PRIVACY",}
472 NM_802_11_AP_SEC = {
473 1: "PAIR_WEP40", 2: "PAIR_WEP104", 4: "PAIR_TKIP", 8: "PAIR_CCMP",
474 16: "GROUP_WEP40", 32: "GROUP_WEP104", 64: "GROUP_TKIP",
475 128: "GROUP_CCMP", 256: "KEY_MGMT_PSK", 512: "KEY_MGMT_802_1X",}
477 def ListNets(self, marker = " "):
478 # TODO *mark current
479 mbr = self.Mbr() / 1024 # 07 1000, 06 1024?
480 priv_s = self.PrivS()
481 print "%s%3d: %s (%dMb%s)" % (marker, self.Strength(), self.Ssid(), mbr, priv_s)
483 class cAP_06(cAP):
484 def Mbr(self, props=None):
485 if props is None:
486 props = self.devi.getProperties()
487 return props[5]
490 def PrivS(self):
491 props = self.devi.getProperties()
492 caps_s = bitmask_str(cDeviceWifi_06.NM_802_11_CAP, props[7]) + ","
493 priv_s = ""
494 if caps_s.find("PROTO_WEP,") != -1:
495 priv_s += " WEP"
496 if caps_s.find("PROTO_WPA,") != -1:
497 priv_s += " WPA"
498 if caps_s.find("PROTO_WPA2,") != -1:
499 priv_s += " WPA2"
500 if caps_s.find("KEY_MGMT_802_1X,") != -1:
501 priv_s += " Enterprise"
502 return priv_s
504 def Strength(self, props=None):
505 if props is None:
506 props = self.devi.getProperties()
507 return props[3]
509 def Ssid(self, props=None):
510 if props is None:
511 props = self.devi.getProperties()
512 return props[1]
515 def Dump(self):
516 props = self.devi.getProperties() # ossid iiib
517 print " Self:", props[0]
518 print " Ssid:", self.Ssid(props)
519 print " HwAddress:", props[2]
520 print " Strength:", self.Strength(props)
521 print " Frequency:", props[4]
522 print " MaxBitrate:", self.Mbr(props)
523 print " AP Mode:", cDevice.IW_MODE[props[6]]
524 print " Capabilities:", bitmask_str(cDeviceWifi_06.NM_802_11_CAP, props[7])
525 print " Broadcast:", props[8]
527 def ssid_str(array):
528 s = ""
529 for b in array:
530 s = s + ("%c" % b)
531 return s
533 def opath_validchar(c):
534 # _ is also escaped even though it is valid
535 return \
536 string.ascii_letters.find(c) != -1 or \
537 string.digits.find(c) != -1
539 def opath_escape(s):
540 r = ""
541 for c in s:
542 # TODO find a more elegant way
543 if not opath_validchar(c):
544 # "-" -> "_2d_"
545 c = "_%2x_" % ord(c)
546 r = r + c
547 return r
549 def opath_unescape(s):
550 # "2d" -> "-"
551 unhex = lambda xx: chr(eval("0x"+xx))
552 # all "_2d_" -> "-"
553 return re.sub("_.._", lambda p: unhex(p.group()[1:3]), s)
555 class cAP_07(cAP):
556 def Mbr(self):
557 return self.appi.Get(NMI, "MaxBitrate")
559 def PrivS(self):
560 priv = self.appi.Get(NMI, "Flags") != 0
561 wpa = self.appi.Get(NMI, "WpaFlags") != 0
562 wpa2 = self.appi.Get(NMI, "RsnFlags") != 0
563 priv_s = ""
564 if priv:
565 if not wpa and not wpa2:
566 priv_s = priv_s + " WEP"
567 if wpa:
568 priv_s = priv_s + " WPA"
569 if wpa2:
570 priv_s = priv_s + " WPA2"
571 return priv_s
573 def Strength(self):
574 return int(self.appi.Get(NMI, "Strength"))
576 def Ssid(self):
577 return ssid_str(self.appi.Get(NMI, "Ssid"))
579 def Dump(self):
580 print " AP:", self.opath
581 print " Ssid:", self.Ssid()
582 for P in ["Frequency", "HwAddress", "MaxBitrate",]:
583 print " %s: %s" % (P, self.appi.Get(NMI, P))
584 print " Strength:", self.Strength()
585 print " AP Mode:", cDevice.IW_MODE[self.appi.Get(NMI, "Mode")]
586 print " AP Flags:", bitmask_str(self.NM_802_11_AP_FLAGS,
587 self.appi.Get(NMI, "Flags"))
588 print " AP WPA Flags:", bitmask_str(self.NM_802_11_AP_SEC,
589 self.appi.Get(NMI, "WpaFlags"))
590 print " AP RSN Flags:", bitmask_str(self.NM_802_11_AP_SEC,
591 self.appi.Get(NMI, "RsnFlags"))
593 # this is the client side of the applet; see also UserSettings
594 class cApplet:
595 def __init__(self, svc, opath):
596 self.svc = svc
597 self.opath = opath
598 self.so = bus.get_object(self.svc, self.opath)
599 self.si = dbus.Interface(self.so, 'org.freedesktop.NetworkManagerSettings')
601 def isSystem(self):
602 return self.svc == SSC;
604 def Dump(self):
605 for conn in self.Connections():
606 conn.Dump()
607 if self.isSystem():
608 self.DumpSystem()
610 def DumpSystem(self):
611 sspi = dbus.Interface(self.so, PI)
612 print "Unmanaged Devices"
613 umds = sspi.Get(NMI, "UnmanagedDevices")
614 for umd in umds:
615 print " ", umd
616 # dump_settings_conn(svc, conn) umd?
619 def myConnection(self, opath):
620 return cConnection(self.svc, opath)
622 def Connections(self):
623 opaths = self.si.ListConnections()
624 return map(self.myConnection, opaths)
626 NETWORK_TYPE_ALLOWED = 1
627 class cApplet_06(cApplet):
628 def __init__(self, svc, opath):
629 self.svc = svc
630 self.opath = opath
631 self.io = bus.get_object(self.svc, self.opath)
632 self.ii = dbus.Interface(self.io, 'org.freedesktop.NetworkManagerInfo')
634 def isSystem(self):
635 return False;
637 def myConnection(self, opath):
638 return cConnection_06(self, opath)
640 # TODO also VPN conns
641 def Connections(self):
642 names = self.ii.getNetworks(NETWORK_TYPE_ALLOWED)
643 return map(self.myConnection, names)
645 class cConnection:
646 def __init__(self, svc, opath):
647 self.svc = svc
648 self.opath = opath
649 self.co = bus.get_object(self.svc, self.opath)
650 self.ci = dbus.Interface(self.co, 'org.freedesktop.NetworkManagerSettings.Connection')
652 def Dump(self):
653 print "Conn:", self.opath
654 settings = self.Settings()
655 settings.Dump()
657 si = dbus.Interface(self.co, 'org.freedesktop.NetworkManagerSettings.Connection.Secrets')
658 security = settings.Security()
659 if security != "":
660 print " SECRETS:", security
661 try:
662 # TODO merge them
663 secrets = cSettings(si.GetSecrets(security,[],False))
664 secrets.Dump()
665 except dbus.exceptions.DBusException, e:
666 if e.get_dbus_name() == "org.freedesktop.DBus.Error.AccessDenied":
667 print " Access denied"
668 else:
669 print " ", e
670 print " FIXME figure out 802-1x secrets"
672 def Settings(self):
673 return cSettings(self.ci.GetSettings())
675 def dump_time(unixtime):
676 return time.asctime(time.localtime(unixtime))
678 class cConnection_06:
679 def __init__(self, applet, id):
680 self.id = id
681 self.applet = applet
683 def Dump(self):
684 print "Conn:", self.id
686 np = self.applet.ii.getNetworkProperties(self.id, NETWORK_TYPE_ALLOWED)
687 ssid = np[0]
688 print " ssid:", ssid
689 print " time:", dump_time(np[1])
690 print " trusted:", bool(np[2])
691 print " bssids:", ", ".join(np[3])
692 enctype = np[4]
693 print " we_cipher:", enctype
694 if enctype != 1:
695 print " secret:", np[5]
696 if enctype == 16:
697 print " wep_auth_algorithm:", np[6]
698 elif enctype == 0:
699 print " wpa_psk_key_mgt:", np[6]
700 print " wpa_psk_wpa_version:", np[7]
702 return # nm-applet will not tell kfn anyway
703 devp = "/org/freedesktop/NetworkManager/Devices/ath0" #FIXME
704 netp = devp + "/Networks/" + opath_escape(self.id)
705 attempt = 1
706 newkey = False
707 kfn = self.applet.ii.getKeyForNetwork(devp, netp, ssid, attempt, newkey)
708 print " kfn:", kfn
711 # 06
712 NM_AUTH_TYPE_WPA_PSK_AUTO = 0x00000000
713 NM_AUTH_TYPE_NONE = 0x00000001
714 NM_AUTH_TYPE_WEP40 = 0x00000002
715 NM_AUTH_TYPE_WPA_PSK_TKIP = 0x00000004
716 NM_AUTH_TYPE_WPA_PSK_CCMP = 0x00000008
717 NM_AUTH_TYPE_WEP104 = 0x00000010
718 NM_AUTH_TYPE_WPA_EAP = 0x00000020
719 NM_AUTH_TYPE_LEAP = 0x00000040
721 IW_AUTH_ALG_OPEN_SYSTEM = 0x00000001
722 IW_AUTH_ALG_SHARED_KEY = 0x00000002
723 IW_AUTH_ALG_LEAP = 0x00000004
725 class cSettings:
726 def __init__(self, conmap):
727 #print "INIT", conmap
728 self.conmap = conmap
730 def Type(self):
731 return self.conmap["connection"]["type"]
733 def ID(self):
734 return self.conmap["connection"]["id"]
736 def Ssid(self):
737 try:
738 return self.conmap["802-11-wireless"]["ssid"]
739 except KeyError:
740 pass
741 # probably 802-3-ethernet
742 return ""
744 def Timestamp(self):
745 try:
746 return self.conmap["connection"]["timestamp"]
747 except KeyError:
748 return 0
750 def Trusted(self):
751 # false by default
752 return False
754 def SeenBssids(self):
755 try:
756 return self.conmap["802-11-wireless"]["seen-bssids"]
757 except KeyError:
758 return []
760 # for 06
761 def WeCipher(self):
762 k = self.Key()
763 if len(k) == 26:
764 return NM_AUTH_TYPE_WEP104
765 elif len(k) == 64:
766 return NM_AUTH_TYPE_WPA_PSK_AUTO
767 elif len(k) == 0:
768 return NM_AUTH_TYPE_NONE
769 print "Defaulting cipher type to none"
770 return NM_AUTH_TYPE_NONE
772 def Key(self):
773 try:
774 return self.conmap["802-11-wireless-security"]["psk"]
775 except KeyError:
776 pass
777 try:
778 return self.conmap["802-11-wireless-security"]["wep-key0"]
779 except KeyError:
780 pass
781 # no key
782 return ""
784 def WepAuthAlgorithm(self):
785 print "FIXME Defaulting WEP auth alg to open"
786 return IW_AUTH_ALG_OPEN_SYSTEM
788 def PskKeyMgt(self):
789 print "FIXME Defaulting PSK key mgmt to 2"
790 return 2
792 def PskWpaVersion(self):
793 print "FIXME Defaulting WPA version to 2"
794 return 2
796 def Security(self):
797 try:
798 return self.conmap[self.Type()]["security"]
799 except KeyError:
800 return ""
802 def isNet(self, net_name):
803 return self.ID() == net_name or self.Ssid() == net_name
805 # FIXME check spec/NM what to censor
806 secrets = dict.fromkeys(["wep-key0", "psk"])
808 def ConMap(self):
809 "For GetSettings: censor secrets."
811 cm = dict()
812 for n1, v1 in self.conmap.iteritems():
813 cm[n1] = dict()
814 for n2, v2 in v1.iteritems():
815 cv2 = v2
816 if self.secrets.has_key(n2):
817 cv2 = ""
818 cm[n1][n2] = cv2
819 return cm
821 def SecMap(self):
822 "For GetSecrets: only secrets."
823 s = self.Security()
824 r = {
825 s: self.conmap[s]
827 print "SECMAP", r
828 return r
830 def Dump(self):
831 for n1, v1 in self.conmap.iteritems():
832 print " ",n1
833 for n2, v2 in v1.iteritems():
834 print " %s: %s" % (n2, v2)
836 def mkconmap_wifi(ssid):
837 return {
838 'connection': {
839 'id': '_cnm_handcrafted_',
840 'uuid': str(uuid.uuid1()), # new in oS 11.1
841 'type': '802-11-wireless',
843 '802-11-wireless': {
844 'ssid': dbus.ByteArray(ssid),
845 'mode': 'infrastructure',
849 def elongate(s, tlen):
850 "repeat string s to target length tlen"
851 if s == "":
852 return ""
853 copies_needed = int(math.ceil(tlen / float(len(s))))
854 return (s * copies_needed)[:tlen]
856 # http://www.mail-archive.com/networkmanager-list@gnome.org/msg07935.html
857 def wep_passphrase_to_hash(p):
858 return hashlib.md5(elongate(p, 64)).hexdigest()
860 def mkconmap_wep_pass(ssid, key):
861 cm = mkconmap_wifi(ssid)
862 cm["802-11-wireless"]["security"] = "802-11-wireless-security"
863 cm["802-11-wireless-security"] = {}
864 cm["802-11-wireless-security"]["key-mgmt"] = "none"
865 cm["802-11-wireless-security"]["wep-tx-keyidx"] = 0
866 cm["802-11-wireless-security"]["wep-key0"] = wep_passphrase_to_hash(key)
867 return cm
869 def mkconmap_wep(ssid, key):
870 cm = mkconmap_wifi(ssid)
871 cm["802-11-wireless"]["security"] = "802-11-wireless-security"
872 cm["802-11-wireless-security"] = {}
873 cm["802-11-wireless-security"]["key-mgmt"] = "none"
874 cm["802-11-wireless-security"]["wep-tx-keyidx"] = 0
875 cm["802-11-wireless-security"]["wep-key0"] = key
876 return cm
878 def mkconmap_psk(ssid, key):
879 cm = mkconmap_wifi(ssid)
880 cm["802-11-wireless"]["security"] = "802-11-wireless-security"
881 cm["802-11-wireless-security"] = {}
882 cm["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"
883 cm["802-11-wireless-security"]["psk"] = key
884 cm["802-11-wireless-security"]["group"] = ["tkip", "ccmp"]
885 cm["802-11-wireless-security"]["pairwise"] = ["tkip", "ccmp"]
886 return cm
889 # server analog of cApplet
890 class UserSettings(dbus.service.Object):
891 # conmaps is a list
892 def __init__(self, opath, conmaps):
893 dbus.service.Object.__init__(self, bus, opath)
894 #print "CONMAPS:", conmaps
895 self.conns = map(self.newCon, conmaps)
897 def addCon(self, conmap):
898 c = self.newCon(conmap)
899 self.conns.append(c)
900 return c
902 counter = 1
903 def newCon(self, conmap):
904 cpath = "/MyConnection/%d" % self.counter
905 self.counter = self.counter + 1
906 c = Connection(cpath, conmap)
907 self.NewConnection(cpath) # announce it
908 return c
910 @dbus.service.method(dbus_interface='org.freedesktop.NetworkManagerSettings',
911 in_signature='', out_signature='ao')
912 def ListConnections(self):
913 return [c.__dbus_object_path__ for c in self.conns]
915 #this is for EMITTING a signal, not receiving it
916 @dbus.service.signal(dbus_interface='org.freedesktop.NetworkManagerSettings',
917 signature='o')
918 def NewConnection(self, opath):
919 pass
920 #print "signalling newconn:", opath
922 def GetByNet(self, net_name):
923 "Returns connection, or None"
924 for c in self.conns:
925 if c.isNet(net_name):
926 return c
927 return None
930 class UserSettings_06(UserSettings):
931 # conmaps is a list
932 def __init__(self, opath, conmaps):
933 dbus.service.Object.__init__(self, bus, opath)
934 #print "CONMAPS:", conmaps
935 self.conns = map(self.newCon, conmaps)
937 counter = 1
938 def newCon(self, conmap):
939 cpath = "/MyConnection/%d" % self.counter
940 self.counter = self.counter + 1
941 c = Connection_06(cpath, conmap)
942 #self.NewConnection(cpath) # announce it
943 return c
945 @dbus.service.method(dbus_interface="org.freedesktop.NetworkManagerInfo",
946 in_signature="i", out_signature='as')
947 def getNetworks(self, i):
948 # FIXME bytearray to str WHERE?
949 #n = [ssid_str(c.Ssid()) for c in self.conns]
950 n = [c.ID() for c in self.conns]
951 print "getNetworks:", n
952 return n
954 @dbus.service.method(dbus_interface="org.freedesktop.NetworkManagerInfo",
955 in_signature="", out_signature='ao') # out??
956 def getVPNConnections(self):
957 return [] # FIXME
959 @dbus.service.method(dbus_interface="org.freedesktop.NetworkManagerInfo",
960 in_signature="si")
961 #out_signature='sibasi') #varies
962 def getNetworkProperties(self, net, type):
963 print "GNP", net
964 # type is 1, NETWORK_TYPE_ALLOWED
965 c = self.GetByNet(net)
966 if c != None:
967 return c.getNetworkProperties()
968 print "Oops, could not getNetworkProperties for " + net
971 @dbus.service.method(dbus_interface="org.freedesktop.NetworkManagerInfo",
972 in_signature="oosib")
973 #out_signature="isi") varies
974 def getKeyForNetwork(self, dev, net, ssid, attempt, newkey):
975 print "GKFN", dev, net, ssid, attempt, bool(newkey)
976 if newkey:
977 m = "Cannot ask for key"
978 print m
979 raise dbus.exceptions.DBusException(m)
981 snet = opath_unescape(net[net.rfind("/")+1 : ]) # only stuff after /
982 c = self.GetByNet(snet)
983 if c != None:
984 return c.getKeyForNetwork()
985 print "Oops, could not getKeyForNetwork " + net
987 @dbus.service.method(dbus_interface="org.freedesktop.NetworkManagerInfo",
988 out_signature='')
989 #in_signature="sbs isi", varies
990 def updateNetworkInfo(self, ssid, automatic, bssid, *security):
991 print "Connected successfully"
992 return
993 print "UNI"
994 print " ssid:", ssid
995 print " automatic:", bool(automatic)
996 print " bssid:", bssid
997 print " security:", security
1000 def GetByNet(self, net_name):
1001 "Returns connection, or None"
1002 for c in self.conns:
1003 if c.isNet(net_name):
1004 return c
1005 return None
1008 # server analog of cConnection
1009 class Connection(dbus.service.Object):
1010 def __init__(self, opath, conmap):
1011 dbus.service.Object.__init__(self, bus, opath)
1012 self.settings = cSettings(conmap)
1014 @dbus.service.method(dbus_interface='org.freedesktop.NetworkManagerSettings.Connection',
1015 sender_keyword='sender',
1016 in_signature='', out_signature='a{sa{sv}}')
1017 def GetSettings(self, sender):
1018 #print "Getting settings:", self. __dbus_object_path__
1019 # return self.settings.ConMap()
1020 # grr, censoring secrets makes NM complain!?
1021 # bnc#479566#c3: Until I figure out how to make it work with
1022 # censored secrets, only pass the settings to the same user.
1023 sender_uid = bus.get_unix_user(sender)
1024 if sender_uid != 0 and sender_uid != os.geteuid():
1025 e = "User %u is not permitted to read the settings" % sender_uid
1026 print e
1027 raise dbus.exceptions.DBusException(e) # could do NM_SETTINGS_ERROR_* instead
1028 return self.settings.conmap
1030 @dbus.service.method(dbus_interface='org.freedesktop.NetworkManagerSettings.Connection.Secrets',
1031 in_signature='sasb', out_signature='a{sa{sv}}')
1032 def GetSecrets(self, tag, hints, ask):
1033 # FIXME respect args
1034 print "Getting secrets:", self.__dbus_object_path__
1035 return self.settings.SecMap()
1037 @dbus.service.method(dbus_interface='org.freedesktop.NetworkManagerSettings.Connection',
1038 in_signature='', out_signature='s')
1039 def ID(self):
1040 return self.settings.ID()
1042 def Ssid(self):
1043 return self.settings.Ssid()
1045 def isNet(self, net_name):
1046 return self.settings.isNet(net_name)
1048 class Connection_06(Connection):
1049 def __init__(self, opath, conmap):
1050 dbus.service.Object.__init__(self, bus, opath)
1051 #print "C6", conmap
1052 self.settings = cSettings(conmap)
1054 # dbus.service.method
1055 def getNetworkProperties(self):
1056 # essid, timestamp, ?, bssids, we_cipher, ?, ...
1057 # we_cipher=16: i wep_auth_algorithm
1058 # we_cipher=0: i wpa_psk_key_mgt, i wpa_psk_wpa_version
1059 ssid = ssid_str(self.settings.Ssid())
1060 time = self.settings.Timestamp() # last sucessfully connected? seen?
1061 trusted = self.settings.Trusted()
1062 bssids = dbus.Array(self.settings.SeenBssids(), signature="s")
1063 r = [ssid, time, trusted, bssids]
1064 security = self.getKeyForNetwork("fake key")
1065 r.extend(security)
1066 return tuple(r)
1068 # dbus.service.method
1069 def getKeyForNetwork(self, fake="no"):
1070 if fake == "no":
1071 key = self.settings.Key()
1072 else:
1073 key = ""
1075 # security
1076 cip = self.settings.WeCipher()
1077 if cip == NM_AUTH_TYPE_NONE:
1078 security = tuple([cip])
1079 elif cip == NM_AUTH_TYPE_WEP40 or cip == NM_AUTH_TYPE_WEP104:
1080 wep_auth_algorithm = self.settings.WepAuthAlgorithm()
1081 security = (cip, key, wep_auth_algorithm)
1082 elif cip == NM_AUTH_TYPE_WPA_PSK_AUTO or cip == NM_AUTH_TYPE_TKIP or \
1083 cip == NM_AUTH_TYPE_CCMP:
1084 wpa_psk_key_mgt = self.settings.PskKeyMgt()
1085 wpa_psk_wpa_version = self.settings.PskWpaVersion()
1086 security = (cip, key, wpa_psk_key_mgt, wpa_psk_wpa_version)
1087 elif cip == NM_AUTH_TYPE_WPA_EAP:
1088 security = tuple([cip]) # TODO more...
1089 elif cip == NM_AUTH_TYPE_LEAP:
1090 security = tuple([cip]) # TODO more...
1091 return security
1094 class ConfigParserKNM:
1095 "Parse ~/.kde/share/config/knetworkmanagerrc"
1097 def __init__(self):
1098 p = ConfigParser.RawConfigParser()
1099 ok = p.read(os.getenv("HOME") + "/.kde/share/config/knetworkmanagerrc")
1101 self.conmaps_d = {}
1102 for s in p.sections():
1103 path = s.split("_")
1104 #print "##", path
1105 if path[0] in ["ConnectionSetting", "ConnectionSecrets"]:
1106 cid = path[1]
1107 self.conmaps_d.setdefault(cid, {})
1108 part = path[2]
1110 values = {}
1111 for (n, v) in p.items(s):
1112 # WTF, Value_ is transformed to value_
1113 if n[:6] == "value_":
1114 n = n[6:]
1115 v = self.ParseValue(v)
1116 #print "# %s:%s" % (n, v)
1117 # do not overwrite ConnectionSecrets
1118 # with empty ConnectionSettings field
1119 try:
1120 vv = self.conmaps_d[cid][part][n]
1121 except KeyError:
1122 vv = ""
1123 if vv == "":
1124 values[n] = v
1125 if len(values) != 0: # empty 802-1x confuses NM!?
1126 self.conmaps_d[cid].setdefault(part, {})
1127 self.conmaps_d[cid][part].update(**values)
1128 #print "PARSED", cid, part, values
1130 def ConMaps(self):
1131 return self.conmaps_d.values()
1133 def ParseValue(self, v):
1134 v = eval('"%s"' % v) # unescape backslashes
1135 dom = xml.dom.minidom.parseString(v)
1136 return self.ParseNode(dom.documentElement)
1138 def ParseNode(self, n):
1139 t = n.localName
1140 if t != "list":
1141 v = self.NodeText(n)
1143 if t == "string":
1144 return v
1145 elif t == "byte":
1146 return dbus.Byte(int(v))
1147 elif t == "bool":
1148 return v == "true"
1149 elif t == "int32" or t == "uint32":
1150 return int(v)
1151 elif t == "list":
1152 v = []
1153 c = n.firstChild
1154 while c != None:
1155 if c.localName != None: # whitespace
1156 v.append(self.ParseNode(c))
1157 c = c.nextSibling
1158 return v
1160 def NodeText(self, n):
1161 if n.hasChildNodes():
1162 return n.firstChild.wholeText
1163 else:
1164 return ""
1166 class MonitorBase:
1167 def __init__(self):
1168 self.amap = {}
1169 self.specific = {}
1170 bus.add_signal_receiver(self.abbr_h,
1171 path_keyword="path",
1172 interface_keyword="interface",
1173 member_keyword="member")
1175 def ignore(self, dbus_interface, signal_name):
1176 self.watch(self.null_h, dbus_interface, signal_name)
1178 def null_h(self, *args, **kwargs):
1179 pass
1181 def watch(self, handler, dbus_interface, signal_name):
1182 self.specific[dbus_interface +"."+ signal_name] = True
1183 bus.add_signal_receiver(handler,
1184 dbus_interface=dbus_interface,
1185 signal_name=signal_name,
1186 path_keyword="path")
1188 def abbr_h(self, *args, **kwargs):
1189 ifc = kwargs["interface"]
1190 sig = kwargs["member"]
1191 if self.specific.has_key(ifc +"."+ sig):
1192 return
1194 opath = kwargs["path"]
1195 line = "SIG %s: %s.%s%s" % (self.abbrev(opath,"/"),
1196 self.abbrev(ifc,"."),
1197 sig, args)
1198 print line
1200 def abbrev(self, s, sep):
1201 words = s.split(sep)
1202 words = map (self.a1, words)
1203 result = sep.join(words)
1204 if self.amap.has_key(result):
1205 if self.amap[result] != s:
1206 print "ABBR COLLISION %s was %s now %s" % (result, self.amap[result], s)
1207 else:
1208 print "ABBR %s is %s" % (result, s)
1209 self.amap[result] = s
1210 return result
1212 def a1(self, s):
1213 if s == "":
1214 return ""
1215 #print "#A", s
1216 # first char, delete lowercase and _ from the rest
1217 return s[0] + s[1:].translate(string.maketrans("", ""),
1218 string.lowercase + "_")
1220 class Monitor(MonitorBase):
1221 def __init__(self):
1222 MonitorBase.__init__(self)
1224 self.watch(
1225 self.propc_h,
1226 dbus_interface="org.freedesktop.NetworkManager.Device.Wireless",
1227 signal_name="PropertiesChanged")
1228 self.watch(
1229 self.propc_h,
1230 dbus_interface="org.freedesktop.NetworkManager.AccessPoint",
1231 signal_name="PropertiesChanged")
1233 self.ignore("org.freedesktop.Hal.Device", "PropertyModified")
1234 self.ignore("fi.epitest.hostap.WPASupplicant.Interface", "ScanResultsAvailable")
1235 self.ignore("com.redhat.PrinterSpooler", "QueueChanged")
1236 self.ignore("org.freedesktop.NetworkManager", "StateChange") # deprecated
1237 self.watch(self.nm_sc_h, "org.freedesktop.NetworkManager", "StateChanged")
1238 self.watch(self.wpas_isc_h, "fi.epitest.hostap.WPASupplicant.Interface", "StateChange")
1239 self.watch(self.nmd_sc_h, "org.freedesktop.NetworkManager.Device", "StateChanged")
1240 self.watch(self.bus_noc_h, "org.freedesktop.DBus", "NameOwnerChanged")
1242 def bus_noc_h(self, *args, **kwargs):
1243 (name, old, new) = args
1244 if new == "":
1245 new = "gone"
1246 else:
1247 new = "at " + new
1248 print "\tBUS NOC\t%s %s" % (name, new)
1250 def wpas_isc_h(self, *args, **kwargs):
1251 opath = kwargs["path"]
1252 (new, old) = args
1253 print "\tWPAS %s\t(%s, was %s)" % (new, opath, old.lower())
1255 def nmd_sc_h(self, *args, **kwargs):
1256 opath = kwargs["path"]
1257 (new, old, reason) = args
1258 news = cDevice_07.NM_DEVICE_STATE[new]
1259 olds = cDevice_07.NM_DEVICE_STATE[old]
1260 reasons = ""
1261 if reason != 0:
1262 reasons = "reason %d" % reason
1263 print "\tDevice State %s\t(%s, was %s%s)" % (news, opath, olds.lower(), reasons)
1265 def nm_sc_h(self, *args, **kwargs):
1266 s = args[0]
1267 ss = cNM.NM_STATE[s]
1268 print "\tNM State:", ss
1270 def propc_h(self, *args, **kwargs):
1271 opath = kwargs["path"]
1272 props = args[0]
1273 for k, v in props.iteritems():
1274 if k == "Strength":
1275 v = "%u" % v
1276 line = "\tPROP\t%s\t%s\t(%s)" % (k, v, opath)
1277 print line
1280 # main
1282 op = OptionParser(version="%prog " + VERSION)
1283 op.add_option("-d", "--dev",
1284 action="store_true", default=False,
1285 help="list devices")
1286 op.add_option("-c", "--actcon",
1287 action="store_true", default=False,
1288 help="list active connections")
1289 op.add_option("-u", "--usrcon",
1290 action="store_true", default=False,
1291 help="list user connection settings (can CRASH nm-applet)")
1292 op.add_option("-s", "--syscon",
1293 action="store_true", default=False,
1294 help="list system connection settings")
1295 op.add_option("-a", "--ap",
1296 action="store_true", default=False,
1297 help="list found access points")
1298 op.add_option("-n", "--nets",
1299 action="store_true", default=False,
1300 help="list found wireless networks")
1301 # TODO http://docs.python.org/lib/optparse-adding-new-types.html
1302 op.add_option("-w", "--wifi",
1303 choices=["0","1","off","on","no","yes","false","true"],
1304 metavar="BOOL",
1305 help="enable or disable wireless")
1306 op.add_option("-o", "--online",
1307 choices=["0","1","off","on","no","yes","false","true"],
1308 metavar="BOOL",
1309 help="enable or disable network at all")
1311 op.add_option("-C", "--connect",
1312 help="connect to a wireless network NET (using knetworkmanagerrc or the key options below)",
1313 metavar="NET")
1314 op.add_option("--unprotected",
1315 action="store_true", default=False,
1316 help="network does not require a key")
1317 op.add_option("--wep-hex",
1318 metavar="KEY",
1319 help="use this WEP key of 26 hex digits")
1320 op.add_option("--wep-pass",
1321 metavar="KEY",
1322 help="use this WEP passphrase")
1323 op.add_option("--wpa-psk-hex",
1324 metavar="KEY",
1325 help="use this WPA key of 64 hex digits")
1326 op.add_option("--wpa-pass",
1327 metavar="KEY",
1328 help="use this WPA passphrase")
1329 op.add_option("-m", "--monitor",
1330 action="store_true", default=False,
1331 help="loop to show dbus signals")
1334 (options, args) = op.parse_args()
1336 if options.ap:
1337 options.dev = True
1338 if options.monitor:
1339 LOOP = True
1342 nmp = '/org/freedesktop/NetworkManager'
1343 try:
1344 nm = make_nm(nmp)
1345 except dbus.exceptions.DBusException, e:
1346 print e
1347 print "NetworkManager is not running"
1348 sys.exit(1)
1349 if options.dev or options.actcon:
1350 nm.Dump()
1352 true_choices = ["1", "on", "yes", "true"]
1353 if options.wifi != None:
1354 nm.SetWifiEnabled(options.wifi in true_choices)
1355 if options.online != None:
1356 nm.SetOnline(options.online in true_choices)
1358 if options.nets:
1359 nm.ListNets()
1361 if options.syscon:
1362 print "SYSTEM Connections"
1363 if nm.Api() == "06":
1364 print "Cannot do that with NM 0.6"
1365 else:
1366 ss = cApplet(SSC, '/org/freedesktop/NetworkManagerSettings')
1367 ss.Dump()
1369 if options.usrcon:
1370 print "USER Connections"
1371 try:
1372 if nm.Api() == "06":
1373 us = cApplet_06(NMIC, "/org/freedesktop/NetworkManagerInfo")
1374 else:
1375 us = cApplet(USC, '/org/freedesktop/NetworkManagerSettings')
1376 us.Dump()
1377 except dbus.exceptions.DBusException, e:
1378 print e
1379 #if e.get_dbus_name() == "org.freedesktop.DBus.Error.ServiceUnknown":
1380 print "Applet is not running"
1382 nmo = bus.get_object(NMC, nmp)
1383 nmi = dbus.Interface(nmo, NMI)
1385 def service_pid(name):
1386 DBS = 'org.freedesktop.DBus'
1387 DBI = DBS
1388 dbo = bus.get_object(DBS, '/')
1389 dbi = dbus.Interface(dbo, DBI)
1390 owner = dbi.GetNameOwner(name)
1391 pid = dbi.GetConnectionUnixProcessID(owner)
1392 return pid
1394 # TODO UserSettings_06
1395 if options.connect != None:
1396 if nm.Api() == "06":
1397 name = NMIC
1398 else:
1399 name = USC
1400 brn = bus.request_name(name, _dbus_bindings.NAME_FLAG_DO_NOT_QUEUE)
1401 if brn == _dbus_bindings.REQUEST_NAME_REPLY_EXISTS:
1402 print "Could not provide settings service, another applet is running (pid %s)" % service_pid(name)
1403 sys.exit(1)
1404 cfg = ConfigParserKNM()
1405 if nm.Api() == "06":
1406 us = UserSettings_06("/org/freedesktop/NetworkManagerInfo",
1407 cfg.ConMaps())
1408 else:
1409 us = UserSettings("/org/freedesktop/NetworkManagerSettings",
1410 cfg.ConMaps())
1412 def Connect(wanted_net): # any. or take arg. net is config name or ssid name
1413 # ... in general, look for string in all config data. ssid for wifi, whatever for dialup
1414 # TODO also respect autoconnect
1416 # ActivateConn wants setting device ap; can find device from ap? ap is "specific" for wifi devices
1417 #print "Connection wanted to", wanted_net
1418 found_con = found_ap = found_dev = None
1419 for dev in nm.Devices():
1420 for ap in dev.APs():
1421 if wanted_net == ap.Ssid():
1422 found_ap = ap
1423 found_dev = dev
1424 break # FIXME both loops
1425 found_con = us.GetByNet(wanted_net)
1426 if found_ap == None:
1427 print "No AP found with SSID", wanted_net
1428 return False
1429 if found_con == None:
1430 print "No settings for net %s, assuming no key is needed" % wanted_net
1431 c = mkconmap_wifi(wanted_net)
1432 found_con = us.addCon(c)
1433 nm.ActivateConnection(found_con, found_dev, found_ap) # TODO async
1434 # TODO run loop, exit it when we have serviced the required calls
1435 return True
1437 if options.connect != None:
1438 if options.unprotected:
1439 c = mkconmap_wifi(options.connect)
1440 us.addCon(c)
1441 if options.wep_hex != None:
1442 c = mkconmap_wep(options.connect, options.wep_hex)
1443 us.addCon(c)
1444 if options.wep_pass != None:
1445 c = mkconmap_wep_pass(options.connect, options.wep_pass)
1446 us.addCon(c)
1447 if options.wpa_psk_hex != None:
1448 c = mkconmap_psk(options.connect, options.wpa_psk_hex)
1449 us.addCon(c)
1450 if options.wpa_pass != None:
1451 wpa_psk_hex = hexlify(pbkdf2.pbkdf2(options.wpa_pass, options.connect, 4096, 32))
1452 print "pbkdf2", wpa_psk_hex
1453 c = mkconmap_psk(options.connect, wpa_psk_hex)
1454 us.addCon(c)
1455 nm.WatchState()
1456 if Connect(options.connect):
1457 LOOP = True
1459 if options.monitor:
1460 m = Monitor()
1462 def loop():
1463 loop = gobject.MainLoop()
1464 try:
1465 loop.run()
1466 except:
1467 print "Loop exited"
1469 if LOOP:
1470 loop()