root / vncauthproxy / proxy.py @ dd62f34b
History | View | Annotate | Download (25.1 kB)
1 |
#!/usr/bin/env python
|
---|---|
2 |
"""
|
3 |
vncauthproxy - a VNC authentication proxy
|
4 |
"""
|
5 |
#
|
6 |
# Copyright (c) 2010-2013 Greek Research and Technology Network S.A.
|
7 |
#
|
8 |
# This program is free software; you can redistribute it and/or modify
|
9 |
# it under the terms of the GNU General Public License as published by
|
10 |
# the Free Software Foundation; either version 2 of the License, or
|
11 |
# (at your option) any later version.
|
12 |
#
|
13 |
# This program is distributed in the hope that it will be useful, but
|
14 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
15 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
16 |
# General Public License for more details.
|
17 |
#
|
18 |
# You should have received a copy of the GNU General Public License
|
19 |
# along with this program; if not, write to the Free Software
|
20 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
21 |
# 02110-1301, USA.
|
22 |
|
23 |
# Daemon files
|
24 |
DEFAULT_LOG_FILE = "/var/log/vncauthproxy/vncauthproxy.log"
|
25 |
DEFAULT_PID_FILE = "/var/run/vncauthproxy/vncauthproxy.pid"
|
26 |
|
27 |
# By default, bind / listen for control connections to TCP *:24999
|
28 |
# (both IPv4 and IPv6)
|
29 |
DEFAULT_LISTEN_ADDRESS = None
|
30 |
DEFAULT_LISTEN_PORT = 24999
|
31 |
|
32 |
# Backlog for the control socket
|
33 |
DEFAULT_BACKLOG = 256
|
34 |
|
35 |
# Timeout for the VNC server connection establishment / RFB handshake
|
36 |
DEFAULT_SERVER_TIMEOUT = 60.0
|
37 |
|
38 |
# Connect retries and delay between retries for the VNC server socket
|
39 |
DEFAULT_CONNECT_RETRIES = 3
|
40 |
DEFAULT_RETRY_WAIT = 0.1
|
41 |
|
42 |
# Connect timeout for the listening sockets
|
43 |
DEFAULT_CONNECT_TIMEOUT = 30
|
44 |
|
45 |
# Port range for the listening sockets
|
46 |
#
|
47 |
# We must take care not to fall into the ephemeral port range,
|
48 |
# this can lead to transient failures to bind a chosen port.
|
49 |
#
|
50 |
# By default, Linux uses 32768 to 61000, see:
|
51 |
# http://www.ncftp.com/ncftpd/doc/misc/ephemeral_ports.html#Linux
|
52 |
# so 25000-30000 seems to be a sensible default.
|
53 |
#
|
54 |
# We also take into account the ports that Ganeti daemons bind to, the port
|
55 |
# range used by DRBD etc.
|
56 |
DEFAULT_MIN_PORT = 25000
|
57 |
DEFAULT_MAX_PORT = 30000
|
58 |
|
59 |
import os |
60 |
import sys |
61 |
import logging |
62 |
import gevent |
63 |
import gevent.event |
64 |
import daemon |
65 |
import random |
66 |
import daemon.runner |
67 |
|
68 |
import rfb |
69 |
|
70 |
try:
|
71 |
import simplejson as json |
72 |
except ImportError: |
73 |
import json |
74 |
|
75 |
from gevent import socket |
76 |
from signal import SIGINT, SIGTERM |
77 |
from gevent.select import select |
78 |
|
79 |
from lockfile import LockTimeout, AlreadyLocked |
80 |
# Take care of differences between python-daemon versions.
|
81 |
try:
|
82 |
from daemon import pidfile as pidlockfile |
83 |
except:
|
84 |
from daemon import pidlockfile |
85 |
|
86 |
|
87 |
logger = None
|
88 |
|
89 |
|
90 |
# Currently, gevent uses libevent-dns for asynchronous DNS resolution,
|
91 |
# which opens a socket upon initialization time. Since we can't get the fd
|
92 |
# reliably, We have to maintain all file descriptors open (which won't harm
|
93 |
# anyway)
|
94 |
class AllFilesDaemonContext(daemon.DaemonContext): |
95 |
"""DaemonContext class keeping all file descriptors open"""
|
96 |
def _get_exclude_file_descriptors(self): |
97 |
class All: |
98 |
def __contains__(self, value): |
99 |
return True |
100 |
return All()
|
101 |
|
102 |
|
103 |
class VncAuthProxy(gevent.Greenlet): |
104 |
"""
|
105 |
Simple class implementing a VNC Forwarder with MITM authentication as a
|
106 |
Greenlet
|
107 |
|
108 |
VncAuthProxy forwards VNC traffic from a specified port of the local host
|
109 |
to a specified remote host:port. Furthermore, it implements VNC
|
110 |
Authentication, intercepting the client/server handshake and asking the
|
111 |
client for authentication even if the backend requires none.
|
112 |
|
113 |
It is primarily intended for use in virtualization environments, as a VNC
|
114 |
``switch''.
|
115 |
|
116 |
"""
|
117 |
id = 1
|
118 |
|
119 |
def __init__(self, logger, client): |
120 |
"""
|
121 |
@type logger: logging.Logger
|
122 |
@param logger: the logger to use
|
123 |
@type client: socket.socket
|
124 |
@param listeners: the client control connection socket
|
125 |
|
126 |
"""
|
127 |
gevent.Greenlet.__init__(self)
|
128 |
self.id = VncAuthProxy.id
|
129 |
VncAuthProxy.id += 1
|
130 |
self.log = logger
|
131 |
self.client = client
|
132 |
# A list of worker/forwarder greenlets, one for each direction
|
133 |
self.workers = []
|
134 |
self.sport = None |
135 |
self.pool = None |
136 |
self.daddr = None |
137 |
self.dport = None |
138 |
self.server = None |
139 |
self.password = None |
140 |
|
141 |
def _cleanup(self): |
142 |
"""Cleanup everything: workers, sockets, ports
|
143 |
|
144 |
Kill all remaining forwarder greenlets, close all active sockets,
|
145 |
return the source port to the pool if applicable, then exit
|
146 |
gracefully.
|
147 |
|
148 |
"""
|
149 |
# Make sure all greenlets are dead, then clean them up
|
150 |
self.debug("Cleaning up %d workers", len(self.workers)) |
151 |
for g in self.workers: |
152 |
g.kill() |
153 |
gevent.joinall(self.workers)
|
154 |
del self.workers |
155 |
|
156 |
self.debug("Cleaning up sockets") |
157 |
while self.listeners: |
158 |
self.listeners.pop().close()
|
159 |
if self.server: |
160 |
self.server.close()
|
161 |
if self.client: |
162 |
self.client.close()
|
163 |
|
164 |
# Reintroduce the port number of the client socket in
|
165 |
# the port pool, if applicable.
|
166 |
if not self.pool is None: |
167 |
self.pool.append(self.sport) |
168 |
self.debug("Returned port %d to port pool, contains %d ports", |
169 |
self.sport, len(self.pool)) |
170 |
|
171 |
self.info("Cleaned up connection, all done") |
172 |
raise gevent.GreenletExit
|
173 |
|
174 |
def __str__(self): |
175 |
return "VncAuthProxy: %d -> %s:%d" % (self.sport, self.daddr, |
176 |
self.dport)
|
177 |
|
178 |
def _forward(self, source, dest): |
179 |
"""
|
180 |
Forward traffic from source to dest
|
181 |
|
182 |
@type source: socket
|
183 |
@param source: source socket
|
184 |
@type dest: socket
|
185 |
@param dest: destination socket
|
186 |
|
187 |
"""
|
188 |
|
189 |
while True: |
190 |
d = source.recv(16384)
|
191 |
if d == '': |
192 |
if source == self.client: |
193 |
self.info("Client connection closed") |
194 |
else:
|
195 |
self.info("Server connection closed") |
196 |
break
|
197 |
dest.sendall(d) |
198 |
# No need to close the source and dest sockets here.
|
199 |
# They are owned by and will be closed by the original greenlet.
|
200 |
|
201 |
def _perform_server_handshake(self): |
202 |
"""
|
203 |
Initiate a connection with the backend server and perform basic
|
204 |
RFB 3.8 handshake with it.
|
205 |
|
206 |
Return a socket connected to the backend server.
|
207 |
|
208 |
"""
|
209 |
server = None
|
210 |
|
211 |
tries = VncAuthProxy.connect_retries |
212 |
while tries:
|
213 |
tries -= 1
|
214 |
|
215 |
# Initiate server connection
|
216 |
for res in socket.getaddrinfo(self.daddr, self.dport, |
217 |
socket.AF_UNSPEC, |
218 |
socket.SOCK_STREAM, 0,
|
219 |
socket.AI_PASSIVE): |
220 |
af, socktype, proto, canonname, sa = res |
221 |
try:
|
222 |
server = socket.socket(af, socktype, proto) |
223 |
except socket.error:
|
224 |
server = None
|
225 |
continue
|
226 |
|
227 |
# Set socket timeout for the initial handshake
|
228 |
server.settimeout(VncAuthProxy.server_timeout) |
229 |
|
230 |
try:
|
231 |
self.debug("Connecting to %s:%s", *sa[:2]) |
232 |
server.connect(sa) |
233 |
self.debug("Connection to %s:%s successful", *sa[:2]) |
234 |
except socket.error:
|
235 |
server.close() |
236 |
server = None
|
237 |
continue
|
238 |
|
239 |
# We succesfully connected to the server
|
240 |
tries = 0
|
241 |
break
|
242 |
|
243 |
# Wait and retry
|
244 |
gevent.sleep(VncAuthProxy.retry_wait) |
245 |
|
246 |
if server is None: |
247 |
raise Exception("Failed to connect to server") |
248 |
|
249 |
version = server.recv(1024)
|
250 |
if not rfb.check_version(version): |
251 |
raise Exception("Unsupported RFB version: %s" % version.strip()) |
252 |
|
253 |
server.send(rfb.RFB_VERSION_3_8 + "\n")
|
254 |
|
255 |
res = server.recv(1024)
|
256 |
types = rfb.parse_auth_request(res) |
257 |
if not types: |
258 |
raise Exception("Error handshaking with the server") |
259 |
|
260 |
else:
|
261 |
self.debug("Supported authentication types: %s", |
262 |
" ".join([str(x) for x in types])) |
263 |
|
264 |
if rfb.RFB_AUTHTYPE_NONE not in types: |
265 |
raise Exception("Error, server demands authentication") |
266 |
|
267 |
server.send(rfb.to_u8(rfb.RFB_AUTHTYPE_NONE)) |
268 |
|
269 |
# Check authentication response
|
270 |
res = server.recv(4)
|
271 |
res = rfb.from_u32(res) |
272 |
|
273 |
if res != 0: |
274 |
raise Exception("Authentication error") |
275 |
|
276 |
# Reset the timeout for the rest of the session
|
277 |
server.settimeout(None)
|
278 |
|
279 |
self.server = server
|
280 |
|
281 |
def _establish_connection(self): |
282 |
client = self.client
|
283 |
ports = VncAuthProxy.ports |
284 |
|
285 |
# Receive and parse a client request.
|
286 |
response = { |
287 |
"source_port": 0, |
288 |
"status": "FAILED", |
289 |
} |
290 |
try:
|
291 |
# TODO: support multiple forwardings in the same message?
|
292 |
#
|
293 |
# Control request, in JSON:
|
294 |
#
|
295 |
# {
|
296 |
# "source_port":
|
297 |
# <source port or 0 for automatic allocation>,
|
298 |
# "destination_address":
|
299 |
# <destination address of backend server>,
|
300 |
# "destination_port":
|
301 |
# <destination port>
|
302 |
# "password":
|
303 |
# <the password to use to authenticate clients>
|
304 |
# }
|
305 |
#
|
306 |
# The <password> is used for MITM authentication of clients
|
307 |
# connecting to <source_port>, who will subsequently be
|
308 |
# forwarded to a VNC server listening at
|
309 |
# <destination_address>:<destination_port>
|
310 |
#
|
311 |
# Control reply, in JSON:
|
312 |
# {
|
313 |
# "source_port": <the allocated source port>
|
314 |
# "status": <one of "OK" or "FAILED">
|
315 |
# }
|
316 |
#
|
317 |
buf = client.recv(1024)
|
318 |
req = json.loads(buf) |
319 |
|
320 |
sport_orig = int(req['source_port']) |
321 |
self.daddr = req['destination_address'] |
322 |
self.dport = int(req['destination_port']) |
323 |
self.password = req['password'] |
324 |
except Exception, e: |
325 |
self.warn("Malformed request: %s", buf) |
326 |
client.send(json.dumps(response)) |
327 |
client.close() |
328 |
raise gevent.GreenletExit
|
329 |
|
330 |
server = None
|
331 |
try:
|
332 |
# If the client has so indicated, pick an ephemeral source port
|
333 |
# randomly, and remove it from the port pool.
|
334 |
if sport_orig == 0: |
335 |
while True: |
336 |
try:
|
337 |
sport = random.choice(ports) |
338 |
ports.remove(sport) |
339 |
break
|
340 |
except ValueError: |
341 |
self.debug("Port %d already taken", sport) |
342 |
|
343 |
self.debug("Got port %d from pool, %d remaining", |
344 |
sport, len(ports))
|
345 |
pool = ports |
346 |
else:
|
347 |
sport = sport_orig |
348 |
pool = None
|
349 |
|
350 |
self.sport = sport
|
351 |
self.pool = pool
|
352 |
|
353 |
self.listeners = get_listening_sockets(self, sport) |
354 |
self._perform_server_handshake()
|
355 |
|
356 |
self.info("New forwarding: %d (client req'd: %d) -> %s:%d", |
357 |
sport, sport_orig, self.daddr, self.dport) |
358 |
response = {"source_port": sport,
|
359 |
"status": "OK"} |
360 |
except IndexError: |
361 |
self.error(("FAILED forwarding, out of ports for [req'd by " |
362 |
"client: %d -> %s:%d]"),
|
363 |
sport_orig, self.daddr, self.dport) |
364 |
raise gevent.GreenletExit
|
365 |
except Exception, msg: |
366 |
self.error(msg)
|
367 |
self.error(("FAILED forwarding: %d (client req'd: %d) -> " |
368 |
"%s:%d"), sport, sport_orig, self.daddr, self.dport) |
369 |
if not pool is None: |
370 |
pool.append(sport) |
371 |
self.debug("Returned port %d to pool, %d remanining", |
372 |
sport, len(pool))
|
373 |
if not server is None: |
374 |
server.close() |
375 |
raise gevent.GreenletExit
|
376 |
finally:
|
377 |
client.send(json.dumps(response)) |
378 |
client.close() |
379 |
|
380 |
def _client_handshake(self): |
381 |
"""
|
382 |
Perform handshake/authentication with a connecting client
|
383 |
|
384 |
Outline:
|
385 |
1. Client connects
|
386 |
2. We fake RFB 3.8 protocol and require VNC authentication
|
387 |
[processing also supports RFB 3.3]
|
388 |
3. Client accepts authentication method
|
389 |
4. We send an authentication challenge
|
390 |
5. Client sends the authentication response
|
391 |
6. We check the authentication
|
392 |
|
393 |
Upon return, self.client socket is connected to the client.
|
394 |
|
395 |
"""
|
396 |
self.client.send(rfb.RFB_VERSION_3_8 + "\n") |
397 |
client_version_str = self.client.recv(1024) |
398 |
client_version = rfb.check_version(client_version_str) |
399 |
if not client_version: |
400 |
self.error("Invalid version: %s", client_version_str) |
401 |
raise gevent.GreenletExit
|
402 |
|
403 |
# Both for RFB 3.3 and 3.8
|
404 |
self.debug("Requesting authentication") |
405 |
auth_request = rfb.make_auth_request(rfb.RFB_AUTHTYPE_VNC, |
406 |
version=client_version) |
407 |
self.client.send(auth_request)
|
408 |
|
409 |
# The client gets to propose an authtype only for RFB 3.8
|
410 |
if client_version == rfb.RFB_VERSION_3_8:
|
411 |
res = self.client.recv(1024) |
412 |
type = rfb.parse_client_authtype(res) |
413 |
if type == rfb.RFB_AUTHTYPE_ERROR:
|
414 |
self.warn("Client refused authentication: %s", res[1:]) |
415 |
else:
|
416 |
self.debug("Client requested authtype %x", type) |
417 |
|
418 |
if type != rfb.RFB_AUTHTYPE_VNC: |
419 |
self.error("Wrong auth type: %d", type) |
420 |
self.client.send(rfb.to_u32(rfb.RFB_AUTH_ERROR))
|
421 |
raise gevent.GreenletExit
|
422 |
|
423 |
# Generate the challenge
|
424 |
challenge = os.urandom(16)
|
425 |
self.client.send(challenge)
|
426 |
response = self.client.recv(1024) |
427 |
if len(response) != 16: |
428 |
self.error("Wrong response length %d, should be 16", len(response)) |
429 |
raise gevent.GreenletExit
|
430 |
|
431 |
if rfb.check_password(challenge, response, self.password): |
432 |
self.debug("Authentication successful") |
433 |
else:
|
434 |
self.warn("Authentication failed") |
435 |
self.client.send(rfb.to_u32(rfb.RFB_AUTH_ERROR))
|
436 |
raise gevent.GreenletExit
|
437 |
|
438 |
# Accept the authentication
|
439 |
self.client.send(rfb.to_u32(rfb.RFB_AUTH_SUCCESS))
|
440 |
|
441 |
def _proxy(self): |
442 |
try:
|
443 |
self.info("Waiting for a client to connect at %s", |
444 |
", ".join(["%s:%d" % s.getsockname()[:2] |
445 |
for s in self.listeners])) |
446 |
rlist, _, _ = select(self.listeners, [], [],
|
447 |
timeout=VncAuthProxy.connect_timeout) |
448 |
if not rlist: |
449 |
self.info("Timed out, no connection after %d sec", |
450 |
VncAuthProxy.connect_timeout) |
451 |
raise gevent.GreenletExit
|
452 |
|
453 |
for sock in rlist: |
454 |
self.client, addrinfo = sock.accept()
|
455 |
self.info("Connection from %s:%d", *addrinfo[:2]) |
456 |
|
457 |
# Close all listening sockets, we only want a one-shot
|
458 |
# connection from a single client.
|
459 |
while self.listeners: |
460 |
self.listeners.pop().close()
|
461 |
break
|
462 |
|
463 |
# Perform RFB handshake with the client.
|
464 |
self._client_handshake()
|
465 |
|
466 |
# Bridge both connections through two "forwarder" greenlets.
|
467 |
# This greenlet will wait until any of the workers dies.
|
468 |
# Final cleanup will take place in _cleanup().
|
469 |
dead = gevent.event.Event() |
470 |
dead.clear() |
471 |
|
472 |
# This callback will get called if any of the two workers dies.
|
473 |
def callback(g): |
474 |
self.debug("Worker %d/%d died", self.workers.index(g), |
475 |
len(self.workers)) |
476 |
dead.set() |
477 |
|
478 |
self.workers.append(gevent.spawn(self._forward, |
479 |
self.client, self.server)) |
480 |
self.workers.append(gevent.spawn(self._forward, |
481 |
self.server, self.client)) |
482 |
for g in self.workers: |
483 |
g.link(callback) |
484 |
|
485 |
# Wait until any of the workers dies
|
486 |
self.debug("Waiting for any of %d workers to die", |
487 |
len(self.workers)) |
488 |
dead.wait() |
489 |
|
490 |
# We can go now, _cleanup() will take care of
|
491 |
# all worker, socket and port cleanup
|
492 |
self.debug("A forwarder died, our work here is done") |
493 |
raise gevent.GreenletExit
|
494 |
except Exception, e: |
495 |
# Any unhandled exception in the previous block
|
496 |
# is an error and must be logged accordingly
|
497 |
if not isinstance(e, gevent.GreenletExit): |
498 |
self.exception(e)
|
499 |
raise e
|
500 |
finally:
|
501 |
self._cleanup()
|
502 |
|
503 |
def _run(self): |
504 |
self._establish_connection()
|
505 |
self._proxy()
|
506 |
|
507 |
# Logging support inside VncAuthproxy
|
508 |
# Wrap all common logging functions in logging-specific methods
|
509 |
for funcname in ["info", "debug", "warn", "error", "critical", |
510 |
"exception"]:
|
511 |
|
512 |
def gen(funcname): |
513 |
def wrapped_log_func(self, *args, **kwargs): |
514 |
func = getattr(self.log, funcname) |
515 |
func("[C%d] %s" % (self.id, args[0]), *args[1:], **kwargs) |
516 |
return wrapped_log_func
|
517 |
setattr(VncAuthProxy, funcname, gen(funcname))
|
518 |
|
519 |
|
520 |
def fatal_signal_handler(signame): |
521 |
logger.info("Caught %s, will raise SystemExit", signame)
|
522 |
raise SystemExit |
523 |
|
524 |
|
525 |
def get_listening_sockets(logger, sport, saddr=None): |
526 |
sockets = [] |
527 |
|
528 |
# Use two sockets, one for IPv4, one for IPv6. IPv4-to-IPv6 mapped
|
529 |
# addresses do not work reliably everywhere (under linux it may have
|
530 |
# been disabled in /proc/sys/net/ipv6/bind_ipv6_only).
|
531 |
for res in socket.getaddrinfo(saddr, sport, socket.AF_UNSPEC, |
532 |
socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
|
533 |
af, socktype, proto, canonname, sa = res |
534 |
try:
|
535 |
s = None
|
536 |
s = socket.socket(af, socktype, proto) |
537 |
if af == socket.AF_INET6:
|
538 |
# Bind v6 only when AF_INET6, otherwise either v4 or v6 bind
|
539 |
# will fail.
|
540 |
s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
|
541 |
s.bind(sa) |
542 |
s.listen(1)
|
543 |
sockets.append(s) |
544 |
logger.debug("Listening on %s:%d", *sa[:2]) |
545 |
except socket.error, msg:
|
546 |
logger.error("Error binding to %s:%d: %s", sa[0], sa[1], msg[1]) |
547 |
if s:
|
548 |
s.close() |
549 |
while sockets:
|
550 |
sockets.pop().close() |
551 |
|
552 |
# Make sure we fail immediately if we cannot get a socket
|
553 |
raise msg
|
554 |
|
555 |
return sockets
|
556 |
|
557 |
|
558 |
def parse_arguments(args): |
559 |
from optparse import OptionParser |
560 |
|
561 |
parser = OptionParser() |
562 |
parser.add_option("-d", "--debug", action="store_true", dest="debug", |
563 |
help="Enable debugging information")
|
564 |
parser.add_option("--log", dest="log_file", |
565 |
default=DEFAULT_LOG_FILE, |
566 |
metavar="FILE",
|
567 |
help=("Write log to FILE (default: %s)" %
|
568 |
DEFAULT_LOG_FILE)) |
569 |
parser.add_option('--pid-file', dest="pid_file", |
570 |
default=DEFAULT_PID_FILE, |
571 |
metavar='PIDFILE',
|
572 |
help=("Save PID to file (default: %s)" %
|
573 |
DEFAULT_PID_FILE)) |
574 |
parser.add_option("--listen-address", dest="listen_address", |
575 |
default=DEFAULT_LISTEN_ADDRESS, |
576 |
metavar="LISTEN_ADDRESS",
|
577 |
help=("Address to listen for control connections"
|
578 |
"(default: *)"))
|
579 |
parser.add_option("--listen-port", dest="listen_port", |
580 |
default=DEFAULT_LISTEN_PORT, |
581 |
metavar="LISTEN_PORT",
|
582 |
help=("Port to listen for control connections"
|
583 |
"(default: %d)" % DEFAULT_LISTEN_PORT))
|
584 |
parser.add_option("--server-timeout", dest="server_timeout", |
585 |
default=DEFAULT_SERVER_TIMEOUT, type="float",
|
586 |
metavar="N",
|
587 |
help=("Wait for N seconds for the VNC server RFB "
|
588 |
"handshake (default %s)" % DEFAULT_SERVER_TIMEOUT))
|
589 |
parser.add_option("--connect-retries", dest="connect_retries", |
590 |
default=DEFAULT_CONNECT_RETRIES, type="int",
|
591 |
metavar="N",
|
592 |
help=("Retry N times to connect to the "
|
593 |
"server (default: %d)" %
|
594 |
DEFAULT_CONNECT_RETRIES)) |
595 |
parser.add_option("--retry-wait", dest="retry_wait", |
596 |
default=DEFAULT_RETRY_WAIT, type="float",
|
597 |
metavar="N",
|
598 |
help=("Wait N seconds before retrying "
|
599 |
"to connect to the server (default: %s)" %
|
600 |
DEFAULT_RETRY_WAIT)) |
601 |
parser.add_option("--connect-timeout", dest="connect_timeout", |
602 |
default=DEFAULT_CONNECT_TIMEOUT, type="int",
|
603 |
metavar="N",
|
604 |
help=("Wait N seconds for a client "
|
605 |
"to connect (default: %d)"
|
606 |
% DEFAULT_CONNECT_TIMEOUT)) |
607 |
parser.add_option("-p", "--min-port", dest="min_port", |
608 |
default=DEFAULT_MIN_PORT, type="int", metavar="MIN_PORT", |
609 |
help=("The minimum port number to use for automatically-"
|
610 |
"allocated ephemeral ports (default: %s)" %
|
611 |
DEFAULT_MIN_PORT)) |
612 |
parser.add_option("-P", "--max-port", dest="max_port", |
613 |
default=DEFAULT_MAX_PORT, type="int", metavar="MAX_PORT", |
614 |
help=("The maximum port number to use for automatically-"
|
615 |
"allocated ephemeral ports (default: %s)" %
|
616 |
DEFAULT_MAX_PORT)) |
617 |
|
618 |
(opts, args) = parser.parse_args(args) |
619 |
|
620 |
if args:
|
621 |
parser.print_help() |
622 |
sys.exit(1)
|
623 |
|
624 |
return opts
|
625 |
|
626 |
|
627 |
def main(): |
628 |
"""Run the daemon from the command line"""
|
629 |
|
630 |
opts = parse_arguments(sys.argv[1:])
|
631 |
|
632 |
# Create pidfile
|
633 |
pidf = pidlockfile.TimeoutPIDLockFile(opts.pid_file, 10)
|
634 |
|
635 |
# Initialize logger
|
636 |
lvl = logging.DEBUG if opts.debug else logging.INFO |
637 |
|
638 |
global logger
|
639 |
logger = logging.getLogger("vncauthproxy")
|
640 |
logger.setLevel(lvl) |
641 |
formatter = logging.Formatter(("%(asctime)s %(module)s[%(process)d] "
|
642 |
" %(levelname)s: %(message)s"),
|
643 |
"%Y-%m-%d %H:%M:%S")
|
644 |
handler = logging.FileHandler(opts.log_file) |
645 |
handler.setFormatter(formatter) |
646 |
logger.addHandler(handler) |
647 |
|
648 |
# Become a daemon:
|
649 |
# Redirect stdout and stderr to handler.stream to catch
|
650 |
# early errors in the daemonization process [e.g., pidfile creation]
|
651 |
# which will otherwise go to /dev/null.
|
652 |
daemon_context = AllFilesDaemonContext( |
653 |
pidfile=pidf, |
654 |
umask=0022,
|
655 |
stdout=handler.stream, |
656 |
stderr=handler.stream, |
657 |
files_preserve=[handler.stream]) |
658 |
|
659 |
# Remove any stale PID files, left behind by previous invocations
|
660 |
if daemon.runner.is_pidfile_stale(pidf):
|
661 |
logger.warning("Removing stale PID lock file %s", pidf.path)
|
662 |
pidf.break_lock() |
663 |
|
664 |
try:
|
665 |
daemon_context.open() |
666 |
except (AlreadyLocked, LockTimeout):
|
667 |
logger.critical(("Failed to lock PID file %s, another instance "
|
668 |
"running?"), pidf.path)
|
669 |
sys.exit(1)
|
670 |
logger.info("Became a daemon")
|
671 |
|
672 |
# A fork() has occured while daemonizing,
|
673 |
# we *must* reinit gevent
|
674 |
gevent.reinit() |
675 |
|
676 |
# Catch signals to ensure graceful shutdown,
|
677 |
#
|
678 |
# Uses gevent.signal so the handler fires even during
|
679 |
# gevent.socket.accept()
|
680 |
gevent.signal(SIGINT, fatal_signal_handler, "SIGINT")
|
681 |
gevent.signal(SIGTERM, fatal_signal_handler, "SIGTERM")
|
682 |
|
683 |
# Init ephemeral port pool
|
684 |
ports = range(opts.min_port, opts.max_port + 1) |
685 |
|
686 |
# Init VncAuthProxy class attributes
|
687 |
VncAuthProxy.server_timeout = opts.server_timeout |
688 |
VncAuthProxy.connect_retries = opts.connect_retries |
689 |
VncAuthProxy.retry_wait = opts.retry_wait |
690 |
VncAuthProxy.connect_timeout = opts.connect_timeout |
691 |
VncAuthProxy.ports = ports |
692 |
|
693 |
try:
|
694 |
sockets = get_listening_sockets(logger, opts.listen_port, |
695 |
opts.listen_address) |
696 |
except socket.error:
|
697 |
logger.critical("Error binding control socket")
|
698 |
sys.exit(1)
|
699 |
|
700 |
while True: |
701 |
try:
|
702 |
rlist, _, _ = select(sockets, [], []) |
703 |
for ctrl in rlist: |
704 |
client, _ = ctrl.accept() |
705 |
logger.info("New control connection")
|
706 |
|
707 |
VncAuthProxy.spawn(logger, client) |
708 |
except Exception, e: |
709 |
logger.exception(e) |
710 |
continue
|
711 |
except SystemExit: |
712 |
break
|
713 |
|
714 |
logger.info("Closing control sockets")
|
715 |
while sockets:
|
716 |
sockets.pop().close() |
717 |
daemon_context.close() |
718 |
sys.exit(0)
|