forked from robin-wittler/massive-passive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmassive-passive-server
executable file
·219 lines (183 loc) · 6.77 KB
/
massive-passive-server
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'Robin Wittler'
__contact__ = '[email protected]'
__license__ = 'GPL3+'
__copyright__ = '(c) 2013 by mysportgroup.de'
__version__ = '0.3.9'
import os
import sys
import signal
import logging
from threading import Event
from pyinotify import IN_DELETE
from pyinotify import IN_CREATE
from pyinotify import IN_MOVED_TO
from mplib.daemon import daemonize
from pyinotify import IN_MOVED_FROM
from twisted.internet import reactor
from pyinotify import IN_CLOSE_WRITE
from setproctitle import setproctitle
from mplib.inotify import WatchManager
from mplib.getopts import get_gpl3_text
from mplib.log import BASE_FORMAT_STDOUT
from mplib.net.server import SSLCallbacks
from mplib.inotify import ThreadedNotifier
from mplib.inotify import ProcessPemEvents
from mplib.log import set_logfile_permissions
from mplib.getopts.server import server_getopt
from logging.handlers import WatchedFileHandler
from mplib.net.server import SSLValidationStore
from mplib.net.server import SSLServerContextFactory
from mplib.getopts.server import get_server_description
from mplib.net.server import ExternalCommandWriterFactory
logger = logging.getLogger(__name__)
class Main(object):
def __init__(self, name, options):
super(Main, self).__init__()
self.name = name
self.logger = logging.getLogger(
'%s.%s' %(
self.name,
self.__class__.__name__
)
)
self.options = options
if not os.access(self.options.allowed_client_cert_dir, os.R_OK|os.X_OK):
raise RuntimeError(
'Can not access %r with mode rx.',
self.options.allowed_client_cert_dir
)
self.stop_event = Event()
self.factory = ExternalCommandWriterFactory(
self.options.command_file,
)
self.ssl_validation_store = SSLValidationStore(
self.options.allowed_client_cert_dir,
self.options.ssl_ca_cert
)
self.ssl_callback = SSLCallbacks(self.ssl_validation_store)
self.ssl_factory = SSLServerContextFactory(
self.options.ssl_key,
self.options.ssl_cert,
self.options.ssl_ca_cert,
checkCallback=self.ssl_callback.verifyCallback
)
self.watch_manager = WatchManager()
callbacks = {
'IN_CLOSE_WRITE': self.add_pem_from_event,
'IN_CREATE': self.add_pem_from_event,
'IN_MOVED_TO': self.add_pem_from_event,
'IN_MOVED_FROM': self.remove_pem_from_event,
'IN_DELETE': self.remove_pem_from_event,
}
self.notifier = ThreadedNotifier(
self.watch_manager,
default_proc_fun=ProcessPemEvents(callbacks=callbacks)
)
self.watch_manager.add_watch(
options.allowed_client_cert_dir,
IN_CLOSE_WRITE|IN_DELETE|IN_CREATE|IN_MOVED_TO|IN_MOVED_FROM,
rec=False,
auto_add=True
)
def add_pem_from_event(self, event):
return self.ssl_validation_store.add_pem(event.pathname)
def remove_pem_from_event(self, event):
return self.ssl_validation_store.remove_pem(event.pathname)
def run(self):
self.logger.info('Startup!')
self.set_proc_title()
if self.options.foreground is False:
self.drop_rights()
self.write_pidfile()
self.notifier.start()
context = self.ssl_factory.buildContext()
reactor.listenSSL(
self.options.port,
self.factory,
self.ssl_factory,
interface=self.options.listen
)
reactor.run()
def set_proc_title(self):
setproctitle(
'%s %s' %(sys.argv[0], ' '.join(sys.argv[1:]))
)
def write_pidfile(self):
pid = os.getpid()
pidfile_fd = os.open(
self.options.pidfile,
os.O_CREAT | os.O_EXCL | os.O_RDWR,
0640
)
pidfile = os.fdopen(pidfile_fd, 'w+')
pidfile.write('%s\n' %(pid,))
pidfile.flush()
os.close(pidfile_fd)
def drop_rights(self):
current_uid = os.getuid()
current_gid = os.getgid()
if not options.group == current_gid:
self.logger.debug('Switching group to %r', options.group)
os.setgid(options.group)
os.setegid(options.group)
if not options.user == current_uid:
self.logger.debug('Switching user to %r', options.user)
os.setuid(options.user)
os.seteuid(options.user)
def start(self):
try:
self.run()
except Exception as error:
self.logger.exception(error)
self.logger.info('Emitting stop signal ...')
os.kill(os.getpid(), signal.SIGTERM)
def config_reload(self, signum, sigframe):
self.logger.info(
'Received Signal %s ... reloading config now ...', signum
)
self.logger.info('Config reload done.')
def shutdown(self, signum, sigframe):
self.logger.info('Received Signal %s.', signum)
self.logger.info('Going down now ...')
self.stop_event.set()
self.logger.debug('Stop Event set.')
self.logger.info('Stopping notifier ...')
self.notifier.stop()
self.logger.info('Notifier stopped.')
self.logger.debug('Stopping reactor ...')
reactor.stop()
if self.options.foreground is False:
self.logger.debug('Removing pidfile at %r', self.options.pidfile)
try:
os.unlink(self.options.pidfile)
except OSError as error:
self.logger.debug('Ignoring error while unlinking pidfile.')
self.logger.exception(error)
self.logger.info('Exiting now!')
if __name__ == '__main__':
options, args = server_getopt(
version='%prog ' + __version__,
description=get_server_description(),
epilog=get_gpl3_text()
)
logging.basicConfig(level=options.loglevel, format=BASE_FORMAT_STDOUT)
root_logger = logging.getLogger('')
if options.foreground is False:
daemonize(cwd='/')
main = Main(sys.argv[0], options)
main.drop_rights()
filehandler = WatchedFileHandler(options.logfile)
filehandler.setLevel(options.loglevel)
filehandler_formatter = logging.Formatter(BASE_FORMAT_STDOUT)
filehandler.setFormatter(filehandler_formatter)
root_logger.addHandler(filehandler)
root_logger.setLevel(options.loglevel)
set_logfile_permissions(options.logfile)
signal.signal(signal.SIGTERM, main.shutdown)
signal.signal(signal.SIGINT, main.shutdown)
signal.signal(signal.SIGHUP, main.config_reload)
main.start()
sys.exit(0)
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4