| 6 | * |
| 7 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. |
| 8 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. |
| 9 | * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. |
| 10 | * |
| 11 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, |
| 12 | * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
| 13 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, |
| 14 | * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; |
| 15 | * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
| 16 | * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 17 | */ |
| 18 |
| 19 | package jawnae.pyronet; |
| 20 |
| 21 | import org.telegram.messenger.ByteBufferDesc; |
| 22 |
| 23 | import java.io.EOFException; |
| 24 | import java.io.IOException; |
| 25 | import java.net.ConnectException; |
| 26 | import java.net.InetAddress; |
| 27 | import java.net.InetSocketAddress; |
| 28 | import java.net.Socket; |
| 29 | import java.nio.ByteBuffer; |
| 30 | import java.nio.channels.NotYetConnectedException; |
| 31 | import java.nio.channels.SelectionKey; |
| 32 | import java.nio.channels.SocketChannel; |
| 33 | import java.util.List; |
| 34 | import java.util.concurrent.CopyOnWriteArrayList; |
| 35 |
| 36 | public class PyroClient { |
| 37 | private final PyroSelector selector; |
| 38 |
| 39 | private final SelectionKey key; |
| 40 |
| 41 | private final ByteStream outbound; |
| 42 |
| 43 | // called by PyroSelector.connect() |
| 44 | PyroClient(PyroSelector selector, InetSocketAddress bind, |
| 45 | InetSocketAddress host) throws IOException { |
| 46 | this(selector, PyroClient.bindAndConfigure(selector, |
| 47 | SocketChannel.open(), bind)); |
| 48 |
| 49 | ((SocketChannel) this.key.channel()).connect(host); |
| 50 | } |
| 51 |
| 52 | // called by PyroClient and PyroServer |
| 53 | PyroClient(PyroSelector selector, SelectionKey key) { |
| 54 | this.selector = selector; |
| 55 | this.selector.checkThread(); |
| 56 |
| 57 | this.key = key; |
| 58 | this.key.attach(this); |
| 59 |
| 60 | this.outbound = new ByteStream(); |
| 61 | this.listeners = new CopyOnWriteArrayList<PyroClientListener>(); |
| 62 | this.lastEventTime = System.currentTimeMillis(); |
| 63 | } |
| 64 |
| 65 | // |
| 66 |
| 67 | private final List<PyroClientListener> listeners; |
| 68 |
| 69 | public void addListener(PyroClientListener listener) { |
| 70 | this.selector.checkThread(); |
| 71 |
| 72 | this.listeners.add(listener); |
| 73 | } |
| 74 |
| 75 | public void removeListener(PyroClientListener listener) { |
| 76 | this.selector.checkThread(); |
| 77 |
| 78 | this.listeners.remove(listener); |
| 79 | } |
| 80 |
| 81 | public void removeListeners() { |
| 82 | this.selector.checkThread(); |
| 83 |
| 84 | this.listeners.clear(); |
| 85 | } |
| 86 |
| 87 | /** |
| 88 | * Returns the PyroSelector that created this client |
| 89 | */ |
| 90 |
| 91 | public PyroSelector selector() { |
| 92 | return this.selector; |
| 93 | } |
| 94 |
| 95 | // |
| 96 |
| 97 | private Object attachment; |
| 98 |
| 99 | /** |
| 100 | * Attach any object to a client, for example to store session information |
| 101 | */ |
| 102 |
| 103 | public void attach(Object attachment) { |
| 104 | this.attachment = attachment; |
| 105 | } |
| 106 |
| 107 | /** |
| 108 | * Returns the previously attached object, or <code>null</code> if none is |
| 109 | * set |
| 110 | */ |
| 111 |
| 112 | @SuppressWarnings("unchecked") |
| 113 | public <T> T attachment() { |
| 114 | return (T) this.attachment; |
| 115 | } |
| 116 |
| 117 | // |
| 118 |
| 119 | /** |
| 120 | * Returns the local socket address (host+port) |
| 121 | */ |
| 122 |
| 123 | public InetSocketAddress getLocalAddress() { |
| 124 | Socket s = ((SocketChannel) key.channel()).socket(); |
| 125 | return (InetSocketAddress) s.getLocalSocketAddress(); |
| 126 | } |
| 127 |
| 128 | /** |
| 129 | * Returns the remove socket address (host+port) |
| 130 | */ |
| 131 |
| 132 | public InetSocketAddress getRemoteAddress() { |
| 133 | Socket s = ((SocketChannel) key.channel()).socket(); |
| 134 | return (InetSocketAddress) s.getRemoteSocketAddress(); |
| 135 | } |
| 136 |
| 137 | // |
| 138 |
| 139 | public void setTimeout(int ms) throws IOException { |
| 140 | this.selector.checkThread(); |
| 141 |
| 142 | ((SocketChannel) key.channel()).socket().setSoTimeout(ms); |
| 143 |
| 144 | // prevent a call to setTimeout from immediately causing a timeout |
| 145 | this.lastEventTime = System.currentTimeMillis(); |
| 146 | this.timeout = ms; |
| 147 | } |
| 148 |
| 149 | public void setLinger(boolean enabled, int seconds) throws IOException { |
| 150 | this.selector.checkThread(); |
| 151 |
| 152 | ((SocketChannel) key.channel()).socket().setSoLinger(enabled, seconds); |
| 153 | } |
| 154 |
| 155 | public void setKeepAlive(boolean enabled) throws IOException { |
| 156 | this.selector.checkThread(); |
| 157 |
| 158 | ((SocketChannel) key.channel()).socket().setKeepAlive(enabled); |
| 159 | } |
| 160 |
| 161 | private boolean doEagerWrite = false; |
| 162 |
| 163 | /** |
| 164 | * If enabled, causes calls to write() to make an attempt to write the |
| 165 | * bytes, without waiting for the selector to signal writable state. |
| 166 | */ |
| 167 |
| 168 | public void setEagerWrite(boolean enabled) { |
| 169 | this.doEagerWrite = enabled; |
| 170 | } |
| 171 |
| 172 | /** |
| 173 | * Will enqueue the bytes to send them<br> |
| 174 | * 1. when the selector is ready to write, if eagerWrite is disabled |
| 175 | * (default)<br> |
| 176 | * 2. immediately, if eagerWrite is enabled<br> |
| 177 | * The ByteBuffer instance is kept, not copied, and thus should not be |
| 178 | * modified |
| 179 | * |
| 180 | * @throws PyroException |
| 181 | * when shutdown() has been called. |
| 182 | */ |
| 183 |
| 184 | public void write(ByteBufferDesc data) throws PyroException { |
| 185 | this.selector.checkThread(); |
| 186 |
| 187 | if (!this.key.isValid()) { |
| 188 | // graceful, as this is meant to be async |
| 189 | return; |
| 190 | } |
| 191 |
| 192 | if (this.doShutdown) { |
| 193 | throw new PyroException("shutting down"); |
| 194 | } |
| 195 |
| 196 | this.outbound.append(data); |
| 197 |
| 198 | if (this.doEagerWrite) { |
| 199 | try { |
| 200 | this.onReadyToWrite(System.currentTimeMillis()); |
| 201 | } catch (NotYetConnectedException exc) { |
| 202 | this.adjustWriteOp(); |
| 203 | } catch (IOException exc) { |
| 204 | this.onConnectionError(exc); |
| 205 | key.cancel(); |
| 206 | } |
| 207 | } else { |
| 208 | this.adjustWriteOp(); |
| 209 | } |
| 210 | } |
| 211 |
| 212 | /** |
| 213 | * Writes as many as possible bytes to the socket buffer |
| 214 | */ |
| 215 |
| 216 | public int flush() { |
| 217 | int total = 0; |
| 218 |
| 219 | while (this.outbound.hasData()) { |
| 220 | int written; |
| 221 |
| 222 | try { |
| 223 | written = this.onReadyToWrite(System.currentTimeMillis()); |
| 224 | } catch (IOException exc) { |
| 225 | written = 0; |
| 226 | } |
| 227 |
| 228 | if (written == 0) { |
| 229 | break; |
| 230 | } |
| 231 |
| 232 | total += written; |
| 233 | } |
| 234 |
| 235 | return total; |
| 236 | } |
| 237 |
| 238 | /** |
| 239 | * Makes an attempt to write all outbound bytes, fails on failure. |
| 240 | * |
| 241 | * @throws PyroException |
| 242 | * on failure |
| 243 | */ |
| 244 |
| 245 | public int flushOrDie() throws PyroException { |
| 246 | int total = 0; |
| 247 |
| 248 | while (this.outbound.hasData()) { |
| 249 | int written; |
| 250 |
| 251 | try { |
| 252 | written = this.onReadyToWrite(System.currentTimeMillis()); |
| 253 | } catch (IOException exc) { |
| 254 | written = 0; |
| 255 | } |
| 256 |
| 257 | if (written == 0) { |
| 258 | throw new PyroException("failed to flush, wrote " + total |
| 259 | + " bytes"); |
| 260 | } |
| 261 |
| 262 | total += written; |
| 263 | } |
| 264 |
| 265 | return total; |
| 266 | } |
| 267 |
| 268 | /** |
| 269 | * Returns whether there are bytes left in the outbound queue. |
| 270 | */ |
| 271 |
| 272 | public boolean hasDataEnqueued() { |
| 273 | this.selector.checkThread(); |
| 274 |
| 275 | return this.outbound.hasData(); |
| 276 | } |
| 277 |
| 278 | private boolean doShutdown = false; |
| 279 |
| 280 | /** |
| 281 | * Gracefully shuts down the connection. The connection is closed after the |
| 282 | * last outbound bytes are sent. Enqueuing new bytes after shutdown, is not |
| 283 | * allowed and will throw an exception |
| 284 | */ |
| 285 |
| 286 | public void shutdown() { |
| 287 | this.selector.checkThread(); |
| 288 |
| 289 | this.doShutdown = true; |
| 290 |
| 291 | if (!this.hasDataEnqueued()) { |
| 292 | this.dropConnection(); |
| 293 | } |
| 294 | } |
| 295 |
| 296 | /** |
| 297 | * Immediately drop the connection, regardless of any pending outbound |
| 298 | * bytes. Actual behaviour depends on the socket linger settings. |
| 299 | */ |
| 300 |
| 301 | public void dropConnection() { |
| 302 | this.selector.checkThread(); |
| 303 |
| 304 | if (this.isDisconnected()) { |
| 305 | return; |
| 306 | } |
| 307 |
| 308 | Runnable drop = new Runnable() { |
| 309 | @Override |
| 310 | @SuppressWarnings("synthetic-access") |
| 311 | public void run() { |
| 312 | try { |
| 313 | if (key.channel().isOpen()) { |
| 314 | (key.channel()).close(); |
| 315 | } |
| 316 | } catch (Exception exc) { |
| 317 | selector().scheduleTask(this); |
| 318 | } |
| 319 | } |
| 320 | }; |
| 321 |
| 322 | drop.run(); |
| 323 |
| 324 | this.onConnectionError("local"); |
| 325 | } |
| 326 |
| 327 | /** |
| 328 | * Returns whether the connection is connected to a remote client. |
| 329 | */ |
| 330 |
| 331 | public boolean isDisconnected() { |
| 332 | this.selector.checkThread(); |
| 333 |
| 334 | return !this.key.channel().isOpen(); |
| 335 | } |
| 336 |
| 337 | // |
| 338 |
| 339 | void onInterestOp(long now) { |
| 340 | if (!key.isValid()) { |
| 341 | this.onConnectionError("remote"); |
| 342 | } else { |
| 343 | try { |
| 344 | if (key.isConnectable()) |
| 345 | this.onReadyToConnect(now); |
| 346 | if (key.isReadable()) |
| 347 | this.onReadyToRead(now); |
| 348 | if (key.isWritable()) |
| 349 | this.onReadyToWrite(now); |
| 350 | } catch (Exception exc) { |
| 351 | this.onConnectionError(exc); |
| 352 | key.cancel(); |
| 353 | } |
| 354 | } |
| 355 | } |
| 356 |
| 357 | private long timeout = 0L; |
| 358 |
| 359 | private long lastEventTime; |
| 360 |
| 361 | boolean didTimeout(long now) { |
| 362 | return this.timeout != 0 && (now - this.lastEventTime) > this.timeout; |
| 363 | } |
| 364 |
| 365 | private void onReadyToConnect(long now) throws IOException { |
| 366 | this.selector.checkThread(); |
| 367 | this.lastEventTime = now; |
| 368 |
| 369 | this.selector.adjustInterestOp(key, SelectionKey.OP_CONNECT, false); |
| 370 | boolean result = ((SocketChannel) key.channel()).finishConnect(); |
| 371 |
| 372 | for (PyroClientListener listener: this.listeners) |
| 373 | listener.connectedClient(this); |
| 374 | } |
| 375 |
| 376 | private void onReadyToRead(long now) throws IOException { |
| 377 | this.selector.checkThread(); |
| 378 | this.lastEventTime = now; |
| 379 |
| 380 | SocketChannel channel = (SocketChannel) key.channel(); |
| 381 |
| 382 | ByteBuffer buffer = this.selector.networkBuffer; |
| 383 |
| 384 | // read from channel |
| 385 | buffer.clear(); |
| 386 | int bytes = channel.read(buffer); |
| 387 | if (bytes == -1) |
| 388 | throw new EOFException(); |
| 389 | buffer.flip(); |
| 390 |
| 391 | for (PyroClientListener listener: this.listeners) |
| 392 | listener.receivedData(this, buffer); |
| 393 | } |
| 394 |
| 395 | private int onReadyToWrite(long now) throws IOException { |
| 396 | this.selector.checkThread(); |
| 397 | //this.lastEventTime = now; |
| 398 |
| 399 | int sent = 0; |
| 400 |
| 401 | // copy outbound bytes into network buffer |
| 402 | ByteBuffer buffer = this.selector.networkBuffer; |
| 403 | buffer.clear(); |
| 404 | this.outbound.get(buffer); |
| 405 | buffer.flip(); |
| 406 |
| 407 | // write to channel |
| 408 | if (buffer.hasRemaining()) { |
| 409 | SocketChannel channel = (SocketChannel) key.channel(); |
| 410 | sent = channel.write(buffer); |
| 411 | } |
| 412 |
| 413 | if (sent > 0) { |
| 414 | this.outbound.discard(sent); |
| 415 | } |
| 416 |
| 417 | for (PyroClientListener listener: this.listeners) |
| 418 | listener.sentData(this, sent); |
| 419 |
| 420 | this.adjustWriteOp(); |
| 421 |
| 422 | if (this.doShutdown && !this.outbound.hasData()) { |
| 423 | this.dropConnection(); |
| 424 | } |
| 425 |
| 426 | return sent; |
| 427 | } |
| 428 |
| 429 | void onConnectionError(final Object cause) { |
| 430 | this.selector.checkThread(); |
| 431 |
| 432 | try { |
| 433 | // if the key is invalid, the channel may remain open!! |
| 434 | this.key.channel().close(); |
| 435 | } catch (Exception exc) { |
| 436 | // type: java.io.IOException |
| 437 | // message: |
| 438 | // "A non-blocking socket operation could not be completed immediately" |
| 439 |
| 440 | // try again later |
| 441 | this.selector.scheduleTask(new Runnable() { |
| 442 | @Override |
| 443 | public void run() { |
| 444 | PyroClient.this.onConnectionError(cause); |
| 445 | } |
| 446 | }); |
| 447 |
| 448 | return; |
| 449 | } |
| 450 |
| 451 | if (cause instanceof ConnectException) { |
| 452 | for (PyroClientListener listener: this.listeners) |
| 453 | listener.unconnectableClient(this, (Exception)cause); |
| 454 | } else if (cause instanceof EOFException) // after read=-1 |
| 455 | { |
| 456 | for (PyroClientListener listener: this.listeners) |
| 457 | listener.disconnectedClient(this); |
| 458 | } else if (cause instanceof IOException) { |
| 459 | for (PyroClientListener listener: this.listeners) |
| 460 | listener.droppedClient(this, (IOException) cause); |
| 461 | } else if (!(cause instanceof String)) { |
| 462 | for (PyroClientListener listener: this.listeners) |
| 463 | listener.unconnectableClient(this, null); |
| 464 | } else if (cause.equals("local")) { |
| 465 | for (PyroClientListener listener: this.listeners) |
| 466 | listener.disconnectedClient(this); |
| 467 | } else if (cause.equals("remote")) { |
| 468 | for (PyroClientListener listener: this.listeners) |
| 469 | listener.droppedClient(this, null); |
| 470 | } else { |
| 471 | throw new IllegalStateException("illegal cause: " + cause); |
| 472 | } |
| 473 | } |
| 474 |
| 475 | public String toString() { |
| 476 | return this.getClass().getSimpleName() + "[" + this.getAddressText() |
| 477 | + "]"; |
| 478 | } |
| 479 |
| 480 | private String getAddressText() { |
| 481 | if (!this.key.channel().isOpen()) |
| 482 | return "closed"; |
| 483 |
| 484 | InetSocketAddress sockaddr = this.getRemoteAddress(); |
| 485 | if (sockaddr == null) |
| 486 | return "connecting"; |
| 487 | InetAddress inetaddr = sockaddr.getAddress(); |
| 488 | return inetaddr.getHostAddress() + "@" + sockaddr.getPort(); |
| 489 | } |
| 490 |
| 491 | // |
| 492 |
| 493 | void adjustWriteOp() { |
| 494 | this.selector.checkThread(); |
| 495 |
| 496 | boolean interested = this.outbound.hasData(); |
| 497 |
| 498 | this.selector.adjustInterestOp(this.key, SelectionKey.OP_WRITE, |
| 499 | interested); |
| 500 | } |
| 501 |
| 502 | static SelectionKey bindAndConfigure(PyroSelector selector, |
| 503 | SocketChannel channel, InetSocketAddress bind) throws IOException { |
| 504 | selector.checkThread(); |
| 505 |
| 506 | channel.socket().bind(bind); |
| 507 |
| 508 | return configure(selector, channel, true); |
| 509 | } |
| 510 |
| 511 | static SelectionKey configure(PyroSelector selector, |
| 512 | SocketChannel channel, boolean connect) throws IOException { |
| 513 | selector.checkThread(); |
| 514 |
| 515 | channel.configureBlocking(false); |
| 516 | // channel.socket().setSoLinger(false, 0); // this will b0rk your |
| 517 | // connections |
| 518 | channel.socket().setSoLinger(true, 4); |
| 519 | channel.socket().setReuseAddress(false); |
| 520 | channel.socket().setKeepAlive(false); |
| 521 | channel.socket().setTcpNoDelay(true); |
| 522 | channel.socket().setReceiveBufferSize(PyroSelector.BUFFER_SIZE); |
| 523 | channel.socket().setSendBufferSize(PyroSelector.BUFFER_SIZE); |
| 524 |
| 525 | int ops = SelectionKey.OP_READ; |
| 526 | if (connect) |
| 527 | ops |= SelectionKey.OP_CONNECT; |
| 528 |
| 529 | return selector.register(channel, ops); |
| 530 | } |
| 531 | } |
| 532 |