aboutsummaryrefslogtreecommitdiffstats
path: root/lib/jython/Lib/socket.py
blob: 1aaf2eaccc939afb96d6c61dbfddcd006182d2d6 (plain)
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
"""Preliminary socket module.

XXX Restrictions:

- Only INET sockets
- No asynchronous behavior
- No socket options
- Can't do a very good gethostbyaddr() right...

"""

import java.net
import org.python.core
import jarray
import string

__all__ = ['AF_INET', 'SOCK_DGRAM', 'SOCK_RAW', 'SOCK_RDM', 'SOCK_SEQPACKET',
           'SOCK_STREAM', 'SocketType', 'error', 'getfqdn', 'gethostbyaddr',
           'gethostbyname', 'gethostname', 'socket']

error = IOError

AF_INET = 2

SOCK_DGRAM = 1
SOCK_STREAM = 2
SOCK_RAW = 3 # not supported
SOCK_RDM = 4 # not supported
SOCK_SEQPACKET = 5 # not supported
SOL_SOCKET = 0xFFFF
SO_REUSEADDR = 4

def _gethostbyaddr(name):
    # This is as close as I can get; at least the types are correct...
    addresses = java.net.InetAddress.getAllByName(gethostbyname(name))
    names = []
    addrs = []
    for addr in addresses:
      names.append(addr.getHostName())
      addrs.append(addr.getHostAddress())
    return (names, addrs)

def getfqdn(name=None):
    """
    Return a fully qualified domain name for name. If name is omitted or empty
    it is interpreted as the local host.  To find the fully qualified name,
    the hostname returned by gethostbyaddr() is checked, then aliases for the
    host, if available. The first name which includes a period is selected.
    In case no fully qualified domain name is available, the hostname is retur
    New in version 2.0.
    """
    if not name:
        name = gethostname()
    names, addrs = _gethostbyaddr(name)
    for a in names:
        if a.find(".") >= 0:
            return a
    return name

def gethostname():
    return java.net.InetAddress.getLocalHost().getHostName()

def gethostbyname(name):
    return java.net.InetAddress.getByName(name).getHostAddress()

def gethostbyaddr(name):
    names, addrs = _gethostbyaddr(name)
    return (names[0], names, addrs)


def socket(family, type, flags=0):
    assert family == AF_INET
    assert type in (SOCK_DGRAM, SOCK_STREAM)
    assert flags == 0
    if type == SOCK_STREAM:
	return _tcpsocket()
    else:
	return _udpsocket()


class _tcpsocket:

    sock = None
    istream = None
    ostream = None
    addr = None
    server = 0
    file_count = 0
    reuse_addr = 0

    def bind(self, addr, port=None):
	if port is not None:
	    addr = (addr, port)
	assert not self.sock
	assert not self.addr
	host, port = addr # format check
	self.addr = addr

    def listen(self, backlog=50):
	"This signifies a server socket"
	assert not self.sock
	self.server = 1
	if self.addr:
	    host, port = self.addr
	else:
	    host, port = "", 0
	if host:
	    a = java.net.InetAddress.getByName(host)
	    self.sock = java.net.ServerSocket(port, backlog, a)
	else:
	    self.sock = java.net.ServerSocket(port, backlog)
        if hasattr(self.sock, "setReuseAddress"):
            self.sock.setReuseAddress(self.reuse_addr)

    def accept(self):
	"This signifies a server socket"
	if not self.sock:
	    self.listen()
	assert self.server
	sock = self.sock.accept()
	host = sock.getInetAddress().getHostName()
	port = sock.getPort()
	conn = _tcpsocket()
	conn._setup(sock)
	return conn, (host, port)

    def connect(self, addr, port=None):
	"This signifies a client socket"
	if port is not None:
	    addr = (addr, port)
	assert not self.sock
	host, port = addr
	if host == "":
	    host = java.net.InetAddress.getLocalHost()
	self._setup(java.net.Socket(host, port))

    def _setup(self, sock):
	self.sock = sock
        if hasattr(self.sock, "setReuseAddress"):
            self.sock.setReuseAddress(self.reuse_addr)
	self.istream = sock.getInputStream()
	self.ostream = sock.getOutputStream()

    def recv(self, n):
	assert self.sock
	data = jarray.zeros(n, 'b')
	m = self.istream.read(data)
	if m <= 0:
	    return ""
	if m < n:
	    data = data[:m]
	return data.tostring()

    def send(self, s):
	assert self.sock
	n = len(s)
	self.ostream.write(s)
	return n

    def getsockname(self):
	if not self.sock:
	    host, port = self.addr or ("", 0)
	    host = java.net.InetAddress.getByName(host).getHostAddress()
	else:
	    if self.server:
		host = self.sock.getInetAddress().getHostAddress()
	    else:
		host = self.sock.getLocalAddress().getHostAddress()
	    port = self.sock.getLocalPort()
	return (host, port)

    def getpeername(self):
	assert self.sock
	assert not self.server
	host = self.sock.getInetAddress().getHostAddress()
	port = self.sock.getPort()
	return (host, port)
        
    def setsockopt(self, level, optname, value):
        if optname == SO_REUSEADDR:
            self.reuse_addr = value

    def getsockopt(self, level, optname):
        if optname == SO_REUSEADDR:
            return self.reuse_addr

    def makefile(self, mode="r", bufsize=-1):
        file = None
	if self.istream:
	    if self.ostream:
		file = org.python.core.PyFile(self.istream, self.ostream,
					      "<socket>", mode)
	    else:
		file = org.python.core.PyFile(self.istream, "<socket>", mode)
	elif self.ostream:
	    file = org.python.core.PyFile(self.ostream, "<socket>", mode)
	else:
	    raise IOError, "both istream and ostream have been shut down"
        if file:
            return _tcpsocket.FileWrapper(self, file)

    class FileWrapper:
        def __init__(self, socket, file):
            self.socket = socket
            self.sock = socket.sock
            self.istream = socket.istream
            self.ostream = socket.ostream

            self.file = file
            self.read       = file.read
            self.readline   = file.readline
            self.readlines  = file.readlines
            self.write      = file.write
            self.writelines = file.writelines
            self.flush      = file.flush
            self.seek       = file.seek
            self.tell       = file.tell

            self.socket.file_count += 1

        def close(self):
            if self.file.closed:
                # Already closed
                return

            self.socket.file_count -= 1
            self.file.close()

            if self.socket.file_count == 0 and self.socket.sock == 0:
                # This is the last file Only close the socket and streams 
                # if there are no outstanding files left.
                if self.sock:
                     self.sock.close()
                if self.istream:
                     self.istream.close()
                if self.ostream:
                     self.ostream.close()

    def shutdown(self, how):
	assert how in (0, 1, 2)
	assert self.sock
	if how in (0, 2):
	    self.istream = None
	if how in (1, 2):
	    self.ostream = None

    def close(self):
	sock = self.sock
	istream = self.istream
	ostream = self.ostream
	self.sock = 0
	self.istream = 0
	self.ostream = 0
        # Only close the socket and streams if there are no 
        # outstanding files left.
        if self.file_count == 0:
	    if istream:
	        istream.close()
	    if ostream:
	        ostream.close()
	    if sock:
	        sock.close()


class _udpsocket:

    def __init__(self):
	self.sock = None
	self.addr = None

    def bind(self, addr, port=None):
	if port is not None:
	    addr = (addr, port)
	assert not self.sock
	host, port = addr
	if host == "":
	    self.sock = java.net.DatagramSocket(port)
	else:
	    a = java.net.InetAddress.getByName(host)
	    self.sock = java.net.DatagramSocket(port, a)

    def connect(self, addr, port=None):
	if port is not None:
	    addr = (addr, port)
	host, port = addr # format check
	assert not self.addr
	if not self.sock:
	    self.sock = java.net.DatagramSocket()
	self.addr = addr # convert host to InetAddress instance?

    def sendto(self, data, addr):
	n = len(data)
	if not self.sock:
	    self.sock = java.net.DatagramSocket()
	host, port = addr
	bytes = jarray.array(map(ord, data), 'b')
	a = java.net.InetAddress.getByName(host)
	packet = java.net.DatagramPacket(bytes, n, a, port)
	self.sock.send(packet)
	return n

    def send(self, data):
	assert self.addr
	return self.sendto(self.addr)

    def recvfrom(self, n):
	assert self.sock
	bytes = jarray.zeros(n, 'b')
	packet = java.net.DatagramPacket(bytes, n)
	self.sock.receive(packet)
	host = packet.getAddress().getHostName()
	port = packet.getPort()
	m = packet.getLength()
	if m < n:
	    bytes = bytes[:m]
	return bytes.tostring(), (host, port)

    def recv(self, n):
	assert self.sock
	bytes = jarray.zeros(n, 'b')
	packet = java.net.DatagramPacket(bytes, n)
	self.sock.receive(packet)
	m = packet.getLength()
	if m < n:
	    bytes = bytes[:m]
	return bytes.tostring()

    def getsockname(self):
	assert self.sock
	host = self.sock.getLocalAddress().getHostName()
	port = self.sock.getLocalPort()
	return (host, port)

    def getpeername(self):
	assert self.sock
	host = self.sock.getInetAddress().getHostName()
	port = self.sock.getPort()
	return (host, port)

    def __del__(self):
	self.close()

    def close(self):
	sock = self.sock
	self.sock = 0
	sock.close()

SocketType = _tcpsocket

def test():
    s = socket(AF_INET, SOCK_STREAM)
    s.connect(("", 80))
    s.send("GET / HTTP/1.0\r\n\r\n")
    while 1:
	data = s.recv(2000)
	print data
	if not data:
	    break

if __name__ == '__main__':
    test()