4.5.0r6
[enigma2.git] / usr / lib / enigma2 / python / Plugins / SystemPlugins / NetworkManager / NetworkConfig.py
1 # -*- coding: utf-8 -*-
2 from enigma import eNetworkManager, eNetworkService, eNetworkServicePtr, StringList
3
4 from Components.Label import Label
5 from Components.ActionMap import ActionMap
6 from Components.config import config, getConfigListEntry, ConfigIP, ConfigOnOff, ConfigIP6, ConfigSelection, ConfigInteger, ConfigText
7 from Components.ConfigList import ConfigListScreen
8 from Components.Sources.List import List
9 from Components.Sources.StaticText import StaticText
10 from Components.Network import NetworkInterface
11 from Screens.Screen import Screen
12
13 from Tools.BoundFunction import boundFunction
14 from Tools.Directories import resolveFilename, SCOPE_CURRENT_SKIN
15 from Tools.Log import Log
16 from Tools.LoadPixmap import LoadPixmap
17
18 from netaddr import IPAddress
19
20 def toIP4List(value):
21         return [ int(v) for v in str(value).split(".") ]
22
23 def toIP4String(cfg):
24         return cfg.tostring(cfg.value)
25
26 class NetworkConfigGeneral(object):
27         @staticmethod
28         def translateSecurity(security):
29                 security_map = {
30                         "none" : _("None"),
31                         "wep"  : "WEP",
32                         "psk"  : "WPA/WPA2",
33                         "wps"  : "WPS",
34                         "ieee8021x" : "ieee8021x",
35                 }
36                 return security_map.get(security, security.upper())
37
38         @staticmethod
39         def translateState(state):
40                 state_map = {
41                         "idle" : _("Idle"),
42                         "failure" : _("Failure"),
43                         "association" : _("Association"),
44                         "configuration" : _("Configuration"),
45                         "disconnect" : _("Disconnect"),
46                         "online" : _("Connected"),
47                 }
48                 return state_map.get(state, state)
49
50         def __init__(self):
51                 self._nm = eNetworkManager.getInstance()
52                 self._nm_conn = [
53                                 self._nm.technologiesChanged.connect(self._technologiesChanged),
54                                 self._nm.stateChanged.connect(self._servicesChanged),
55                                 self._nm.servicesChanged.connect(self._servicesChanged),
56                         ]
57                 self._tech_conn = []
58                 self._services = List([], enableWrapAround = True)
59                 self._services.buildfunc = self._buildServiceListEntry
60
61         def _getCurrentService(self):
62                 service = self._services.getCurrent()
63                 if service:
64                         return service[1]
65                 return None
66         _currentService = property(_getCurrentService)
67
68         def _technologiesChanged(self):
69                 pass
70
71         def _techPoweredChanged(self, powered):
72                 if powered:
73                         self._rescan()
74
75         def _setTechPowered(self, cfg):
76                 tech = cfg.tech
77                 powered = not tech.powered()
78                 tech.setPowered(powered)
79
80         def _scanFinished(self, tech):
81                 pass
82
83         def _rescan(self, tech=None):
84                 if tech is not None and tech.type() == eNetworkService.TYPE_WIFI and tech.powered():
85                         Log.i("Triggering rescan for '%s'" %tech.name())
86                         tech.scan()
87                         return True
88
89                 res = False
90                 for tech in self._nm.getTechnologies():
91                         if tech.type() == eNetworkService.TYPE_WIFI and tech.powered():
92                                 Log.i("Triggering rescan for '%s'" %tech.name())
93                                 tech.scan()
94                                 res = True
95                 return res
96
97         def _removeService(self):
98                 service = self._currentService
99                 if isinstance(service, eNetworkServicePtr):
100                         Log.i("Removing %s" %service.name())
101                         service.setAutoConnect(False)
102                         service.remove()
103
104         def getActiveTechnologyCount(self):
105                 techs = self._nm.getTechnologies()
106                 counter = 0
107                 for tech in techs:
108                         if tech.powered():
109                                 counter += 1
110                 return counter
111
112         def getTechnologyConfig(self):
113                 l = []
114                 techs = self._nm.getTechnologies()
115                 self._tech_conn = []
116                 for tech in techs:
117                         cfg = ConfigOnOff(default=tech.powered())
118                         cfg.tech = tech
119                         cfg.addNotifier(self._setTechPowered, initial_call=False)
120                         self._tech_conn.append(tech.poweredChanged.connect(self._techPoweredChanged))
121                         self._tech_conn.append(tech.scanFinished.connect(boundFunction(self._scanFinished, tech)))
122                         title = "%s (%s)" %(tech.name(), tech.type())
123                         l.append(getConfigListEntry(title, cfg))
124                 Log.w(l)
125                 return l
126
127         def _servicesChanged(self, *args):
128                 pass
129
130         def getServiceList(self, unified=False):
131                 l = []
132                 services = self._nm.getServices()
133                 techs = self._nm.getTechnologies()
134                 self._tech_conn = []
135                 if unified:
136                         for tech in techs:
137                                 self._tech_conn.append(tech.poweredChanged.connect(self._techPoweredChanged))
138                                 self._tech_conn.append(tech.scanFinished.connect(boundFunction(self._scanFinished, tech)))
139                                 l.append( (tech.path(), tech,) )
140                                 for service in services:
141                                         if service.type() == tech.type():
142                                                 l.append( (service.path(), service,) )
143                 else:
144                         for service in services:
145                                 l.append( (service.path(), service,) )
146                 return l
147
148         def _buildListEntry(self, path, instance):
149                 if isinstance(instance, eNetworkServicePtr):
150                         return self._buildServiceListEntry(path, instance)
151                 else:
152                         return self._buildTechnologyListEntry(path, instance)
153
154         def _buildTechnologyListEntry(self, techpath, tech):
155                 #Log.i("technology: %s/%s" %(tech.name(), tech.type()))
156                 enabled = _("on") if tech.powered() else _("off")
157                 name = tech.name()
158                 if tech.isScanning():
159                         name = _("%s - scanning...") %name
160                 return (tech.path(), None, enabled, None, None, None, name, "")
161
162         def _buildServiceListEntry(self, svcpath, service):
163                 #Log.i("service: %s/%s/%s" %(service.name(), service.type(), service.strength()))
164                 strength = ""
165                 security = ""
166                 interfacepng = None
167                 if service.type() == eNetworkService.TYPE_ETHERNET:
168                         if service.connected():
169                                 interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wired-active.png"))
170                         else:
171                                 if service.state() != eNetworkManager.STATE_IDLE:
172                                         interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wired.png"))
173                                 else:
174                                         interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wired-inactive.png"))
175                 elif service.type() == eNetworkService.TYPE_WIFI:
176                         strength = "%s%s" %(service.strength(), "%")
177                         for sec in service.security():
178                                 if not security:
179                                         security = NetworkConfigGeneral.translateSecurity(sec)
180                                 else:
181                                         security = "%s, %s" %(security, NetworkConfigGeneral.translateSecurity(sec))
182                         if service.connected():
183                                 interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wireless-active.png"))
184                         else:
185                                 if service.state() != eNetworkManager.STATE_IDLE:
186                                         interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wireless.png"))
187                                 else:
188                                         interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wireless-inactive.png"))
189                 ip = ""
190                 if service.connected():
191                         ip = service.ipv4().get(eNetworkService.KEY_ADDRESS, "")
192                         if not ip:
193                                 ip = service.ipv6().get(eNetworkService.KEY_ADDRESS, "")
194
195                 if service.type() == eNetworkService.TYPE_BLUETOOTH:
196                         if service.connected():
197                                 interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/bluetooth-active.png"))
198                         else:
199                                 if service.state() != eNetworkManager.STATE_IDLE:
200                                         interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/bluetooth.png"))
201                                 else:
202                                         interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/bluetooth-inactive.png"))
203
204
205                 return (service.path(), interfacepng, strength, service.name(), ip, NetworkConfigGeneral.translateState(service.state()), None, security)
206
207 class NetworkServiceConfig(Screen, NetworkConfigGeneral):
208         def __init__(self, session):
209                 Screen.__init__(self, session)
210                 NetworkConfigGeneral.__init__(self)
211
212                 self["key_red"] = Label(_("Reset"))
213                 self["key_green"] = Label(_("Scan"))
214                 self["key_yellow"] = Label(_("IP"))
215                 self["key_blue"] = Label(_("DNS"))
216                 self["hint"] = Label(_("Press OK to connect"))
217                 self["details_label"] = Label(_("Active connection"))
218                 self["details"] = Label("")
219                 self["OkCancelActions"] = ActionMap(["OkCancelActions", "ColorActions", "MenuActions"],
220                 {
221                         "menu": self._menu,
222                         "cancel": self.close,
223                         "ok" : self._ok,
224                         "green": self._green,
225                         "red": self._removeService
226                 }, -3)
227                 self["ServiceActions"] = ActionMap(["ColorActions"],
228                 {
229                         "yellow": self._configIP,
230                         "blue": self._configDNS,
231                 }, -2)
232
233                 self["list"] = self._services
234                 self["summary_list"] = StaticText("")
235                 self._hasWireless = False
236
237                 self._services.buildfunc = self._buildListEntry
238                 self._services.onSelectionChanged.append(self._selectionChanged)
239
240                 self._addNotifiers()
241                 self._createSetup()
242
243                 self.onClose.append(self._onClose)
244                 self.onLayoutFinish.append(self.layoutFinished)
245
246         def _menu(self):
247                 self.session.open(NetworkTimeserverConfig)
248
249         def _green(self):
250                 if isinstance(self._currentService, eNetworkServicePtr):
251                         wol = self._currentService.wol()
252                         self._enableWoL(wol == eNetworkService.WAKE_FLAG_NEVER)
253                 else:
254                         self._rescan()
255
256         def _rescan(self):
257                 if not self._currentService or isinstance(self._currentService, eNetworkServicePtr):
258                         return
259                 if self._currentService.type() != eNetworkService.TYPE_WIFI:
260                         return
261                 if NetworkConfigGeneral._rescan(self, self._currentService):
262                         self._createSetup()
263
264         def _enableWoL(self, enable):
265                 if isinstance(self._currentService, eNetworkServicePtr) and self._currentService.hasWoL():
266                         Log.w(self._currentService.wol())
267                         config.network.wol_enabled.value = enable
268                         config.network.wol_enabled.save()
269                         if enable:
270
271                                 self._currentService.setWoL(eNetworkService.WAKE_FLAG_MAGIC)
272                         else:
273                                 self._currentService.setWoL(eNetworkService.WAKE_FLAG_NEVER)
274                         self._createSetup()
275
276         def _scanFinished(self, tech):
277                 Log.i("finished!")
278                 self._createSetup()
279
280         def _removeService(self):
281                 NetworkConfigGeneral._removeService(self)
282                 self._createSetup()
283
284         def _selectionChanged(self):
285                 self._checkButtons()
286                 self._updateSummary()
287
288         def _updateSummary(self):
289                 text = ""
290                 service = self._currentService
291                 if not service:
292                         self["summary_list"].setText(text)
293                         return
294                 if isinstance(service, eNetworkServicePtr):
295                         text = service.name()
296                         if service.connected():
297                                 ni = NetworkInterface(service)
298                                 ip = ni.getIpv4()
299                                 if not ip:
300                                         ip = ni.getIpv6()
301                                 if ip:
302                                         ip = ip.address
303                                 else:
304                                         ip = self.translateState(service.state())
305                                 text = "%s\n%s" %(text, ip)
306                         else:
307                                 text = "%s\n%s" %(text, self.translateState(service.state()))
308                 else:
309                         powered = _("On") if service.powered() else _("Off")
310                         text = "%s - %s" %(service.name(), powered)
311                 self["summary_list"].setText(text)
312
313         def _checkButtons(self):
314                 self["hint"].setText("")
315                 if isinstance(self._currentService, eNetworkServicePtr): #a service
316                         if self._currentService.hasWoL():
317                                 self["key_green"].setText(_("WoL"))
318                                 self["key_green"].show()
319                         else:
320                                 self["key_green"].hide()
321                         if self._currentService.connected():
322                                 self["hint"].setText(_("Press OK to disconnect"))
323                         else:
324                                 self["hint"].setText(_("Press OK to connect"))
325                         if self._currentService.favorite():
326                                 self["key_red"].show()
327                         else:
328                                 self["key_red"].hide()
329                         self["key_yellow"].show()
330                         self["key_blue"].show()
331                         self["ServiceActions"].setEnabled(True)
332                 else: #a technology
333                         if self._currentService and self._currentService.type() == eNetworkService.TYPE_WIFI:
334                                 self["key_green"].setText(_("Scan"))
335                                 self["key_green"].show()
336                         else:
337                                 self["key_green"].hide()
338                         self["key_red"].hide()
339                         if self._currentService:
340                                 if self._currentService.powered():
341                                         self["hint"].setText(_("Press OK to disable"))
342                                 else:
343                                         self["hint"].setText(_("Press OK to enable"))
344                         else:
345                                 self["hint"].setText("")
346                         self["key_yellow"].hide()
347                         self["key_blue"].hide()
348                         self["ServiceActions"].setEnabled(False)
349
350         def _configChanged(self, *args, **kwargs):
351                 self._createSetup()
352
353         def _configIP(self):
354                 service = self._currentService
355                 if service:
356                         self.session.open(NetworkServiceIPConfig, service)
357
358         def _configDNS(self):
359                 service = self._currentService
360                 if service:
361                         self.session.open(NetworkServiceNSConfig, service)
362
363         def _technologiesChanged(self):
364                 self._createSetup()
365
366         def _servicesChanged(self, *args):
367                 self._createSetup()
368
369         def _addNotifiers(self):
370                 pass
371
372         def _removeNotifiers(self):
373                 pass
374
375         def _onClose(self):
376                 self._removeNotifiers()
377
378         def keyLeft(self):
379                 ConfigListScreen.keyLeft(self)
380
381         def keyRight(self):
382                 ConfigListScreen.keyRight(self)
383
384         def _ok(self):
385                 item = self._currentService
386                 if not item:
387                         return
388                 if isinstance(item, eNetworkServicePtr):
389                         state = item.state()
390                         Log.i(state)
391                         if state == eNetworkManager.STATE_IDLE or state == eNetworkManager.STATE_FAILURE:
392                                 item.requestDisconnect()
393                                 item.requestConnect()
394                                 item.setAutoConnect(True)
395                         else:
396                                 item.requestDisconnect()
397                 else:
398                         item.setPowered(not item.powered())
399
400         def _createSetup(self):
401                 self._hasWireless = False
402                 for tech in self._nm.getTechnologies():
403                         if tech.type() == eNetworkService.TYPE_WIFI and tech.powered():
404                                 self._hasWireless = True
405                 self._services.updateList(self.getServiceList(unified=True))
406                 self._checkButtons()
407                 self._setDetailText()
408
409         def _setDetailText(self):
410                 text = ""
411                 for service in self._nm.getServices():
412                         if service.connected():
413                                 if text:
414                                         text = "\n\n%s" %(text)
415
416                                 text = "%s" %(service.name())
417                                 Log.w(service.wol())
418                                 if service.wol() != eNetworkService.WAKE_FLAG_NEVER:
419                                         Log.w(service.wol())
420                                         text = "%s (Wake-on-Lan enabled)" %(text,)
421                                 text = "%s\n\n" %(text,)
422                                 ni = NetworkInterface(service)
423
424                                 ip4 = ni.getIpv4()
425                                 ip6 = ni.getIpv6()
426                                 iptext = _("%s IPv%s\n  Address: %s\n  %s: %s\n  Gateway: %s\n\n")
427                                 #IPv4
428                                 if ip4.method != eNetworkService.METHOD_OFF:
429                                         addr = ip4.address
430                                         mask = ip4.netmask
431                                         gw = ip4.gateway
432                                         text = iptext %(
433                                                         text,
434                                                         4,
435                                                         addr,
436                                                         _("Netmask"),
437                                                         mask,
438                                                         gw,
439                                                 )
440                                 #IPv6
441                                 if ip6.method != eNetworkService.METHOD_OFF:
442                                         addr = ip6.address
443                                         mask = ip6.netmask
444                                         gw = ip6.gateway
445                                         text = iptext %(
446                                                         text,
447                                                         6,
448                                                         addr,
449                                                         _("Prefix length"),
450                                                         mask,
451                                                         gw,
452                                                 )
453                                 ns = self._textFormatIpList( service.nameservers() )
454                                 text = _("%sName server\n%s\n") %(text, ns)
455                                 ts = self._textFormatIpList( service.timeservers() )
456                                 text = _("%s\nTime server\n%s\n") %(text, ts)
457
458                                 mac = ni.ethernet.mac
459                                 text = ("%s\n" + _("Hardware address") + "\n%s\n") %(text, mac)
460                                 break
461                 self["details"].setText(text)
462
463         def _textFormatIpList(self, iplist):
464                 if not iplist:
465                         return "  %s" %(_("n/a"))
466                 iplist = "  %s" %("\n  ".join(iplist))
467                 return iplist
468
469         def _techPoweredChanged(self, powered):
470                 if powered:
471                         self._rescan()
472                 self._createSetup()
473
474         def layoutFinished(self):
475                 self.setTitle(_("Network Config"))
476                 self._checkButtons()
477                 self._updateSummary()
478
479 class ServiceBoundConfiguration(object):
480         def __init__(self, service):
481                 self._service = service
482                 nm = eNetworkManager.getInstance()
483                 self._svcRemovedConn = nm.serviceRemoved.connect(self.__onServiceRemoved)
484                 self._isServiceRemoved = False
485
486         def __onServiceRemoved(self, svcpath):
487                 if svcpath == self._service.path():
488                         Log.i("Service '%s' removed. Closing..." %svcpath)
489                         self._isServiceRemoved = True
490                         #TODO show a messagebox! The user will be VERY confused otherwise!
491                         self.close()
492
493 class ServiceIPConfiguration(object):
494         def __init__(self, service):
495                 self._service = service
496                 self.onChanged = []
497                 self.onMethodChanged = []
498                 method_choices_ip4 = {eNetworkService.METHOD_DHCP : "dhcp", eNetworkService.METHOD_MANUAL : _("manual"), eNetworkService.METHOD_OFF : _("off")}
499                 #IPv4
500                 self._config_ip4_method = ConfigSelection(method_choices_ip4, default=eNetworkService.METHOD_DHCP)
501                 self._config_ip4_address = ConfigIP(default=[0,0,0,0])
502                 self._config_ip4_mask = ConfigIP(default=[0,0,0,0])
503                 self._config_ip4_gw = ConfigIP(default=[0,0,0,0])
504                 #IPv6
505                 method_choices_ip6 = {eNetworkService.METHOD_AUTO : _("auto"), eNetworkService.METHOD_6TO4 : "6to4", eNetworkService.METHOD_MANUAL : _("manual"), eNetworkService.METHOD_OFF : _("off")}
506                 choices_privacy_ip6 = {eNetworkService.IPV6_PRIVACY_DISABLED : _("Disabled"), eNetworkService.IPV6_PRIVACY_ENABLED : _("Enabled"), eNetworkService.IPV6_PRIVACY_PREFERRED : _("Preferred")}
507                 self._config_ip6_method = ConfigSelection(method_choices_ip6, default=eNetworkService.METHOD_DHCP)
508                 self._config_ip6_address = ConfigIP6()
509                 self._config_ip6_prefix_length = ConfigInteger(0, limits=(1, 128))
510                 self._config_ip6_gw = ConfigIP6()
511                 self._config_ip6_privacy = ConfigSelection(choices_privacy_ip6, default="disabled")
512
513                 self._isReloading = False
514                 self._ipv4Changed = False
515                 self._ipv6Changed = False
516                 self._addNotifiers()
517                 self._service_conn = [
518                         self._service.ipv4Changed.connect(self._serviceChanged),
519                         self._service.ipv6Changed.connect(self._serviceChanged),
520                         self._service.ipv4ConfigChanged.connect(self._serviceChanged),
521                         self._service.ipv6ConfigChanged.connect(self._serviceChanged),
522                 ]
523
524         def _serviceChanged(self, *args):
525                 self.reload(force=False)
526
527         def _addNotifiers(self):
528                 #Setup refresh
529                 self._config_ip4_method.addNotifier(self._methodChanged, initial_call=False)
530                 self._config_ip6_method.addNotifier(self._methodChanged, initial_call=False)
531
532                 #change tracking
533                 #ipv4
534                 self._config_ip4_method.addNotifier(self._changedIP4, initial_call=False)
535                 self._config_ip4_address.addNotifier(self._changedIP4, initial_call=False)
536                 self._config_ip4_mask.addNotifier(self._changedIP4, initial_call=False)
537                 self._config_ip4_gw.addNotifier(self._changedIP4, initial_call=False)
538                 #ipv6
539                 self._config_ip6_method.addNotifier(self._changedIP6, initial_call=False)
540                 self._config_ip6_address.addNotifier(self._changedIP6, initial_call=False)
541                 self._config_ip6_prefix_length.addNotifier(self._changedIP6, initial_call=False)
542                 self._config_ip6_gw.addNotifier(self._changedIP6, initial_call=False)
543                 self._config_ip6_privacy.addNotifier(self._changedIP6, initial_call=False)
544
545         def _changedIP4(self, element):
546                 if not self._isReloading:
547                         self._ipv4Changed = True
548                 self._changed(element)
549
550         def _changedIP6(self, element):
551                 if not self._isReloading:
552                         self._ipv6Changed = True
553                 self._changed(element)
554
555         def _changed(self, element):
556                 if not self._isReloading:
557                         Log.i()
558                         for fnc in self.onChanged:
559                                 fnc()
560
561         def _methodChanged(self, element):
562                 if not self._isReloading:
563                         Log.i()
564                         for fnc in self.onMethodChanged:
565                                 fnc()
566
567         def reload(self, force=True):
568                 self._isReloading = True
569                 if force:
570                         self._ipv4Changed = False
571                         self._ipv6Changed = False
572                 if not self._ipv6Changed:
573                         ip4 = self._service.ipv4()
574                         if not dict(ip4):
575                                 ip6 = self._service.ipv4Config()
576                         self._config_ip4_method.value = ip4.get(eNetworkService.KEY_METHOD, eNetworkService.METHOD_OFF)
577                         self._config_ip4_address.value = toIP4List( ip4.get("Address", "0.0.0.0") )
578                         self._config_ip4_mask.value = toIP4List( ip4.get(eNetworkService.KEY_NETMASK, "0.0.0.0") )
579                         self._config_ip4_gw.value = toIP4List( ip4.get(eNetworkService.KEY_GATEWAY, "0.0.0.0") )
580                 if not self._ipv6Changed:
581                         ip6 = self._service.ipv6()
582                         Log.i("%s / %s" %(dict(ip6), dict(self._service.ipv6Config())) )
583                         if not dict(ip6):
584                                 ip6 = self._service.ipv6Config()
585                         self._config_ip6_method.value = ip6.get(eNetworkService.KEY_METHOD, eNetworkService.METHOD_OFF)
586                         self._config_ip6_address.value = ip6.get(eNetworkService.KEY_ADDRESS, "::")
587                         self._config_ip6_prefix_length.value = ord( ip6.get(eNetworkService.KEY_PREFIX_LENGTH, chr(1)) or chr(1) )
588                         self._config_ip6_gw.value = ip6.get(eNetworkService.KEY_GATEWAY, "::")
589                         self._config_ip6_privacy.value = ip6.get(eNetworkService.KEY_PRIVACY, eNetworkService.IPV6_PRIVACY_DISABLED)
590                 self._isReloading = False
591                 self._changed(None)
592
593         def getList(self):
594                 if self._config_ip4_method.value == eNetworkService.METHOD_MANUAL:
595                         self._config_ip4_address.enabled = True
596                         self._config_ip4_mask.enabled = True
597                         self._config_ip4_gw.enabled = True
598                 else:
599                         self._config_ip4_address.enabled = False
600                         self._config_ip4_mask.enabled = False
601                         self._config_ip4_gw.enabled = False
602                 if self._config_ip6_method.value == eNetworkService.METHOD_MANUAL:
603                         self._config_ip6_address.enabled = True
604                         self._config_ip6_prefix_length.enabled = True
605                         self._config_ip6_gw.enabled = True
606                 else:
607                         self._config_ip6_address.enabled = False
608                         self._config_ip6_prefix_length.enabled = False
609                         self._config_ip6_gw.enabled = False
610
611                 l = [ getConfigListEntry(_("Method (IPv4)"), self._config_ip4_method), ]
612                 if self._config_ip4_method.value != eNetworkService.METHOD_OFF:
613                         l.extend([
614                                 getConfigListEntry(_("Address (IPv4)"), self._config_ip4_address),
615                                 getConfigListEntry(_("Mask (IPv4)"), self._config_ip4_mask),
616                                 getConfigListEntry(_("Gateway (IPv4)"), self._config_ip4_gw),
617                         ])
618                 l.append( getConfigListEntry(_("Method (IPv6)"), self._config_ip6_method))
619                 if self._config_ip6_method.value != eNetworkService.METHOD_OFF:
620                         l.extend([
621                                 getConfigListEntry(_("Address (IPv6)"), self._config_ip6_address),
622                                 getConfigListEntry(_("Prefix length (IPv6)"), self._config_ip6_prefix_length),
623                                 getConfigListEntry(_("Gateway (IPv6)"), self._config_ip6_gw),
624                         ])
625                 if self._config_ip6_method.value in (eNetworkService.METHOD_AUTO, eNetworkService.METHOD_6TO4):
626                         l.append( getConfigListEntry(_("Privacy (IPv6)"), self._config_ip6_privacy) )
627                 return l
628
629         def save(self):
630                 if self._ipv4Changed:
631                         Log.i("IPv4 Changed, saving!")
632                         if self._config_ip4_method.value == eNetworkService.METHOD_MANUAL:
633                                 ip4_config = {
634                                                 eNetworkService.KEY_METHOD : self._config_ip4_method.value,
635                                                 eNetworkService.KEY_ADDRESS : toIP4String(self._config_ip4_address),
636                                                 eNetworkService.KEY_NETMASK : toIP4String(self._config_ip4_mask),
637                                                 eNetworkService.KEY_GATEWAY : toIP4String(self._config_ip4_gw),
638                                         }
639                         else:
640                                 ip4_config = { eNetworkService.KEY_METHOD : self._config_ip4_method.value }
641                         Log.i(ip4_config)
642                         self._service.setIpv4Config(ip4_config)
643
644                 if self._ipv6Changed:
645                         Log.i("IPv6 Changed, saving!")
646                         if self._config_ip6_method.value == eNetworkService.METHOD_MANUAL:
647                                 ip6_config = {
648                                                 eNetworkService.KEY_METHOD : self._config_ip6_method.value,
649                                                 eNetworkService.KEY_ADDRESS : self._config_ip6_address.value,
650                                                 eNetworkService.KEY_PREFIX_LENGTH : self._config_ip6_prefix_length.value,
651                                                 eNetworkService.KEY_GATEWAY : self._config_ip6_gw.value,
652                                                 eNetworkService.KEY_PRIVACY : self._config_ip6_privacy.value,
653                                         }
654                         else:
655                                 val = self._config_ip6_method.value #avoid config element overhead here
656                                 #one can not configure 6to4, it will automatically be applied by connman if applicable -> change it to auto
657                                 if val == eNetworkService.METHOD_6TO4:
658                                         val = eNetworkService.METHOD_AUTO
659
660                                 ip6_config = { eNetworkService.KEY_METHOD : val }
661                                 if val != eNetworkService.METHOD_OFF:
662                                         ip6_config[eNetworkService.KEY_PRIVACY] = self._config_ip6_privacy.value
663                         Log.i(ip6_config)
664                         self._service.setIpv6Config(ip6_config)
665
666 class NetworkServiceIPConfig(ConfigListScreen, Screen, ServiceBoundConfiguration):
667         def __init__(self, session, service):
668                 Screen.__init__(self, session)
669                 ConfigListScreen.__init__(self, [], session=session)
670                 ServiceBoundConfiguration.__init__(self, service)
671
672                 self["key_blue"] = StaticText(_("Reset"))
673                 self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
674                 {
675                         "blue": self._reload,
676                         "save": self.close,
677                         "cancel": self.close,
678                         "ok" : self.close,
679                 }, -2)
680
681                 self._ipconfig = ServiceIPConfiguration(self._service)
682                 self._ipconfig.onMethodChanged.append(self._createSetup)
683                 self._noSave = False
684
685                 self._reload()
686                 self.onClose.append(self.__onClose)
687
688         def __onClose(self):
689                 self._ipconfig.onMethodChanged.remove(self._createSetup)
690                 self._apply()
691                 del self._ipconfig
692
693         def _apply(self):
694                 if self._isServiceRemoved:
695                         return
696                 self._ipconfig.save()
697
698         def _reload(self):
699                 self._ipconfig.reload()
700                 self._createSetup()
701
702         def _createSetup(self):
703                 self["config"].list = self._ipconfig.getList()
704
705 class ServiceNSConfiguration(object):
706
707         def __init__(self, service):
708                 self._service = service
709                 self.onChanged = []
710                 self._nameservers = []
711
712         def reload(self):
713                 self._nameservers = []
714                 ns = self._service.nameserversConfig()
715                 for n in ns:
716                         ip = IPAddress(n)
717                         if ip.version == 4:
718                                 cfg = ConfigIP( default=toIP4List(ip.format()))
719                                 self._nameservers.append(cfg)
720                         elif ip.version == 6:
721                                 cfg = ConfigIP6(default=ip.format())
722                                 self._nameservers.append(cfg)
723
724         def getList(self):
725                 return [ getConfigListEntry("Name server", ns) for ns in self._nameservers ]
726
727         def add4(self):
728                 self._nameservers.append(ConfigIP([0,0,0,0]))
729
730         def add6(self):
731                 self._nameservers.append(ConfigIP6())
732
733         def remove(self, cfg):
734                 self._nameservers.remove(cfg)
735
736         def save(self):
737                 servers = []
738                 for nscfg in self._nameservers:
739                         if isinstance(nscfg, ConfigIP):
740                                 servers.append(toIP4String(nscfg))
741                         elif isinstance(nscfg, ConfigIP6):
742                                 servers.append(nscfg.value)
743                 self._service.setNameserversConfig(StringList(servers))
744
745 class NetworkServiceNSConfig(ConfigListScreen, Screen, ServiceBoundConfiguration):
746
747         def __init__(self, session, service):
748                 Screen.__init__(self, session)
749                 ConfigListScreen.__init__(self, [], session=session)
750                 ServiceBoundConfiguration.__init__(self, service)
751
752                 self["key_red"] = StaticText(_("Delete"))
753                 self["key_green"] = StaticText(_("New (IPv4)"))
754                 self["key_yellow"] = StaticText(_("New (IPv6)"))
755                 self["key_blue"] = StaticText(_("Reset"))
756                 self["activedns"] = StaticText(self.getActiveDnsText())
757                 self["setupActions"] = ActionMap(["OkCancelActions", "ColorActions"],
758                 {
759                         "red": self._remove,
760                         "green": self._add4,
761                         "yellow": self._add6,
762                         "blue": self._reload,
763                         "save": self.close,
764                         "cancel": self.close,
765                         "ok" : self.close,
766                 }, -2)
767
768                 self._nsconfig = ServiceNSConfiguration(self._service)
769                 self._reload()
770                 self.onClose.append(self.__onClose)
771                 self.onLayoutFinish.append(self._layoutFinished)
772
773         def getActiveDnsText(self):
774                 nameservers = list(self._service.nameservers())
775                 text = ""
776                 if nameservers:
777                         text = _("Active name servers:\n%s") %(", ".join(nameservers))
778                         Log.i(text)
779                 return text
780
781         def _layoutFinished(self):
782                 self.setTitle(_("%s Network - Name servers" %self._service.name()))
783
784         def _remove(self):
785                 cfg = self["config"].getCurrent()
786                 if cfg:
787                         self._nsconfig.remove(cfg[1])
788                         self._createSetup()
789
790         def _add4(self):
791                 self._nsconfig.add4()
792                 self._createSetup()
793
794         def _add6(self):
795                 self._nsconfig.add6()
796                 self._createSetup()
797
798         def __onClose(self):
799                 if self._isServiceRemoved:
800                         return
801                 self._nsconfig.save()
802
803         def _reload(self):
804                 self._nsconfig.reload()
805                 self._createSetup()
806
807         def _createSetup(self):
808                 self["config"].setList( self._nsconfig.getList() )
809
810 class NetworkTimeserverConfiguration(object):
811         def __init__(self, nm):
812                 self._nm = nm
813                 self._timeservers = []
814
815         def reload(self):
816                 self._timeservers = []
817                 timeservers = list(self._nm.getTimeservers())
818                 for timeserver in timeservers:
819                         self._timeservers.append(ConfigText(default=timeserver))
820
821         def getList(self):
822                 return [ getConfigListEntry("Time server", ts) for ts in self._timeservers ]
823
824         def add(self):
825                 self._timeservers.append(ConfigText(default="0.pool.ntp.org"))
826
827         def remove(self, cfg):
828                 self._timeservers.remove(cfg)
829
830         def save(self):
831                 servers = [x.value for x in self._timeservers]
832                 self._nm.setTimeservers(StringList(servers))
833
834 class NetworkTimeserverConfig(ConfigListScreen, Screen, ServiceBoundConfiguration):
835
836         def __init__(self, session):
837                 Screen.__init__(self, session, windowTitle=_("Time server configuration"))
838                 ConfigListScreen.__init__(self, [], session=session)
839                 self.skinName = "NetworkServiceNSConfig"
840
841                 self._nm = eNetworkManager.getInstance()
842                 self._tsconfig = NetworkTimeserverConfiguration(self._nm)
843
844                 self["key_red"] = StaticText(_("Delete"))
845                 self["key_green"] = StaticText(_("New"))
846                 self["key_yellow"] = StaticText("")
847                 self["key_blue"] = StaticText(_("Reset"))
848                 self["activedns"] = StaticText(self.getActiveTimeserversText())
849                 self["setupActions"] = ActionMap(["OkCancelActions", "ColorActions"],
850                 {
851                         "red": self._remove,
852                         "green": self._add,
853                         "blue": self._reload,
854                         "save": self.close,
855                         "cancel": self.close,
856                         "ok" : self.close,
857                 }, -2)
858
859                 self["config"].onSelectionChanged.append(self._checkButtons)
860
861                 choices_timeupdates = { eNetworkManager.TIME_UPDATES_AUTO : _("auto"), eNetworkManager.TIME_UPDATES_MANUAL : _("manual") }
862                 self._config_timeupdates = ConfigSelection(choices_timeupdates, default=self._nm.timeUpdates())
863                 self._config_timeupdates.addNotifier(self._onConfigChange, initial_call=False)
864                 self.__timeservers_changed_conn = self._nm.timeserversChanged.connect(self._reload)
865
866                 self.onClose.append(self.__onClose)
867                 self._reload()
868
869         def _checkButtons(self):
870                 cfg = self["config"].getCurrent() and  self["config"].getCurrent()[1]
871                 self["key_red"].text = _("Delete") if cfg != self._config_timeupdates else ""
872
873         def _onConfigChange(self, element=None):
874                 self._nm.setTimeUpdates(self._config_timeupdates.value)
875                 self._createSetup()
876
877         def getActiveTimeserversText(self):
878                 timeservers = list(self._nm.getTimeservers())
879                 text = ""
880                 if timeservers:
881                         text = _("Active time servers:\n%s") %(", ".join(timeservers))
882                         Log.i(text)
883                 return text
884
885         def _remove(self):
886                 cfg = self["config"].getCurrent()
887                 if cfg and cfg[1] != self._config_timeupdates:
888                         self._tsconfig.remove(cfg[1])
889                         self._createSetup()
890
891         def _add(self):
892                 self._tsconfig.add()
893                 self._createSetup()
894
895         def __onClose(self):
896                 self._tsconfig.save()
897
898         def _reload(self):
899                 self._tsconfig.reload()
900                 self._createSetup()
901
902         def _createSetup(self):
903                 self["activedns"].text = self.getActiveTimeserversText()
904                 lst = [getConfigListEntry(_("NTP Time Updates"), self._config_timeupdates)]
905                 lst.extend(self._tsconfig.getList())
906                 self["config"].list = lst
907