1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#!/usr/bin/env python
###########################################################################
# Copyright (c) 2018- Franco (nextime) Lanza <franco@nexlab.it>
#
# Penguidom System client Daemon "penguidomd" [https://git.nexlab.net/domotika/Penguidom]
#
# This file is part of penguidom.
#
# penguidom is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from twisted.internet import epollreactor
epollreactor.install()
from twisted.internet import reactor, ssl, protocol, endpoints
from twisted.application import service, internet, app, reactors
from twisted.web import server
import logging, time, sys, os
from nexlibs.daemonizer import Daemonizer
from penguidom import penguidom
from nexlibs.utils.genutils import configFile
from logging import handlers as loghandlers
try:
import setproctitle
setproctitle.setproctitle('penguidomd')
print 'Setting process title to', sys.argv[0]
except:
pass
loglevels = {
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL,
'debug': logging.DEBUG
}
#LOGLEN=104857600 # 100 mega
#LOGLEN=10485760 # 10 mega
LOGLEN=26214400 # 25 mega
from OpenSSL import SSL
class PenguiSSLContext(ssl.DefaultOpenSSLContextFactory):
def cacheContext(self):
if self._context is None:
ctx = self._contextFactory(self.sslmethod)
# Disallow SSLv2! It's insecure! SSLv3 has been around since
# 1996. It's time to move on.
ctx.set_options(SSL.OP_NO_SSLv2)
ctx.use_certificate_chain_file(self.certificateFileName)
ctx.use_privatekey_file(self.privateKeyFileName)
self._context = ctx
class penguidomDaemon(Daemonizer):
def __init__(self):
self.curdir = os.path.abspath(os.path.dirname(sys.argv[0]))
log.debug("Reading daemon Config file")
self.daemoncfg = configFile(self.curdir+'/conf/penguidomd.conf')
self.daemoncfg.readConfig()
log.debug("Daemonizing process")
Daemonizer.__init__(self, self.curdir+'/run/penguidom.pid')
def main_loop(self):
log.debug("Main loop called")
application = service.Application("penguidomd")
PENGUIDOMServerService = penguidom.penguidomService('penguidomd', curdir=self.curdir, config=self.daemoncfg)
serviceCollection = service.IServiceCollection(application)
PENGUIDOMServerService.setServiceParent(serviceCollection)
IkapServerUDP = PENGUIDOMServerService.getIkapUDP()
IkapServerTCP = PENGUIDOMServerService.getIkapTCP()
WebAuthServer = PENGUIDOMServerService.getAuthWebServer()
privkey = self.daemoncfg.get('web', 'privkey')
cacert = self.daemoncfg.get('web', 'cacert')
if not privkey.startswith('/'): privkey="/".join([self.curdir, privkey])
if not cacert.startswith('/'): cacert="/".join([self.curdir, cacert])
sslContext = PenguiSSLContext(privkey, cacert)
if str(self.daemoncfg.get('web', 'enable')).lower() in ['yes', '1', 'y','true']:
reactor.listenSSL(int(self.daemoncfg.get('web', 'sslport')), WebAuthServer,
contextFactory=sslContext,
interface=str(self.daemoncfg.get('web', 'interface')))
if not str(self.daemoncfg.get('web', 'sslonly')).lower() in ['yes', '1', 'y','true']:
reactor.listenTCP(int(self.daemoncfg.get('web', 'port')), WebAuthServer,
interface=str(self.daemoncfg.get('web', 'interface')))
if str(self.daemoncfg.get('ikap', 'enable')).lower() in ['yes', '1', 'y','true']:
reactor.listenUDP(int(self.daemoncfg.get('ikap', 'port')), IkapServerUDP,
interface=str(self.daemoncfg.get('ikap', 'interface')))
if self.daemoncfg.get('ikap', 'port') != self.daemoncfg.get('ikap', 'notifyport'):
reactor.listenUDP(int(self.daemoncfg.get('ikap', 'notifyport')), IkapServerUDP,
interface=str(self.daemoncfg.get('ikap', 'interface')))
if str(self.daemoncfg.get('ikap', 'tcpenable')).lower() in ['yes', '1', 'y','true']:
reactor.listenTCP(int(self.daemoncfg.get('ikap', 'tcpport')), IkapServerTCP,
interface=str(self.daemoncfg.get('ikap', 'tcpinterface')))
log.debug("Running reactor")
reactor.callWhenRunning(PENGUIDOMServerService.isStarted)
reactor.run()
if __name__ == "__main__":
# Starting all loggers
# file di log da 100 mega, per 5 rotazioni
LOGFORMAT='%(asctime)s => %(name)-12s: %(levelname)-8s %(message)s'
formatter = logging.Formatter(LOGFORMAT)
logdict={"corelog":
{"file":"penguidom.log","name":[("Core","general")]},
"weblog":
{"file":"web.log","name":[("Webgui","web")]},
"pluginslog":
{"file":"plugins.log","name":[("Plugins","plugins")]},
"protocollog":
{"file":"ikap.log","name":
[("IKAProtocol","ikap"),("IKAPServer","ikap"),("DMDomain","ikap")]},
}
for l in logdict.keys():
logdict[l]["handler"] = loghandlers.RotatingFileHandler(
os.path.abspath(os.path.dirname(sys.argv[0]))+'/logs/'+logdict[l]["file"], 'a', LOGLEN, 5)
logdict[l]["handler"].setLevel(logging.DEBUG)
logdict[l]["handler"].setFormatter(formatter)
logging.basicConfig(format=LOGFORMAT)
log = logging.getLogger( 'DaemonStarter' )
log.addHandler(logdict["corelog"]["handler"])
log.setLevel( logging.INFO )
curdir = os.path.abspath(os.path.dirname(sys.argv[0]))
daemoncfg = configFile(curdir+'/conf/penguidomd.conf')
daemoncfg.readConfig()
for l in logdict.keys():
for n in logdict[l]["name"]:
lh = logging.getLogger(n[0])
lh.setLevel( loglevels[daemoncfg.get(n[1], 'loglevel')] )
lh.addHandler( logdict[l]["handler"] )
logging.basicConfig(format=LOGFORMAT)
# staring the application
if len(sys.argv) > 1:
log.debug("Starting daemon with option "+sys.argv[1])
penguidomDaemon().process_command_line(sys.argv)
else:
print 'Please specify start, stop or debug option'