fix startup, now starting after the network interfaces are configured
[enigma2-plugins.git] / httpproxy / src / plugin.py
1 # by 3c5x9@2008
2 from enigma import eTimer
3
4 from Screens.Screen import Screen
5
6 from Components.config import config, getConfigListEntry
7 from Components.ConfigList import ConfigListScreen
8 from Components.Label import Label
9 from Components.ActionMap import ActionMap
10 from Components.config import config, ConfigSubsection, ConfigInteger,ConfigYesNo
11 from Components.Network import iNetwork
12 from Plugins.Plugin import PluginDescriptor
13
14 from twisted.web import proxy, http
15 from twisted.internet import reactor
16
17
18 ###############################################################################
19 config.plugins.httpproxy = ConfigSubsection()
20 config.plugins.httpproxy.enable = ConfigYesNo(default = True)
21 config.plugins.httpproxy.port = ConfigInteger(8080,limits = (1, 65536))
22 config.plugins.httpproxy.filter_hosts = ConfigYesNo(default = False)
23 config.plugins.httpproxy.filter_uri = ConfigYesNo(default = False)
24
25 global ALLOWED_CLIENTS,LOG_TO_STDOUT,URI_BLACKLIST
26 LOG_TO_STDOUT = False
27 ALLOWED_CLIENTS = ['192.168.1.3'] # only clients listed here with ther IP Adress passed
28 URI_BLACKLIST = ['microsoft','teen','porn'] # all uri s containig this words will be blocked
29
30
31 ###############################################################################
32 class HTTPProxyConfigScreen(ConfigListScreen,Screen):
33     skin = """
34         <screen position="100,100" size="550,400" title="HTTP Proxy Setup" >
35         <widget name="config" position="0,0" size="550,360" scrollbarMode="showOnDemand" />
36         <widget name="buttonred" position="10,360" size="100,40" backgroundColor="red" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/>
37         <widget name="buttongreen" position="120,360" size="100,40" backgroundColor="green" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/>
38         </screen>"""
39
40     def __init__(self, session, args = 0):
41         self.session = session
42         Screen.__init__(self, session)
43         self.list = []
44         self.list.append(getConfigListEntry(_("start HTTP Proxy"), config.plugins.httpproxy.enable))
45         self.list.append(getConfigListEntry(_("use Port"), config.plugins.httpproxy.port))
46         self.list.append(getConfigListEntry(_("use Host Filter"), config.plugins.httpproxy.filter_hosts))
47         self.list.append(getConfigListEntry(_("use URI Filter"), config.plugins.httpproxy.filter_uri))
48
49         ConfigListScreen.__init__(self, self.list)
50         self["buttonred"] = Label(_("cancel"))
51         self["buttongreen"] = Label(_("ok"))
52         self["setupActions"] = ActionMap(["SetupActions"],
53         {
54             "green": self.save,
55             "red": self.cancel,
56             "save": self.save,
57             "cancel": self.cancel,
58             "ok": self.save,
59         }, -2)
60
61     def save(self):
62         print "saving"
63         for x in self["config"].list:
64             x[1].save()
65         self.close(True,self.session)
66
67     def cancel(self):
68         print "cancel"
69         for x in self["config"].list:
70             x[1].cancel()
71         self.close(False,self.session)
72
73 ###############################################################################
74
75 class myProxyRequest(proxy.ProxyRequest):
76     RESPONSE_CLIENTED_DENIED = "this client it not allowed to connect"
77     ports = {'http': 80}
78
79     def process(self):
80         global URI_BLACKLIST
81         check_passed = True
82         if config.plugins.httpproxy.filter_hosts.value is True:
83             if self.checkClientAccess(self.client) is not True:
84                 self.logMessage('BLOCKED/HOST_FILTER')
85                 self.renderResponse(self.RESPONSE_CLIENTED_DENIED)
86                 check_passed = False
87
88         if check_passed is True and config.plugins.httpproxy.filter_uri.value is True:
89             for i in URI_BLACKLIST:
90                 if self.uri.find(i) > 0:
91                     self.logMessage('BLOCKED/URI_FILTER')
92                     self.renderResponse('''<H1>Could not connect due to security issues</H1>''')
93                     check_passed = False
94                     break
95
96         if check_passed:
97             self.logMessage('OK')
98             proxy.ProxyRequest.process(self)
99
100     def renderResponse(self,message):
101         self.transport.write("HTTP/1.0 200 blocked\r\n")
102         self.transport.write("Content-Type: text/html\r\n")
103         self.transport.write("\r\n")
104         self.transport.write('<H1>%s</H1>'%message)
105         self.transport.stopProducing()
106
107     def checkClientAccess(self,client):
108         global ALLOWED_CLIENTS
109         if client.host not in ALLOWED_CLIENTS:
110             return False
111         else:
112             return True
113
114     def logMessage(self,status):
115         global LOG_TO_STDOUT
116         if LOG_TO_STDOUT:
117             try:
118                 print "[PROXY]",self.client.host,self.uri,status
119             except Exception:
120                 ''' now i am quite careful with logging webstuff with E2 '''
121                 pass
122
123 class ProxyProtocol(proxy.Proxy):
124     requestFactory = myProxyRequest
125
126 class ProxyFactory(http.HTTPFactory):
127         protocol = ProxyProtocol
128
129 ###############################################################################
130 def main(session, **kwargs):
131     """ open config screen """
132     session.open(HTTPProxyConfigScreen)
133
134 def autostart(reason,**kwargs):
135     """ start proxy in background """
136     if reason is True and config.plugins.httpproxy.enable.value is True:
137         try:
138             for adaptername in iNetwork.ifaces:
139                 extip = iNetwork.ifaces[adaptername]['ip']
140                 if iNetwork.ifaces[adaptername]['up'] is True:
141                     extip = "%i.%i.%i.%i" % (extip[0], extip[1], extip[2], extip[3])
142                     print "starting proxy on ",extip,":", config.plugins.httpproxy.port.value
143                     reactor.listenTCP(int(config.plugins.httpproxy.port.value), ProxyFactory(),interface=extip)
144         except Exception,e:
145             print "starting the http proxy failed!"
146             print e
147
148
149 def Plugins(**kwargs):
150   return [
151           PluginDescriptor(name="HTTP Proxy",description="use your Dreambox as Web Proxy",where = PluginDescriptor.WHERE_PLUGINMENU,fnc = main),
152           PluginDescriptor(where = [PluginDescriptor.WHERE_NETWORKCONFIG_READ], fnc = autostart)
153           ]
154