Statistics
| Branch: | Tag: | Revision:

root / vncauthproxy / client.py @ b129b0c0

History | View | Annotate | Download (4.9 kB)

1
#!/usr/bin/env python
2
#
3
# Copyright (c) 2010-2011 Greek Research and Technology Network S.A.
4
#
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 2 of the License, or
8
# (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful, but
11
# WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
# General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18
# 02110-1301, USA.
19

    
20
import sys
21
import socket
22

    
23
try:
24
    import simplejson as json
25
except ImportError:
26
    import json
27

    
28
try:
29
    from gevent import sleep
30
except ImportError:
31
    import sleep
32

    
33
DEFAULT_SERVER_ADDRESS = '127.0.0.1'
34
DEFAULT_SERVER_PORT = 24999
35

    
36

    
37
def parse_arguments(args):
38
    from optparse import OptionParser
39

    
40
    parser = OptionParser()
41
    parser.add_option("--server", dest="server_address",
42
                      default=DEFAULT_SERVER_ADDRESS,
43
                      metavar="SERVER",
44
                      help=("vncauthproxy server"))
45
    parser.add_option("--server-port", dest="server_port",
46
                      default=DEFAULT_SERVER_PORT, type="int",
47
                      metavar="SERVER_PORT",
48
                      help=("vncauthproxy port"))
49
    parser.add_option('-s', dest="sport",
50
                      default=0, type="int",
51
                      metavar='PORT',
52
                      help=("Use source port PORT for incoming connections "
53
                            "(default: allocate a port automatically)"))
54
    parser.add_option("-d", "--dest",
55
                      default=None, dest="daddr",
56
                      metavar="HOST",
57
                      help="Proxy connection to destination host HOST")
58
    parser.add_option("-p", "--dport", dest="dport",
59
                      default=None, type="int",
60
                      metavar="PORT",
61
                      help="Proxy connection to destination port PORT")
62
    parser.add_option("-P", "--password", dest="password",
63
                      default=None,
64
                      metavar="PASSWORD",
65
                      help=("Use password PASSWD to authenticate incoming "
66
                            "VNC connections"))
67

    
68
    (opts, args) = parser.parse_args(args)
69

    
70
    # Mandatory arguments
71
    if not opts.server_address:
72
        parser.error("The --server argument is mandatory.")
73
    if not opts.password:
74
        parser.error("The -P/--password argument is mandatory.")
75
    if not opts.daddr:
76
        parser.error("The -d/--dest argument is mandatory.")
77
    if not opts.dport:
78
        parser.error("The -p/--dport argument is mandatory.")
79

    
80
    return (opts, args)
81

    
82

    
83
def request_forwarding(sport, daddr, dport, password,
84
                       server_address=DEFAULT_SERVER_ADDRESS,
85
                       server_port=DEFAULT_SERVER_PORT):
86
    """Connect to vncauthproxy and request a VNC forwarding."""
87
    if not password:
88
        raise ValueError("You must specify a non-empty password")
89

    
90
    req = {
91
        "source_port": int(sport),
92
        "destination_address": daddr,
93
        "destination_port": int(dport),
94
        "password": password,
95
    }
96

    
97
    retries = 5
98
    while retries:
99
        # Initiate server connection
100
        for res in socket.getaddrinfo(server_address, server_port,
101
                                      socket.AF_UNSPEC,
102
                                      socket.SOCK_STREAM, 0,
103
                                      socket.AI_PASSIVE):
104
            af, socktype, proto, canonname, sa = res
105
            try:
106
                server = socket.socket(af, socktype, proto)
107
            except socket.error:
108
                server = None
109
                continue
110

    
111
            server.settimeout(60.0)
112

    
113
            try:
114
                server.connect(sa)
115
            except socket.error:
116
                server.close()
117
                server = None
118
                continue
119

    
120
            retries = 0
121
            break
122

    
123
        sleep(0.2)
124

    
125
    if server is None:
126
        raise Exception("Failed to connect to server")
127

    
128
    server.send(json.dumps(req))
129

    
130
    response = server.recv(1024)
131
    server.close()
132
    res = json.loads(response)
133
    return res
134

    
135

    
136
if __name__ == '__main__':
137
    (opts, args) = parse_arguments(sys.argv[1:])
138

    
139
    res = request_forwarding(sport=opts.sport, daddr=opts.daddr,
140
                             dport=opts.dport, password=opts.password)
141

    
142
    sys.stderr.write("Forwaring %s -> %s:%s: %s\n" % (res['source_port'],
143
                                                      opts.daddr, opts.dport,
144
                                                      res['status']))
145

    
146
    if res['status'] == "OK":
147
        sys.exit(0)
148
    else:
149
        sys.exit(1)