summaryrefslogtreecommitdiff
path: root/java/net/ServerSocket.java
blob: d5f2a176b812160fd592f9832613a330dd61cebb (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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/* ServerSocket.java -- Class for implementing server side sockets
   Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2006
   Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath 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 2, or (at your option)
any later version.

GNU Classpath 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 GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

package java.net;

import gnu.java.net.PlainSocketImpl;

import java.io.IOException;
import java.nio.channels.IllegalBlockingModeException;
import java.nio.channels.ServerSocketChannel;


/* Written using on-line Java Platform 1.2 API Specification.
 * Status:  I believe all methods are implemented.
 */

/**
 * This class models server side sockets.  The basic model is that the
 * server socket is created and bound to some well known port.  It then
 * listens for and accepts connections.  At that point the client and
 * server sockets are ready to communicate with one another utilizing
 * whatever application layer protocol they desire.
 *
 * As with the <code>Socket</code> class, most instance methods of this class
 * simply redirect their calls to an implementation class.
 *
 * @author Aaron M. Renn (arenn@urbanophile.com)
 * @author Per Bothner (bothner@cygnus.com)
 */
public class ServerSocket
{
  /**
   * This is the user defined SocketImplFactory, if one is supplied
   */
  private static SocketImplFactory factory;

  /**
   * This is the SocketImp object to which most instance methods in this
   * class are redirected
   */
  private SocketImpl impl;

  /**
   * We need to retain the local address even after the socket is closed.
   */
  private InetSocketAddress local;
  private int port;

  /*
   * This constructor is only used by java.nio.
   */

  // FIXME: Workaround a bug in gcj.
  //ServerSocket (PlainSocketImpl impl) throws IOException
  ServerSocket(SocketImpl impl) throws IOException
  {
    if (impl == null)
      throw new NullPointerException("impl may not be null");

    this.impl = impl;
    this.impl.create(true);
    setReuseAddress(true);
  }

  /*
   * This method is only used by java.nio.
   */

  // FIXME: Workaround a bug in gcj.
  //PlainSocketImpl getImpl()
  SocketImpl getImpl()
  {
    return impl;
  }

  /**
   * Constructor that simply sets the implementation.
   *
   * @exception IOException If an error occurs
   *
   * @specnote This constructor is public since JDK 1.4
   */
  public ServerSocket() throws IOException
  {
    if (factory != null)
      impl = factory.createSocketImpl();
    else
      impl = new PlainSocketImpl();

    impl.create(true);
  }

  /**
   * Creates a server socket and binds it to the specified port.  If the
   * port number is 0, a random free port will be chosen.  The pending
   * connection queue on this socket will be set to 50.
   *
   * @param port The port number to bind to
   *
   * @exception IOException If an error occurs
   * @exception SecurityException If a security manager exists and its
   * checkListen method doesn't allow the operation
   */
  public ServerSocket(int port) throws IOException
  {
    this(port, 50);
  }

  /**
   * Creates a server socket and binds it to the specified port.  If the
   * port number is 0, a random free port will be chosen.  The pending
   * connection queue on this socket will be set to the value passed as
   * arg2.
   *
   * @param port The port number to bind to
   * @param backlog The length of the pending connection queue
   *
   * @exception IOException If an error occurs
   * @exception SecurityException If a security manager exists and its
   * checkListen method doesn't allow the operation
   */
  public ServerSocket(int port, int backlog) throws IOException
  {
    this(port, backlog, null);
  }

  /**
   * Creates a server socket and binds it to the specified port.  If the
   * port number is 0, a random free port will be chosen.  The pending
   * connection queue on this socket will be set to the value passed as
   * backlog.  The third argument specifies a particular local address to
   * bind t or null to bind to all local address.
   *
   * @param port The port number to bind to
   * @param backlog The length of the pending connection queue
   * @param bindAddr The address to bind to, or null to bind to all addresses
   *
   * @exception IOException If an error occurs
   * @exception SecurityException If a security manager exists and its
   * checkListen method doesn't allow the operation
   *
   * @since 1.1
   */
  public ServerSocket(int port, int backlog, InetAddress bindAddr)
    throws IOException
  {
    this();

    // bind/listen socket
    bind(new InetSocketAddress(bindAddr, port), backlog);
  }

  /**
   * Binds the server socket to a specified socket address
   *
   * @param endpoint The socket address to bind to
   *
   * @exception IOException If an error occurs
   * @exception IllegalArgumentException If address type is not supported
   * @exception SecurityException If a security manager exists and its
   * checkListen method doesn't allow the operation
   *
   * @since 1.4
   */
  public void bind(SocketAddress endpoint) throws IOException
  {
    bind(endpoint, 50);
  }

  /**
   * Binds the server socket to a specified socket address
   *
   * @param endpoint The socket address to bind to
   * @param backlog The length of the pending connection queue
   *
   * @exception IOException If an error occurs
   * @exception IllegalArgumentException If address type is not supported
   * @exception SecurityException If a security manager exists and its
   * checkListen method doesn't allow the operation
   *
   * @since 1.4
   */
  public void bind(SocketAddress endpoint, int backlog)
    throws IOException
  {
    if (isClosed())
      throw new SocketException("ServerSocket is closed");

    if (isBound())
      throw new SocketException("Already bound");

    InetAddress addr;
    int port;

    if (endpoint == null)
      {
        addr = InetAddress.ANY_IF;
        port = 0;
      }
    else if (! (endpoint instanceof InetSocketAddress))
      {
        throw new IllegalArgumentException("Address type not supported");
      }
    else
      {
        InetSocketAddress tmp = (InetSocketAddress) endpoint;
        if (tmp.isUnresolved())
          throw new SocketException("Unresolved address");
        addr = tmp.getAddress();
        port = tmp.getPort();
      }

    SecurityManager s = System.getSecurityManager();
    if (s != null)
      s.checkListen(port);

    try
      {
	impl.bind(addr, port);
	impl.listen(backlog);
        this.port = port;
        local = new InetSocketAddress(
            (InetAddress) impl.getOption(SocketOptions.SO_BINDADDR),
            impl.getLocalPort());
      }
    finally
      {
        try
          {
            if (local == null)
	      close();
          }
        catch (IOException _)
          {
          }
      }
  }

  /**
   * This method returns the local address to which this socket is bound
   *
   * @return The socket's local address
   */
  public InetAddress getInetAddress()
  {
    if (local == null)
      return null;

    return local.getAddress();
  }

  /**
   * This method returns the local port number to which this socket is bound
   *
   * @return The socket's port number
   */
  public int getLocalPort()
  {
    if (local == null)
      return -1;

    return local.getPort();
  }

  /**
   * Returns the local socket address
   *
   * @return the local socket address, null if not bound
   * 
   * @since 1.4
   */
  public SocketAddress getLocalSocketAddress()
  {
    return local;
  }

  /**
   * Accepts a new connection and returns a connected <code>Socket</code>
   * instance representing that connection.  This method will block until a
   * connection is available.
   *
   * @return socket object for the just accepted connection
   *
   * @exception IOException If an error occurs
   * @exception SecurityException If a security manager exists and its
   * checkListen method doesn't allow the operation
   * @exception IllegalBlockingModeException If this socket has an associated
   * channel, and the channel is in non-blocking mode
   * @exception SocketTimeoutException If a timeout was previously set with
   * setSoTimeout and the timeout has been reached
   */
  public Socket accept() throws IOException
  {
    Socket socket = new Socket();

    try
      {
	implAccept(socket);
      }
    catch (IOException e)
      {
	try
	  {
	    socket.close();
	  }
	catch (IOException e2)
	  {
	    // Ignore.
	  }

	throw e;
      }
    catch (SecurityException e)
      {
	try
	  {
	    socket.close();
	  }
	catch (IOException e2)
	  {
	    // Ignore.
	  }

	throw e;
      }

    return socket;
  }

  /**
   * This protected method is used to help subclasses override
   * <code>ServerSocket.accept()</code>.  The passed in socket will be
   * connected when this method returns.
   *
   * @param socket The socket that is used for the accepted connection
   *
   * @exception IOException If an error occurs
   * @exception IllegalBlockingModeException If this socket has an associated
   * channel, and the channel is in non-blocking mode
   *
   * @since 1.1
   */
  protected final void implAccept(Socket socket) throws IOException
  {
    if (isClosed())
      throw new SocketException("ServerSocket is closed");

    // The Sun spec says that if we have an associated channel and
    // it is in non-blocking mode, we throw an IllegalBlockingModeException.
    // However, in our implementation if the channel itself initiated this
    // operation, then we must honor it regardless of its blocking mode.
    if (getChannel() != null && ! getChannel().isBlocking()
        && ! ((PlainSocketImpl) getImpl()).isInChannelOperation())
      throw new IllegalBlockingModeException();

    impl.accept(socket.impl);
    socket.bound = true;

    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
      sm.checkAccept(socket.getInetAddress().getHostAddress(),
		     socket.getPort());
  }

  /**
   * Closes this socket and stops listening for connections
   *
   * @exception IOException If an error occurs
   */
  public void close() throws IOException
  {
    if (impl != null)
      {
        impl.close();
        impl = null;
      }
  }

  /**
   * Returns the unique <code>ServerSocketChannel</code> object
   * associated with this socket, if any.
   *
   * <p>The socket only has a <code>ServerSocketChannel</code> if its created
   * by <code>ServerSocketChannel.open()</code>.</p>
   *
   * @return the associated socket channel, null if none exists
   * 
   * @since 1.4
   */
  public ServerSocketChannel getChannel()
  {
    return null;
  }

  /**
   * Returns true when the socket is bound, otherwise false
   *
   * @return true if socket is bound, false otherwise
   * 
   * @since 1.4
   */
  public boolean isBound()
  {
    return local != null;
  }

  /**
   * Returns true if the socket is closed, otherwise false
   *
   * @return true if socket is closed, false otherwise
   * 
   * @since 1.4
   */
  public boolean isClosed()
  {
    ServerSocketChannel channel = getChannel();
    return impl == null || (channel != null && ! channel.isOpen());
  }

  /**
   * Sets the value of SO_TIMEOUT.  A value of 0 implies that SO_TIMEOUT is
   * disabled (ie, operations never time out).  This is the number of
   * milliseconds a socket operation can block before an
   * InterruptedIOException is thrown.
   *
   * @param timeout The new SO_TIMEOUT value
   *
   * @exception SocketException If an error occurs
   *
   * @since 1.1
   */
  public void setSoTimeout(int timeout) throws SocketException
  {
    if (isClosed())
      throw new SocketException("ServerSocket is closed");

    if (timeout < 0)
      throw new IllegalArgumentException("SO_TIMEOUT value must be >= 0");

    impl.setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
  }

  /**
   * Retrieves the current value of the SO_TIMEOUT setting.  A value of 0
   * implies that SO_TIMEOUT is disabled (ie, operations never time out).
   * This is the number of milliseconds a socket operation can block before
   * an InterruptedIOException is thrown.
   *
   * @return The value of SO_TIMEOUT
   *
   * @exception IOException If an error occurs
   *
   * @since 1.1
   */
  public int getSoTimeout() throws IOException
  {
    if (isClosed())
      throw new SocketException("ServerSocket is closed");

    Object timeout = impl.getOption(SocketOptions.SO_TIMEOUT);

    if (! (timeout instanceof Integer))
      throw new IOException("Internal Error");

    return ((Integer) timeout).intValue();
  }

  /**
   * Enables/Disables the SO_REUSEADDR option
   *
   * @param on true if SO_REUSEADDR should be enabled, false otherwise
   * 
   * @exception SocketException If an error occurs
   *
   * @since 1.4
   */
  public void setReuseAddress(boolean on) throws SocketException
  {
    if (isClosed())
      throw new SocketException("ServerSocket is closed");

    impl.setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
  }

  /**
   * Checks if the SO_REUSEADDR option is enabled
   *
   * @return true if SO_REUSEADDR is set, false otherwise
   *
   * @exception SocketException If an error occurs
   *
   * @since 1.4
   */
  public boolean getReuseAddress() throws SocketException
  {
    if (isClosed())
      throw new SocketException("ServerSocket is closed");

    Object reuseaddr = impl.getOption(SocketOptions.SO_REUSEADDR);

    if (! (reuseaddr instanceof Boolean))
      throw new SocketException("Internal Error");

    return ((Boolean) reuseaddr).booleanValue();
  }

  /**
   * This method sets the value for the system level socket option
   * SO_RCVBUF to the specified value.  Note that valid values for this
   * option are specific to a given operating system.
   *
   * @param size The new receive buffer size.
   *
   * @exception SocketException If an error occurs or Socket is not connected
   * @exception IllegalArgumentException If size is 0 or negative
   *
   * @since 1.4
   */
  public void setReceiveBufferSize(int size) throws SocketException
  {
    if (isClosed())
      throw new SocketException("ServerSocket is closed");

    if (size <= 0)
      throw new IllegalArgumentException("SO_RCVBUF value must be > 0");

    impl.setOption(SocketOptions.SO_RCVBUF, new Integer(size));
  }

  /**
   * This method returns the value of the system level socket option
   * SO_RCVBUF, which is used by the operating system to tune buffer
   * sizes for data transfers.
   *
   * @return The receive buffer size.
   *
   * @exception SocketException If an error occurs or Socket is not connected
   *
   * @since 1.4
   */
  public int getReceiveBufferSize() throws SocketException
  {
    if (isClosed())
      throw new SocketException("ServerSocket is closed");

    Object buf = impl.getOption(SocketOptions.SO_RCVBUF);

    if (! (buf instanceof Integer))
      throw new SocketException("Internal Error: Unexpected type");

    return ((Integer) buf).intValue();
  }

  /**
   * Returns the value of this socket as a <code>String</code>.
   *
   * @return This socket represented as a <code>String</code>.
   */
  public String toString()
  {
    if (! isBound())
      return "ServerSocket[unbound]";

    return ("ServerSocket[addr=" + getInetAddress() + ",port="
           + port + ",localport=" + getLocalPort() + "]");
  }

  /**
   * Sets the <code>SocketImplFactory</code> for all
   * <code>ServerSocket</code>'s.  This may only be done
   * once per virtual machine.  Subsequent attempts will generate an
   * exception.  Note that a <code>SecurityManager</code> check is made prior
   * to setting the factory.  If insufficient privileges exist to set the
   * factory, an exception will be thrown
   *
   * @param fac the factory to set
   *
   * @exception SecurityException If this operation is not allowed by the
   * <code>SecurityManager</code>.
   * @exception SocketException If the factory object is already defined
   * @exception IOException If any other error occurs
   */
  public static synchronized void setSocketFactory(SocketImplFactory fac)
    throws IOException
  {
    if (factory != null)
      throw new SocketException("SocketFactory already defined");

    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
      sm.checkSetFactory();

    factory = fac;
  }
}