knetworkmanagerrc sections: whitelisting works better
[cnetworkmanager.git] / cnetworkmanager
blob7ebac871a88ae819470ab345a70fbb6390b2b249
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.5.1"
7 print "cnetworkmanager %s - Command Line Interface for NetworkManager" % VERSION
9 norpm = False
10 import sys
11 import os
12 import ConfigParser # knm config
13 from optparse import OptionParser
14 try:
15 import dbus
16 import dbus.service
17 import _dbus_bindings
18 except:
19 print "Install python-1-dbus.rpm or python-dbus.deb"
20 norpm = True
21 import xml.dom.minidom
22 try:
23 import gobject
24 except:
25 # todo - only if loop wanted
26 print "Install python-gobject2.rpm or python-gobject.deb"
27 norpm = True
28 # python-gnome.rpm has gconf for nm-applet...
29 if norpm:
30 sys.exit(1)
32 from dbus.mainloop.glib import DBusGMainLoop
33 DBusGMainLoop(set_as_default=True)
35 LOOP = False
37 bus = dbus.SystemBus()
39 # FOOC = connection (service) string
40 # FOOI = interface string
41 # fooo = object
42 # fooi = interface
43 # foopi = property interface
44 NMC = 'org.freedesktop.NetworkManager'
45 NMI = NMC
46 PI = 'org.freedesktop.DBus.Properties'
47 SSC = "org.freedesktop.NetworkManagerSystemSettings"
48 USC = "org.freedesktop.NetworkManagerUserSettings"
50 def introspect(obj):
51 ii = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable')
52 print ii.Introspect()
54 class cNM:
55 # TODO: pull them from introspection.xml
56 NM_STATE = ["UNKNOWN", "ASLEEP", "CONNECTING", "CONNECTED", "DISCONNECTED",]
58 def __init__(self, opath):
59 self.opath = opath
60 self.nmo = bus.get_object(NMC, self.opath)
61 self.nmi = dbus.Interface(self.nmo, NMI)
62 self.nmpi = dbus.Interface(self.nmo, PI)
64 def Dump0(self):
65 "Dumps its own info (not owned objects)."
66 pass
68 def Dump(self):
69 self.Dump0()
70 if options.dev:
71 for device in self.Devices():
72 device.Dump()
74 if options.actcon:
75 print "Active Connections"
76 aconns = self.ActiveConnections()
77 for aconn in aconns:
78 aconn.Dump()
80 def ListNets(self):
81 print "Wifi Networks:"
82 for dev in self.Devices():
83 dev.ListNets()
85 def reply_handler(self, opath):
86 print "Connected:", opath
88 def err_handler(self, *args):
89 print "ERR:", args
91 def silent_handler(self, *args):
92 pass
93 print "BOO!:", args
95 def quitter_handler(self, *args):
96 # exit the loop that runs only because of us
97 print "padla"
98 sys.exit(0)
100 def ActivateConnection(self, conn, device, ap):
101 # passing *_handler makes the call asynchronous
102 self.nmi.ActivateConnection(USC,
103 conn.__dbus_object_path__,
104 device.opath,
105 ap.opath,
106 reply_handler=self.reply_handler,
107 error_handler=self.err_handler,
110 def make_nm(opath):
111 "Detects NM version and chooses appropriate class"
113 nmo = bus.get_object(NMC, opath)
114 nmi = dbus.Interface(nmo, NMI)
115 try:
116 dummy = nmi.getDevices()
117 return cNM_06(opath)
118 except dbus.exceptions.DBusException:
119 return cNM_07(opath)
121 class cNM_06(cNM):
122 def SetWifiEnabled(self, v):
123 # TODO: async call, catch the state signal and exit
124 # weird: synchronous call works, but times out
125 # asynchronous call does not work
126 self.nmi.setWirelessEnabled(v,
127 reply_handler=self.quitter_handler,
128 error_handler=self.quitter_handler)
129 global LOOP
130 LOOP = True
132 def SetOnline(self, v):
133 self.nmi.sleep(not v,
134 reply_handler=self.quitter_handler,
135 error_handler=self.quitter_handler)
136 global LOOP
137 LOOP = True
139 def Dump0(self):
140 print "State:", self.NM_STATE[self.nmi.state()]
141 (we, whe) = self.nmi.getWirelessEnabled()
142 print "Wifi enabled:", bool(we)
143 print "Wifi HW enabled:", bool(whe)
144 try:
145 dup = self.nmi.getDialup()
146 except dbus.exceptions.DBusException, e:
147 if e.get_dbus_name() == "org.freedesktop.NetworkManager.NoDialup":
148 dup = []
149 print "Dialup:", dup
151 def Devices(self):
152 opaths = self.nmi.getDevices()
153 return map(cDevice_06, opaths)
155 def ActiveConnections(self):
156 return [] # at most one active connection, FIXME find it
159 class cNM_07(cNM):
160 def SetWifiEnabled(self, v):
161 self.nmpi.Set(NMI, "WirelessEnabled", v)
163 def SetOnline(self, v):
164 self.nmi.Sleep(not v)
166 def Dump0(self):
167 print "State:", self.NM_STATE[self.nmpi.Get(NMI, "State")]
168 print "Wifi enabled:", self.nmpi.Get(NMI, "WirelessEnabled")
169 print "Wifi HW enabled:", self.nmpi.Get(NMI, "WirelessHardwareEnabled")
171 def Devices(self):
172 opaths = self.nmi.GetDevices()
173 return map(cDevice_07, opaths)
175 def ActiveConnections(self):
176 aconns = self.nmpi.Get(NMI, "ActiveConnections")
177 return map(cActiveConnection, aconns)
181 class cActiveConnection:
182 def __init__(self, opath):
183 self.opath = opath
185 def Dump(self):
186 print self.opath
187 co = bus.get_object(NMC, self.opath)
188 copi = dbus.Interface(co, PI)
189 for P in ["ServiceName", "Connection", "SharedServiceName", "SharedConnection", "SpecificObject",]:
190 print " %s: %s" % (P, copi.Get(NMI, P))
191 devs = copi.Get(NMI, "Devices")
192 print " Devices:"
193 for dev in devs:
194 print " ", dev
196 def bitmask_str(map, value):
197 ret = []
198 for mask in sorted(map.keys()):
199 if value & mask: ret.append(map[mask])
200 return ",".join(ret)
203 class cDevice:
204 def __init__(self, opath):
205 self.opath = opath
206 self.devo = bus.get_object(NMC, self.opath)
207 self.devi = dbus.Interface(self.devo, NMI + ".Device")
208 self.devpi = dbus.Interface(self.devo, PI)
209 self.dt = None
210 self.DeviceType0()
212 DEVICE_TYPE = ["UNKNOWN", "802_3_ETHERNET", "802_11_WIRELESS",
213 "GSM", "CDMA",]
215 def DeviceType(self):
216 return self.DEVICE_TYPE[self.DeviceType0()]
218 def ip_str(self, i32):
219 ret = []
220 ret.append("%d" % (i32 % 256))
221 i32 /= 256
222 ret.append("%d" % (i32 % 256))
223 i32 /= 256
224 ret.append("%d" % (i32 % 256))
225 i32 /= 256
226 ret.append("%d" % (i32 % 256))
227 i32 /= 256
228 return ".".join(ret)
230 def DumpIp4Config(self, opath):
231 print " Ip4Config:", opath
232 o = bus.get_object(NMC, opath)
233 pi = dbus.Interface(o, PI)
234 try:
235 for P in ["Address", "Netmask", "Broadcast", "Gateway",]: # beta2?
236 print " %s: %s" % (P, self.ip_str(pi.Get(NMI, P)))
237 except:
238 print " Addresses:"
239 addrs = pi.Get(NMI, "Addresses")
240 for addr in addrs:
241 print " %s/%s via %s" % tuple(map(self.ip_str, addr))
242 hn = pi.Get(NMI, "Hostname")
243 print " Hostname:", hn
244 nss = pi.Get(NMI, "Nameservers")
245 print " Nameservers:", " ".join(map(self.ip_str, nss))
246 doms = pi.Get(NMI, "Domains")
247 print " Domains:", " ".join(doms)
248 nisd = pi.Get(NMI, "NisDomain")
249 print " NisDomain:", nisd
250 niss = pi.Get(NMI, "NisServers")
251 print " NisServers:", " ".join(map(self.ip_str, niss))
253 NM_DEVICE_CAP = {1: "NM_SUPPORTED", 2: "CARRIER_DETECT", 4: "SCANNING", }
256 def Dump(self):
257 print "Device:", self.opath
260 IW_MODE = ["AUTO", "ADHOC", "INFRA", "MASTER",
261 "REPEAT", "SECOND", "MONITOR",]
263 def ListNets(self):
264 for ap in self.APs():
265 ap.ListNets()
267 # mixin
268 class cDeviceEth:
269 def APs(self):
270 return []
272 class cDevice_06(cDevice):
273 def DeviceType0(self):
274 if self.dt is None:
275 self.dt = self.devi.getProperties()[2]
276 if self.dt == 1:
277 self.__class__ = cDeviceEth_06
278 elif self.dt == 2:
279 self.__class__ = cDeviceWifi_06
280 return self.dt
282 NM_ACT_STAGE = [
283 "UNKNOWN", "DEVICE_PREPARE", "DEVICE_CONFIG", "NEED_USER_KEY",
284 "IP_CONFIG_START", "IP_CONFIG_GET", "IP_CONFIG_COMMIT",
285 "ACTIVATED", "FAILED", "CANCELLED", ]
287 def Dump(self):
288 cDevice.Dump(self)
289 print " Driver:", self.devi.getDriver()
290 props = self.devi.getProperties() # osusb ussss sssii biuus as
291 print " Self:", props[0] # o
292 print " Interface:", props[1] # s
293 print " Type:", self.DEVICE_TYPE[props[2]] # u
294 print " UDI:", props[3] # s
295 print " Active:", bool(props[4]) # b
296 print " Activation Stage:", self.NM_ACT_STAGE[props[5]] # u
297 print " IP:", props[6] # s
298 print " Mask:", props[7] # s
299 print " Bcast:", props[8] # s
300 print " HwAddress:", props[9] # s
301 print " GW:", props[10] # s
302 print " NS1:", props[11] # s
303 print " NS2:", props[12] # s
304 self.DumpMore()
306 class cDeviceEth_06(cDevice_06, cDeviceEth):
307 def DumpMore(self):
308 props = self.devi.getProperties() # osusb ussss sssii biuus as
309 print " Link Active:", bool(props[15]) # b
310 print " Speed:", props[16] # i
311 print " Generic Capabilities:", bitmask_str(self.NM_DEVICE_CAP, props[17]) # u
313 class cDeviceWifi_06(cDevice_06):
314 NM_802_11_CAP = {
315 0x00000001: "PROTO_NONE",
316 0x00000002: "PROTO_WEP",
317 0x00000004: "PROTO_WPA",
318 0x00000008: "PROTO_WPA2",
319 0x00000010: "RESERVED1",
320 0x00000020: "RESERVED2",
321 0x00000040: "KEY_MGMT_PSK",
322 0x00000080: "KEY_MGMT_802_1X",
323 0x00000100: "RESERVED3",
324 0x00000200: "RESERVED4",
325 0x00000400: "RESERVED5",
326 0x00000800: "RESERVED6",
327 0x00001000: "CIPHER_WEP40",
328 0x00002000: "CIPHER_WEP104",
329 0x00004000: "CIPHER_TKIP",
330 0x00008000: "CIPHER_CCMP",
333 def APs(self):
334 self.wdevi = dbus.Interface(self.devo, NMI + ".Device.Wireless")
335 aps = self.devi.getProperties()[20]
336 return map(cAP_06, aps)
338 def DumpMore(self):
339 props = self.devi.getProperties() # osusb ussss sssii biuus as
340 print " Mode:", self.IW_MODE[props[13]] # i
341 print " Strength:", props[14] # i
342 print " Link Active:", bool(props[15]) # b
343 print " Speed:", props[16] # i
344 print " Generic Capabilities:", bitmask_str(self.NM_DEVICE_CAP, props[17]) # u
345 print " Capabilities:", bitmask_str(self.NM_802_11_CAP, props[18]) # u
346 print " Current net:", props[19] # s
347 nets = props[20] # as
348 print " Seen nets:", " ".join(nets)
349 if options.ap:
350 print " Access Points"
351 for ap in self.APs():
352 ap.Dump()
354 class cDevice_07(cDevice):
355 def DeviceType0(self):
356 if self.dt is None:
357 self.dt = self.devpi.Get(NMI, "DeviceType")
358 if self.dt == 1:
359 self.__class__ = cDeviceEth_07
360 elif self.dt == 2:
361 self.__class__ = cDeviceWifi_07
362 return self.dt
364 NM_DEVICE_STATE = [
365 "UNKNOWN", "UNMANAGED", "UNAVAILABLE", "DISCONNECTED", "PREPARE",
366 "CONFIG", "NEED_AUTH", "IP_CONFIG", "ACTIVATED", "FAILED",]
368 def Dump(self):
369 cDevice.Dump(self)
371 # "Ip4Config", only for NM_DEVICE_STATE_ACTIVATED
372 for P in ["Udi", "Interface", "Driver",]:
373 print " %s: %s" % (P, self.devpi.Get(NMI, P))
374 addr = self.devpi.Get(NMI, "Ip4Address")
375 print " Ip4Address:", self.ip_str(addr)
376 caps = self.devpi.Get(NMI, "Capabilities")
377 print " Capabilities:", bitmask_str(self.NM_DEVICE_CAP, caps)
378 state = self.NM_DEVICE_STATE[self.devpi.Get(NMI, "State")]
379 print " Dev State:", state
380 if state == "ACTIVATED":
381 self.DumpIp4Config(self.devpi.Get(NMI, "Ip4Config"))
383 dt = self.DeviceType()
384 print " Dev Type:", dt
385 self.DumpMore()
387 class cDeviceEth_07(cDevice_07, cDeviceEth):
388 def DumpMore(self):
389 for P in ["HwAddress", "Speed", "Carrier"]:
390 print " %s: %s" % (P, self.devpi.Get(NMI, P))
392 class cDeviceWifi_07(cDevice_07):
393 NM_802_11_DEVICE_CAP = {1:"CIPHER_WEP40", 2:"CIPHER_WEP104",
394 4:"CIPHER_TKIP", 8:"CIPHER_CCMP",
395 16:"WPA", 32:"RSN",}
397 def APs(self):
398 self.wdevi = dbus.Interface(self.devo, NMI + ".Device.Wireless")
399 aps = self.wdevi.GetAccessPoints()
400 return map(cAP_07, aps)
402 def DumpMore(self):
403 print " Dev Mode:", self.IW_MODE[self.devpi.Get(NMI, "Mode")]
404 wcaps = self.devpi.Get(NMI, "WirelessCapabilities")
405 print " Wifi Capabilities:", bitmask_str(self.NM_802_11_DEVICE_CAP, wcaps)
406 for P in ["HwAddress", "Bitrate", "ActiveAccessPoint"]:
407 print " %s: %s" % (P, self.devpi.Get(NMI, P))
408 if options.ap:
409 print " Access Points"
410 for ap in self.APs():
411 ap.Dump()
413 """An AP found around us"""
414 class cAP:
415 def __init__(self, opath):
416 self.opath = opath
417 self.apo = bus.get_object(NMC, self.opath)
418 self.appi = dbus.Interface(self.apo, PI)
419 # for _06
420 self.devi = dbus.Interface(self.apo, NMI + ".Devices")
422 NM_802_11_AP_FLAGS = {1: "PRIVACY",}
424 NM_802_11_AP_SEC = {
425 1: "PAIR_WEP40", 2: "PAIR_WEP104", 4: "PAIR_TKIP", 8: "PAIR_CCMP",
426 16: "GROUP_WEP40", 32: "GROUP_WEP104", 64: "GROUP_TKIP",
427 128: "GROUP_CCMP", 256: "KEY_MGMT_PSK", 512: "KEY_MGMT_802_1X",}
429 def ListNets(self, marker = " "):
430 # TODO *mark current
431 mbr = self.Mbr() / 1024 # 07 1000, 06 1024?
432 priv_s = self.PrivS()
433 print "%s%3d: %s (%dMb%s)" % (marker, self.Strength(), self.Ssid(), mbr, priv_s)
435 class cAP_06(cAP):
436 def Mbr(self, props=None):
437 if props is None:
438 props = self.devi.getProperties()
439 return props[5]
442 def PrivS(self):
443 props = self.devi.getProperties()
444 caps_s = bitmask_str(cDeviceWifi_06.NM_802_11_CAP, props[7]) + ","
445 priv_s = ""
446 if caps_s.find("PROTO_WEP,") != -1:
447 priv_s += " WEP"
448 if caps_s.find("PROTO_WPA,") != -1:
449 priv_s += " WPA"
450 if caps_s.find("PROTO_WPA2,") != -1:
451 priv_s += " WPA2"
452 if caps_s.find("KEY_MGMT_802_1X,") != -1:
453 priv_s += " Enterprise"
454 return priv_s
456 def Strength(self, props=None):
457 if props is None:
458 props = self.devi.getProperties()
459 return props[3]
461 def Ssid(self, props=None):
462 if props is None:
463 props = self.devi.getProperties()
464 return props[1]
467 def Dump(self):
468 props = self.devi.getProperties() # ossid iiib
469 print " Self:", props[0]
470 print " Ssid:", self.Ssid(props)
471 print " HwAddress:", props[2]
472 print " Strength:", self.Strength(props)
473 print " Frequency:", props[4]
474 print " MaxBitrate:", self.Mbr(props)
475 print " AP Mode:", cDevice.IW_MODE[props[6]]
476 print " Capabilities:", bitmask_str(cDeviceWifi_06.NM_802_11_CAP, props[7])
477 print " Broadcast:", props[8]
479 class cAP_07(cAP):
480 def Mbr(self):
481 return self.appi.Get(NMI, "MaxBitrate")
483 def PrivS(self):
484 priv = self.appi.Get(NMI, "Flags") != 0
485 wpa = self.appi.Get(NMI, "WpaFlags") != 0
486 wpa2 = self.appi.Get(NMI, "RsnFlags") != 0
487 priv_s = ""
488 if priv:
489 if not wpa and not wpa2:
490 priv_s = priv_s + " WEP"
491 if wpa:
492 priv_s = priv_s + " WPA"
493 if wpa2:
494 priv_s = priv_s + " WPA2"
495 return priv_s
497 def Strength(self):
498 return int(self.appi.Get(NMI, "Strength"))
500 def ssid_str(noself, array):
501 s = ""
502 for b in array:
503 s = s + ("%c" % b)
504 return s
506 def Ssid(self):
507 return self.ssid_str(self.appi.Get(NMI, "Ssid"))
509 def Dump(self):
510 print " AP:", self.opath
511 print " Ssid:", self.Ssid()
512 for P in ["Frequency", "HwAddress", "MaxBitrate",]:
513 print " %s: %s" % (P, self.appi.Get(NMI, P))
514 print " Strength:", self.Strength()
515 print " AP Mode:", cDevice.IW_MODE[self.appi.Get(NMI, "Mode")]
516 print " AP Flags:", bitmask_str(self.NM_802_11_AP_FLAGS,
517 self.appi.Get(NMI, "Flags"))
518 print " AP WPA Flags:", bitmask_str(self.NM_802_11_AP_SEC,
519 self.appi.Get(NMI, "WpaFlags"))
520 print " AP RSN Flags:", bitmask_str(self.NM_802_11_AP_SEC,
521 self.appi.Get(NMI, "RsnFlags"))
523 # this is the client side of the applet; see also UserSettings
524 class cApplet:
525 def __init__(self, svc, opath):
526 self.svc = svc
527 self.opath = opath
528 self.so = bus.get_object(self.svc, self.opath)
529 self.si = dbus.Interface(self.so, 'org.freedesktop.NetworkManagerSettings')
531 def isSystem(self):
532 return self.svc == SSC;
534 def Dump(self):
535 for conn in self.Connections():
536 conn.Dump()
537 if self.isSystem():
538 self.DumpSystem()
540 def DumpSystem(self):
541 sspi = dbus.Interface(self.so, PI)
542 print "Unmanaged Devices"
543 umds = sspi.Get(NMI, "UnmanagedDevices")
544 for umd in umds:
545 print " ", umd
546 # dump_settings_conn(svc, conn) umd?
549 def myConnection(self, opath):
550 return cConnection(self.svc, opath)
552 def Connections(self):
553 opaths = self.si.ListConnections()
554 return map(self.myConnection, opaths)
556 class cConnection:
557 def __init__(self, svc, opath):
558 self.svc = svc
559 self.opath = opath
560 self.co = bus.get_object(self.svc, self.opath)
561 self.ci = dbus.Interface(self.co, 'org.freedesktop.NetworkManagerSettings.Connection')
563 def Dump(self):
564 print "Conn:", self.opath
565 print " Id:", self.ci.GetID()
566 settings = self.Settings()
567 settings.Dump()
569 si = dbus.Interface(self.co, 'org.freedesktop.NetworkManagerSettings.Connection.Secrets')
570 security = settings.Security()
571 if security != "":
572 print " SECRETS:", security
573 # TODO merge them
574 secrets = cSettings(si.GetSecrets(security,[],False))
575 secrets.Dump()
577 def Settings(self):
578 return cSettings(self.ci.GetSettings())
581 class cSettings:
582 def __init__(self, conmap):
583 self.conmap = conmap
585 def Type(self):
586 return self.conmap["connection"]["type"]
588 def GetID(self):
589 return self.conmap["connection"]["id"]
591 def Security(self):
592 try:
593 return self.conmap[self.Type()]["security"]
594 except KeyError:
595 return ""
597 def isNet(self, net_name):
598 # FIXME also ssid ...
599 return self.GetID() == net_name
601 # FIXME check spec/NM what to censor
602 secrets = dict.fromkeys(["wep-key0", "psk"])
604 def ConMap(self):
605 "For GetSettings: censor secrets."
607 cm = dict()
608 for n1, v1 in self.conmap.iteritems():
609 cm[n1] = dict()
610 for n2, v2 in v1.iteritems():
611 cv2 = v2
612 if self.secrets.has_key(n2):
613 cv2 = ""
614 cm[n1][n2] = cv2
615 return cm
617 def SecMap(self):
618 "For GetSecrets: only secrets."
619 s = self.Security()
620 r = {
621 s: self.conmap[s]
623 print "SECMAP", r
624 return r
626 def Dump(self):
627 for n1, v1 in self.conmap.iteritems():
628 print " ",n1
629 for n2, v2 in v1.iteritems():
630 print " %s: %s" % (n2, v2)
632 # just an example, unused now
633 hardwired_conmaps = [
635 "connection": {
636 "id": "onenet",
637 "type": "802-11-wireless",
639 "802-11-wireless": {
640 "ssid": dbus.ByteArray("onenet"),
641 "mode": "infrastructure",
642 "security": "802-11-wireless-security",
644 # ipv4
645 # method: dhcp
646 "802-11-wireless-security": {
647 "key-mgmt": "wpa-psk",
648 "wep-tx-keyidx": 0,
649 "psk": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", # CENSORED
653 'connection': {
654 'id': 'frogs',
655 'type': '802-11-wireless',
657 '802-11-wireless': {
658 'ssid': dbus.ByteArray('frogs'),
659 'mode': 'infrastructure',
660 'security': '802-11-wireless-security',
662 '802-11-wireless-security': {
663 'key-mgmt': 'none',
664 'wep-tx-keyidx': 0,
665 'wep-key0': 'aaaaaaaaaaaaaaaaaaaaaaaaaa', # CENSORED
670 class UserSettings_06:
671 @dbus.service.method(dbus_interface="org.freedesktop.NetworkManagerInfo",
672 in_signature="i", out_signature='as')
673 def getNetworks(self, i):
674 return ["frogs"] # FIXME
676 @dbus.service.method(dbus_interface="org.freedesktop.NetworkManagerInfo",
677 in_signature="", out_signature='ao') # out??
678 def getVpnConnections(self):
679 return [] # FIXME
681 @dbus.service.method(dbus_interface="org.freedesktop.NetworkManagerInfo",
682 in_signature="si", out_signature='sibasisi')
683 # or additional i ???
684 def getNetworkProperties(self, net, i):
685 # essid, timestamp, ?, bssids, we_cipher, ?, ...
686 # we_cipher=16: i wep_auth_algorithm
687 # we_cipher=0: i wpa_psk_key_mgt, i wpa_psk_wpa_version
688 return ("frogs", 1213713468, 0, ['00:13:10:06:E3:77'], 16, "", 1)
689 return [] # FIXME
691 @dbus.service.method(dbus_interface="org.freedesktop.NetworkManagerInfo",
692 in_signature="oosib", out_signature="isi")
693 def getKeyForNetwork(self, dev, net, ssid, i, b):
694 return (16, "66666666666666666666666666",1) # FIXME
696 @dbus.service.method(dbus_interface="org.freedesktop.NetworkManagerInfo",
697 in_signature="sbsisi", out_signature='')
698 def updateNetworkInfo(self, ssid, b, ap, i1, secret, i2):
699 pass
703 # server analog of cApplet
704 class UserSettings(dbus.service.Object):
705 # conmaps is a list
706 def __init__(self, opath, conmaps):
707 dbus.service.Object.__init__(self, bus, opath)
708 #print "CONMAPS:", conmaps
709 self.conns = map(self.newCon, conmaps)
711 counter = 1
712 def newCon(self, conmap):
713 cpath = "/MyConnection/%d" % self.counter
714 self.counter = self.counter + 1
715 c = Connection(cpath, conmap)
716 self.NewConnection(cpath) # announce it
717 return c
719 @dbus.service.method(dbus_interface='org.freedesktop.NetworkManagerSettings',
720 in_signature='', out_signature='ao')
721 def ListConnections(self):
722 return [c.__dbus_object_path__ for c in self.conns]
724 #this is for EMITTING a signal, not receiving it
725 @dbus.service.signal(dbus_interface='org.freedesktop.NetworkManagerSettings',
726 signature='o')
727 def NewConnection(self, opath):
728 pass
729 #print "signalling newconn:", opath
731 def GetByNet(self, net_name):
732 "Returns connection, or None"
733 for c in self.conns:
734 if c.isNet(net_name):
735 return c
736 return None
739 # server analog of cConnection
740 class Connection(dbus.service.Object):
741 def __init__(self, opath, conmap):
742 dbus.service.Object.__init__(self, bus, opath)
743 self.settings = cSettings(conmap)
745 @dbus.service.method(dbus_interface='org.freedesktop.NetworkManagerSettings.Connection',
746 in_signature='', out_signature='a{sa{sv}}')
747 def GetSettings(self):
748 #print "Getting settings:", self. __dbus_object_path__
749 # return self.settings.ConMap()
750 # grr, censoring secrets makes NM complain!?
751 return self.settings.conmap
753 @dbus.service.method(dbus_interface='org.freedesktop.NetworkManagerSettings.Connection.Secrets',
754 in_signature='sasb', out_signature='a{sa{sv}}')
755 def GetSecrets(self, tag, hints, ask):
756 # FIXME respect args
757 print "Getting secrets:", self.__dbus_object_path__
758 return self.settings.SecMap()
760 @dbus.service.method(dbus_interface='org.freedesktop.NetworkManagerSettings.Connection',
761 in_signature='', out_signature='s')
762 def GetID(self):
763 return self.settings.GetID()
765 def isNet(self, net_name):
766 return self.settings.isNet(net_name)
768 class ConfigParserKNM:
769 "Parse ~/.kde/share/config/knetworkmanagerrc"
771 def __init__(self):
772 p = ConfigParser.RawConfigParser()
773 ok = p.read(os.getenv("HOME") + "/.kde/share/config/knetworkmanagerrc")
775 self.conmaps_d = {}
776 for s in p.sections():
777 path = s.split("_")
778 #print path
779 if path[0] in ["ConnectionSetting", "ConnectionSecrets"]:
780 cid = path[1]
781 self.conmaps_d.setdefault(cid, {})
782 part = path[2]
784 values = {}
785 for (n, v) in p.items(s):
786 # WTF, Value_ is transfrmed to value_
787 if n[:6] == "value_":
788 n = n[6:]
789 v = self.ParseValue(v)
790 values[n] = v
791 if len(values) != 0: # empty 802-1x confuses NM!?
792 self.conmaps_d[cid].setdefault(part, {})
793 self.conmaps_d[cid][part].update(**values)
794 #print "PARSED", cid, part, values
796 def ConMaps(self):
797 return self.conmaps_d.values()
799 def ParseValue(self, v):
800 v = eval('"%s"' % v) # unescape backslashes
801 dom = xml.dom.minidom.parseString(v)
802 return self.ParseNode(dom.documentElement)
804 def ParseNode(self, n):
805 t = n.localName
806 if t != "list":
807 v = self.NodeText(n)
809 if t == "string":
810 return v
811 elif t == "byte":
812 return dbus.Byte(int(v))
813 elif t == "bool":
814 return v == "true"
815 elif t == "int32" or t == "uint32":
816 return int(v)
817 elif t == "list":
818 v = []
819 c = n.firstChild
820 while c != None:
821 if c.localName != None: # whitespace
822 v.append(self.ParseNode(c))
823 c = c.nextSibling
824 return v
826 def NodeText(self, n):
827 if n.hasChildNodes():
828 return n.firstChild.wholeText
829 else:
830 return ""
832 def abbr_signal_handler(*args, **kwargs):
833 ifc = kwargs["interface"]
834 sig = kwargs["member"]
835 opath = kwargs["path"]
836 line = "SIG %s: %s.%s%s" % (abbrev(opath,"/"), abbrev(ifc,"."), sig, args)
837 print line
839 class Monitor:
840 def __init__(self):
841 self.amap = {}
842 bus.add_signal_receiver(self.abbr_signal_handler,
843 path_keyword="path",
844 interface_keyword="interface",
845 member_keyword="member")
847 def abbr_signal_handler(self, *args, **kwargs):
848 ifc = kwargs["interface"]
849 sig = kwargs["member"]
850 opath = kwargs["path"]
851 line = "SIG %s: %s.%s%s" % (self.abbrev(opath,"/"),
852 self.abbrev(ifc,"."),
853 sig, args)
854 print line
856 def abbrev(self, s, sep):
857 words = s.split(sep)
858 words = map (self.a1, words)
859 result = sep.join(words)
860 if not self.amap.has_key(s):
861 print "ABBR %s is %s" % (result, s)
862 self.amap[s] = result
863 else:
864 if self.amap[s] != result:
865 print "ABBR COLLISION %s was %s now %s" % (s, self.amap[s], result)
866 return result
868 def a1(self, s):
869 try:
870 return s[0]
871 except:
872 return ""
874 # main
876 op = OptionParser(version="%prog " + VERSION)
877 op.add_option("-d", "--dev",
878 action="store_true", default=False,
879 help="list devices")
880 op.add_option("-c", "--actcon",
881 action="store_true", default=False,
882 help="list active connections")
883 op.add_option("-u", "--usrcon",
884 action="store_true", default=False,
885 help="list user connection settings (can CRASH nm-applet)")
886 op.add_option("-s", "--syscon",
887 action="store_true", default=False,
888 help="list system connection settings")
889 op.add_option("-a", "--ap",
890 action="store_true", default=False,
891 help="list found access points")
892 op.add_option("-n", "--nets",
893 action="store_true", default=False,
894 help="list found wireless networks")
895 # TODO http://docs.python.org/lib/optparse-adding-new-types.html
896 op.add_option("-w", "--wifi",
897 choices=["0","1","off","on","no","yes","false","true"],
898 metavar="BOOL",
899 help="enable or disable wireless")
900 op.add_option("-o", "--online",
901 choices=["0","1","off","on","no","yes","false","true"],
902 metavar="BOOL",
903 help="enable or disable network at all")
905 op.add_option("-C", "--connect",
906 help="connect to a wireless network NET (using knetworkmanagerrc)",
907 metavar="NET")
908 op.add_option("-m", "--monitor",
909 action="store_true", default=False,
910 help="loop to show dbus signals")
913 (options, args) = op.parse_args()
915 if options.ap:
916 options.dev = True
917 if options.monitor:
918 LOOP = True
921 nmp = '/org/freedesktop/NetworkManager'
922 nm = make_nm(nmp)
923 if options.dev or options.actcon:
924 nm.Dump()
926 true_choices = ["1", "on", "yes", "true"]
927 if options.wifi != None:
928 nm.SetWifiEnabled(options.wifi in true_choices)
929 if options.online != None:
930 nm.SetOnline(options.online in true_choices)
932 if options.nets:
933 nm.ListNets()
935 if options.syscon:
936 print "SYSTEM Connections"
937 ss = cApplet(SSC, '/org/freedesktop/NetworkManagerSettings')
938 ss.Dump()
940 if options.usrcon:
941 print "USER Connections"
942 try:
943 us = cApplet(USC, '/org/freedesktop/NetworkManagerSettings')
944 us.Dump()
945 except dbus.exceptions.DBusException, e:
946 print e
947 if e.get_dbus_name() == "org.freedesktop.DBus.Error.ServiceUnknown":
948 print "Applet is not running"
950 nmo = bus.get_object(NMC, nmp)
951 nmi = dbus.Interface(nmo, NMI)
953 # TODO UserSettings_06
954 if options.connect != None:
955 brn = bus.request_name(USC, _dbus_bindings.NAME_FLAG_DO_NOT_QUEUE)
956 if brn == _dbus_bindings.REQUEST_NAME_REPLY_EXISTS:
957 print "Could not provide settings service, another applet is running"
958 sys.exit(1)
959 cfg = ConfigParserKNM()
960 us = UserSettings("/org/freedesktop/NetworkManagerSettings",
961 cfg.ConMaps())
963 def Connect(wanted_net): # any. or take arg. net is config name or ssid name
964 # ... in general, look for string in all config data. ssid for wifi, whatever for dialup
965 # TODO also respect autoconnect
967 # ActivateConn wants setting device ap; can find device from ap? ap is "specific" for wifi devices
968 #print "Connection wanted to", wanted_net
969 found_con = found_ap = found_dev = None
970 for dev in nm.Devices():
971 for ap in dev.APs():
972 if wanted_net == ap.Ssid():
973 found_ap = ap
974 found_dev = dev
975 break # FIXME both loops
976 found_con = us.GetByNet(wanted_net)
977 if found_ap == None:
978 print "No AP found with SSID", wanted_net
979 return False
980 elif found_con == None:
981 print "No settings for net", wanted_net
982 return False
983 else:
984 nm.ActivateConnection(found_con, found_dev, found_ap) # TODO async
985 # TODO run loop, exit it when we have serviced the required calls
986 return True
988 if options.connect != None:
989 if Connect(options.connect):
990 LOOP = True
992 if options.monitor:
993 m = Monitor()
995 def loop():
996 loop = gobject.MainLoop()
997 try:
998 loop.run()
999 except:
1000 print "Loop exited"
1002 if LOOP:
1003 loop()