001/* 002 * JGrapes Event Driven Framework 003 * Copyright (C) 2016-2018 Michael N. Lipp 004 * 005 * This program is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU Affero General Public License as published by 007 * the Free Software Foundation; either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, but 011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 013 * for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License along 016 * with this program; if not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jgrapes.http; 020 021import java.lang.ref.WeakReference; 022import java.net.Inet4Address; 023import java.net.InetAddress; 024import java.net.InetSocketAddress; 025import java.net.URI; 026import java.net.URISyntaxException; 027import java.net.UnknownHostException; 028import java.nio.Buffer; 029import java.nio.ByteBuffer; 030import java.nio.CharBuffer; 031import java.util.ArrayList; 032import java.util.Arrays; 033import java.util.Collections; 034import java.util.List; 035import java.util.Optional; 036import javax.net.ssl.SNIHostName; 037import javax.net.ssl.SNIServerName; 038import org.jdrupes.httpcodec.Codec; 039import org.jdrupes.httpcodec.Decoder; 040import org.jdrupes.httpcodec.MessageHeader; 041import org.jdrupes.httpcodec.ProtocolException; 042import org.jdrupes.httpcodec.ServerEngine; 043import org.jdrupes.httpcodec.protocols.http.HttpConstants.HttpStatus; 044import org.jdrupes.httpcodec.protocols.http.HttpField; 045import org.jdrupes.httpcodec.protocols.http.HttpRequest; 046import org.jdrupes.httpcodec.protocols.http.HttpResponse; 047import org.jdrupes.httpcodec.protocols.http.server.HttpRequestDecoder; 048import org.jdrupes.httpcodec.protocols.http.server.HttpResponseEncoder; 049import org.jdrupes.httpcodec.protocols.websocket.WsCloseFrame; 050import org.jdrupes.httpcodec.protocols.websocket.WsMessageHeader; 051import org.jdrupes.httpcodec.types.Converters; 052import org.jdrupes.httpcodec.types.StringList; 053import org.jgrapes.core.Channel; 054import org.jgrapes.core.ClassChannel; 055import org.jgrapes.core.Component; 056import org.jgrapes.core.Components; 057import org.jgrapes.core.EventPipeline; 058import org.jgrapes.core.annotation.Handler; 059import org.jgrapes.core.annotation.HandlerDefinition.ChannelReplacements; 060import org.jgrapes.core.internal.EventProcessor; 061import org.jgrapes.http.events.ProtocolSwitchAccepted; 062import org.jgrapes.http.events.Request; 063import org.jgrapes.http.events.Response; 064import org.jgrapes.http.events.Upgraded; 065import org.jgrapes.http.events.WebSocketClose; 066import org.jgrapes.io.IOSubchannel; 067import org.jgrapes.io.events.Close; 068import org.jgrapes.io.events.Closed; 069import org.jgrapes.io.events.Input; 070import org.jgrapes.io.events.Output; 071import org.jgrapes.io.events.Purge; 072import org.jgrapes.io.util.LinkedIOSubchannel; 073import org.jgrapes.io.util.ManagedBuffer; 074import org.jgrapes.io.util.ManagedBufferPool; 075import org.jgrapes.net.SocketServer; 076import org.jgrapes.net.events.Accepted; 077 078/** 079 * A converter component that receives and sends byte buffers on a 080 * network channel and web application layer messages on 081 * {@link IOSubchannel}s of its channel. 082 * 083 * Each {@link IOSubchannel} represents a connection established by 084 * the browser. The {@link HttpServer} fires {@link Request} events 085 * (and {@link Input} events, if there is associated data) on the 086 * subchannels. Web application components (short "weblets") handle 087 * these events and use 088 * {@link LinkedIOSubchannel#respond(org.jgrapes.core.Event)} 089 * to send {@link Response} events and, if applicable, {@link Output} 090 * events with data belonging to the response. 091 * 092 * Events must be fired by weblets while handling the {@link Request} 093 * or {@link Input} events only (to be precise: while handling events 094 * processed by the associated {@link EventProcessor}) to ensure 095 * that responses and their associated data do not interleave. 096 */ 097@SuppressWarnings({ "PMD.ExcessiveImports", "PMD.CouplingBetweenObjects" }) 098public class HttpServer extends Component { 099 100 @SuppressWarnings("PMD.SingularField") 101 private WeakReference<Channel> networkChannelPassBack; 102 private List<Class<? extends Request.In>> providedFallbacks; 103 private int matchLevels = 1; 104 private boolean acceptNoSni; 105 private int applicationBufferSize = -1; 106 107 /** 108 * Denotes the network channel in handler annotations. 109 */ 110 private static final class NetworkChannel extends ClassChannel { 111 } 112 113 /** 114 * Create a new server that uses the {@code networkChannel} for network 115 * level I/O. 116 * <P> 117 * As a convenience the server can provide fall back handlers for the 118 * specified types of requests. The fall back handler simply returns 404 ( 119 * "Not found"). 120 * 121 * @param appChannel 122 * this component's channel 123 * @param networkChannel 124 * the channel for network level I/O 125 * @param fallbacks 126 * the requests for which a fall back handler is provided 127 */ 128 @SafeVarargs 129 public HttpServer(Channel appChannel, Channel networkChannel, 130 Class<? extends Request.In>... fallbacks) { 131 super(appChannel, ChannelReplacements.create() 132 .add(NetworkChannel.class, networkChannel)); 133 networkChannelPassBack = new WeakReference<>(networkChannel); 134 this.providedFallbacks = Arrays.asList(fallbacks); 135 } 136 137 /** 138 * Create a new server that creates its own {@link SocketServer} with 139 * the given address and uses it for network level I/O. 140 * 141 * @param appChannel 142 * this component's channel 143 * @param serverAddress the address to listen on 144 * @param fallbacks fall backs 145 */ 146 @SafeVarargs 147 @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") 148 public HttpServer(Channel appChannel, InetSocketAddress serverAddress, 149 Class<? extends Request.In>... fallbacks) { 150 this(appChannel, new SocketServer().setServerAddress(serverAddress), 151 fallbacks); 152 attach((SocketServer) networkChannelPassBack.get()); 153 } 154 155 /** 156 * @return the matchLevels 157 */ 158 public int matchLevels() { 159 return matchLevels; 160 } 161 162 /** 163 * Sets the number of elements from the request path used in the match value 164 * of the generated events (see {@link Request#defaultCriterion()}), defaults 165 * to 1. 166 * 167 * @param matchLevels the matchLevels to set 168 * @return the http server for easy chaining 169 */ 170 public HttpServer setMatchLevels(int matchLevels) { 171 this.matchLevels = matchLevels; 172 return this; 173 } 174 175 /** 176 * Sets the size of the buffers used for {@link Output} events 177 * on the application channel. Defaults to the upstream buffer size 178 * minus 512 (estimate for added protocol overhead). 179 * 180 * @param applicationBufferSize the size to set 181 * @return the http server for easy chaining 182 */ 183 public HttpServer setApplicationBufferSize(int applicationBufferSize) { 184 this.applicationBufferSize = applicationBufferSize; 185 return this; 186 } 187 188 /** 189 * Returns the size of the application side (receive) buffers. 190 * 191 * @return the value or -1 if not set 192 */ 193 public int applicationBufferSize() { 194 return applicationBufferSize; 195 } 196 197 /** 198 * Determines if request from secure (TLS) connections without 199 * SNI are accepted. 200 * 201 * Secure (TLS) requests usually transfer the name of the server that 202 * they want to connect to during handshake. The HTTP server checks 203 * that the `Host` header field of decoded requests matches the 204 * name used to establish the connection. If, however, the connection 205 * is made using the IP-address, the client does not have a host name. 206 * If such connections are to be accepted, this flag, which 207 * defaults to `false`, must be set. 208 * 209 * Note that in request accepted without SNI, the `Host` header field 210 * will be modified to contain the IP-address of the indicated host 211 * to prevent accidental matching with virtual host names. 212 * 213 * @param acceptNoSni the value to set 214 * @return the http server for easy chaining 215 */ 216 public HttpServer setAcceptNoSni(boolean acceptNoSni) { 217 this.acceptNoSni = acceptNoSni; 218 return this; 219 } 220 221 /** 222 * Returns if secure (TLS) requests without SNI are allowed. 223 * 224 * @return the result 225 */ 226 public boolean acceptNoSni() { 227 return acceptNoSni; 228 } 229 230 /** 231 * Creates a new downstream connection as {@link LinkedIOSubchannel} 232 * of the network connection, a {@link HttpRequestDecoder} and a 233 * {@link HttpResponseEncoder}. 234 * 235 * @param event 236 * the accepted event 237 */ 238 @Handler(channels = NetworkChannel.class) 239 public void onAccepted(Accepted event, IOSubchannel netChannel) { 240 new WebAppMsgChannel(event, netChannel); 241 } 242 243 /** 244 * Handles data from the client (from upstream). The data is send through 245 * the {@link HttpRequestDecoder} and events are sent downstream according 246 * to the decoding results. 247 * 248 * @param event the event 249 * @throws ProtocolException if a protocol exception occurs 250 * @throws InterruptedException 251 */ 252 @Handler(channels = NetworkChannel.class) 253 public void onInput( 254 Input<ByteBuffer> event, IOSubchannel netChannel) 255 throws ProtocolException, InterruptedException { 256 @SuppressWarnings("unchecked") 257 final Optional<WebAppMsgChannel> appChannel 258 = (Optional<WebAppMsgChannel>) LinkedIOSubchannel 259 .downstreamChannel(this, netChannel); 260 if (appChannel.isPresent()) { 261 appChannel.get().handleNetInput(event); 262 } 263 } 264 265 /** 266 * Forwards a {@link Closed} event to the application channel. 267 * 268 * @param event the event 269 * @param netChannel the net channel 270 */ 271 @Handler(channels = NetworkChannel.class) 272 public void onClosed(Closed<?> event, IOSubchannel netChannel) { 273 LinkedIOSubchannel.downstreamChannel(this, netChannel, 274 WebAppMsgChannel.class).ifPresent(appChannel -> { 275 appChannel.handleClosed(event); 276 }); 277 } 278 279 /** 280 * Forwards a {@link Purge} event to the application channel. 281 * 282 * @param event the event 283 * @param netChannel the net channel 284 */ 285 @Handler(channels = NetworkChannel.class) 286 public void onPurge(Purge event, IOSubchannel netChannel) { 287 LinkedIOSubchannel.downstreamChannel(this, netChannel, 288 WebAppMsgChannel.class).ifPresent(appChannel -> { 289 appChannel.handlePurge(event); 290 }); 291 } 292 293 /** 294 * Handles a response event from downstream by sending it through an 295 * {@link HttpResponseEncoder} that generates the data (encoded information) 296 * and sends it upstream with {@link Output} events. Depending on whether 297 * the response has a body, subsequent {@link Output} events can 298 * follow. 299 * 300 * @param event 301 * the response event 302 * @throws InterruptedException if the execution was interrupted 303 */ 304 @Handler 305 public void onResponse(Response event, WebAppMsgChannel appChannel) 306 throws InterruptedException { 307 appChannel.handleResponse(event); 308 } 309 310 /** 311 * Receives the message body of a response. A {@link Response} event that 312 * has a message body can be followed by one or more {@link Output} events 313 * from downstream that contain the data. An {@code Output} event 314 * with the end of record flag set signals the end of the message body. 315 * 316 * @param event 317 * the event with the data 318 * @throws InterruptedException if the execution was interrupted 319 */ 320 @Handler 321 public void onOutput(Output<?> event, WebAppMsgChannel appChannel) 322 throws InterruptedException { 323 appChannel.handleAppOutput(event); 324 } 325 326 /** 327 * Handles a close event from downstream by closing the upstream 328 * connections. 329 * 330 * @param event 331 * the close event 332 * @throws InterruptedException if the execution was interrupted 333 */ 334 @Handler 335 public void onClose(Close event, WebAppMsgChannel appChannel) 336 throws InterruptedException { 337 appChannel.handleClose(event); 338 } 339 340 /** 341 * Checks whether the request has been handled (value of {@link Request} 342 * event set to `true`) or the status code in the prepared response 343 * is no longer "Not Implemented". If not, but a fall back has been set, 344 * send a "Not Found" response. If this isn't the case either, send 345 * the default response ("Not implemented") to the client. 346 * 347 * @param event 348 * the request completed event 349 * @param appChannel the application channel 350 * @throws InterruptedException if the execution was interrupted 351 */ 352 @Handler 353 public void onRequestCompleted( 354 Request.In.Completed event, IOSubchannel appChannel) 355 throws InterruptedException { 356 final Request.In requestEvent = event.event(); 357 // A check that also works with null. 358 if (Boolean.TRUE.equals(requestEvent.get()) 359 || requestEvent.httpRequest().response().map( 360 response -> response.statusCode() != HttpStatus.NOT_IMPLEMENTED 361 .statusCode()) 362 .orElse(false)) { 363 // Some other component has taken care 364 return; 365 } 366 367 // Check if "Not Found" should be sent 368 if (providedFallbacks != null 369 && providedFallbacks.contains(requestEvent.getClass())) { 370 ResponseCreationSupport.sendResponse( 371 requestEvent.httpRequest(), appChannel, HttpStatus.NOT_FOUND); 372 return; 373 } 374 375 // Last resort 376 ResponseCreationSupport.sendResponse(requestEvent.httpRequest(), 377 appChannel, HttpStatus.NOT_IMPLEMENTED); 378 } 379 380 /** 381 * Provides a fallback handler for an OPTIONS request with asterisk. Simply 382 * responds with "OK". 383 * 384 * @param event the event 385 * @param appChannel the application channel 386 */ 387 @Handler(priority = Integer.MIN_VALUE) 388 public void onOptions(Request.In.Options event, IOSubchannel appChannel) { 389 if (event.requestUri() == HttpRequest.ASTERISK_REQUEST) { 390 HttpResponse response = event.httpRequest().response().get(); 391 response.setStatus(HttpStatus.OK); 392 appChannel.respond(new Response(response)); 393 event.setResult(true); 394 event.stop(); 395 } 396 } 397 398 /** 399 * Send the response indicating that the protocol switch was accepted 400 * and causes subsequent data to be handled as {@link Input} and 401 * {@link Output} events on the channel. 402 * 403 * As a convenience, the channel is associates with the URI that 404 * was used to request the protocol switch using {@link URI} as key. 405 * 406 * @param event the event 407 * @param appChannel the channel 408 */ 409 @Handler 410 public void onProtocolSwitchAccepted( 411 ProtocolSwitchAccepted event, WebAppMsgChannel appChannel) { 412 appChannel.handleProtocolSwitchAccepted(event, appChannel); 413 } 414 415 /** 416 * An application layer channel. 417 */ 418 @SuppressWarnings("PMD.PublicMemberInNonPublicType") 419 private class WebAppMsgChannel extends LinkedIOSubchannel { 420 // Starts as ServerEngine<HttpRequest,HttpResponse> but may change 421 private final ServerEngine<?, ?> engine; 422 private ManagedBuffer<ByteBuffer> outBuffer; 423 private final boolean secure; 424 private List<String> snis = Collections.emptyList(); 425 private final ManagedBufferPool<ManagedBuffer<ByteBuffer>, 426 ByteBuffer> byteBufferPool; 427 private final ManagedBufferPool<ManagedBuffer<CharBuffer>, 428 CharBuffer> charBufferPool; 429 private ManagedBufferPool<?, ?> currentPool; 430 private final EventPipeline downPipeline; 431 private Upgraded pendingUpgraded; 432 private WsMessageHeader currentWsMessage; 433 434 /** 435 * Instantiates a new channel. 436 * 437 * @param event the event 438 * @param netChannel the net channel 439 */ 440 @SuppressWarnings({ "PMD.AvoidLiteralsInIfCondition", 441 "PMD.ConstructorCallsOverridableMethod" }) 442 public WebAppMsgChannel(Accepted event, IOSubchannel netChannel) { 443 super(HttpServer.this, channel(), netChannel, newEventPipeline()); 444 engine = new ServerEngine<>( 445 new HttpRequestDecoder(), new HttpResponseEncoder()); 446 secure = event.isSecure(); 447 if (secure) { 448 snis = new ArrayList<>(); 449 for (SNIServerName sni : event.requestedServerNames()) { 450 if (sni instanceof SNIHostName) { 451 snis.add(((SNIHostName) sni).getAsciiName()); 452 } 453 } 454 } 455 456 // Calculate "good" application buffer size 457 int bufferSize = applicationBufferSize; 458 if (bufferSize <= 0) { 459 bufferSize = netChannel.byteBufferPool().bufferSize() - 512; 460 if (bufferSize < 4096) { 461 bufferSize = 4096; 462 } 463 } 464 465 String channelName = Components.objectName(HttpServer.this) 466 + "." + Components.objectName(this); 467 byteBufferPool().setName(channelName + ".upstream.byteBuffers"); 468 charBufferPool().setName(channelName + ".upstream.charBuffers"); 469 // Allocate downstream buffer pools. Note that decoding WebSocket 470 // network packets may result in several WS frames that are each 471 // delivered in independent events. Therefore provide some 472 // additional buffers. 473 final int bufSize = bufferSize; 474 byteBufferPool = new ManagedBufferPool<>(ManagedBuffer::new, 475 () -> { 476 return ByteBuffer.allocate(bufSize); 477 }, 2, 100) 478 .setName(channelName + ".downstream.byteBuffers"); 479 charBufferPool = new ManagedBufferPool<>(ManagedBuffer::new, 480 () -> { 481 return CharBuffer.allocate(bufSize); 482 }, 2, 100) 483 .setName(channelName + ".downstream.charBuffers"); 484 485 // Downstream pipeline 486 downPipeline = newEventPipeline(); 487 } 488 489 /** 490 * Handle {@link Input} events from the network. 491 * 492 * @param event the event 493 * @throws ProtocolException the protocol exception 494 * @throws InterruptedException the interrupted exception 495 */ 496 @SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops", 497 "PMD.CollapsibleIfStatements", "PMD.CognitiveComplexity", 498 "PMD.AvoidDuplicateLiterals" }) 499 public void handleNetInput(Input<ByteBuffer> event) 500 throws ProtocolException, InterruptedException { 501 // Send the data from the event through the decoder. 502 ByteBuffer inData = event.data(); 503 // Don't unnecessary allocate a buffer, may be header only message 504 ManagedBuffer<?> bodyData = null; 505 boolean wasOverflow = false; 506 while (inData.hasRemaining()) { 507 if (wasOverflow) { 508 // Message has (more) body 509 bodyData = currentPool.acquire(); 510 } 511 Decoder.Result<?> result = engine.decode(inData, 512 bodyData == null ? null : bodyData.backingBuffer(), 513 event.isEndOfRecord()); 514 if (result.response().isPresent()) { 515 // Feedback required, send it "in sync", even if 516 // event source is not the regular one. 517 responsePipeline().overrideRestriction().fire( 518 new Response(result.response().get()), this); 519 if (result.isResponseOnly()) { 520 maybeCloseConnection(result); 521 continue; 522 } 523 } 524 if (result.isHeaderCompleted()) { 525 if (!handleRequestHeader(engine.currentRequest().get())) { 526 maybeCloseConnection(result); 527 break; 528 } 529 } 530 if (bodyData != null) { 531 if (bodyData.position() > 0) { 532 downPipeline.fire(Input.fromSink( 533 bodyData, !result.isOverflow() 534 && !result.isUnderflow()), 535 this); 536 } else { 537 bodyData.unlockBuffer(); 538 } 539 bodyData = null; 540 } 541 maybeCloseConnection(result); 542 wasOverflow = result.isOverflow(); 543 } 544 } 545 546 private void maybeCloseConnection(Decoder.Result<?> result) { 547 if (result.closeConnection()) { 548 // Send close "in sync", even if event source is unexpected. 549 responsePipeline().overrideRestriction() 550 .fire(new Close(), this); 551 } 552 } 553 554 @SuppressWarnings({ "PMD.CollapsibleIfStatements", 555 "PMD.CognitiveComplexity", "PMD.AvoidDeeplyNestedIfStmts" }) 556 private boolean handleRequestHeader(MessageHeader request) { 557 if (request instanceof HttpRequest) { 558 HttpRequest httpRequest = (HttpRequest) request; 559 if (httpRequest.hasPayload()) { 560 if (httpRequest.findValue( 561 HttpField.CONTENT_TYPE, Converters.MEDIA_TYPE) 562 .map(type -> "text" 563 .equalsIgnoreCase(type.value().topLevelType())) 564 .orElse(false)) { 565 currentPool = charBufferPool; 566 } else { 567 currentPool = byteBufferPool; 568 } 569 } 570 if (secure) { 571 if (!snis.contains(httpRequest.host())) { 572 if (acceptNoSni && snis.isEmpty()) { 573 convertHostToNumerical(httpRequest); 574 } else { 575 ResponseCreationSupport.sendResponse(httpRequest, 576 this, 421, "Misdirected Request"); 577 return false; 578 } 579 } 580 } 581 try { 582 downPipeline.fire(Request.In.fromHttpRequest(httpRequest, 583 secure, matchLevels), this); 584 } catch (URISyntaxException e) { 585 ResponseCreationSupport.sendResponse(httpRequest, this, 400, 586 "Bad Request"); 587 return false; 588 } 589 } else if (request instanceof WsMessageHeader) { 590 WsMessageHeader wsMessage = (WsMessageHeader) request; 591 if (wsMessage.hasPayload()) { 592 if (wsMessage.isTextMode()) { 593 currentPool = charBufferPool; 594 } else { 595 currentPool = byteBufferPool; 596 } 597 } 598 } else if (request instanceof WsCloseFrame) { 599 downPipeline.fire( 600 new WebSocketClose((WsCloseFrame) request, this)); 601 } 602 return true; 603 } 604 605 private void convertHostToNumerical(HttpRequest request) { 606 int port = request.port(); 607 String host; 608 try { 609 InetAddress addr = InetAddress.getByName( 610 request.host()); 611 host = addr.getHostAddress(); 612 if (!(addr instanceof Inet4Address)) { 613 host = "[" + host + "]"; 614 } 615 } catch (UnknownHostException e) { 616 host = InetAddress.getLoopbackAddress().getHostAddress(); 617 } 618 request.setHostAndPort(host, port); 619 } 620 621 /** 622 * Handle a response event from the application layer. 623 * 624 * @param event the event 625 * @throws InterruptedException the interrupted exception 626 */ 627 @SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops", 628 "PMD.AvoidBranchingStatementAsLastInLoop", 629 "PMD.CognitiveComplexity" }) 630 public void handleResponse(Response event) throws InterruptedException { 631 if (!engine.encoding() 632 .isAssignableFrom(event.response().getClass())) { 633 return; 634 } 635 final MessageHeader response = event.response(); 636 // Start sending the response 637 @SuppressWarnings("unchecked") 638 ServerEngine<?, MessageHeader> msgEngine 639 = (ServerEngine<?, MessageHeader>) engine; 640 msgEngine.encode(response); 641 if (pendingUpgraded != null) { 642 if (response instanceof HttpResponse 643 && ((HttpResponse) response).statusCode() % 100 == 1) { 644 downPipeline.fire(pendingUpgraded, this); 645 } 646 pendingUpgraded = null; 647 } 648 boolean hasBody = response.hasPayload(); 649 while (true) { 650 outBuffer = upstreamChannel().byteBufferPool().acquire(); 651 final ManagedBuffer<ByteBuffer> buffer = outBuffer; 652 Codec.Result result = engine.encode( 653 Codec.EMPTY_IN, buffer.backingBuffer(), !hasBody); 654 if (result.isOverflow()) { 655 upstreamChannel().respond(Output.fromSink(buffer, false)); 656 continue; 657 } 658 if (hasBody) { 659 // Keep buffer with incomplete response to be further 660 // filled by subsequent Output events 661 break; 662 } 663 // Response is complete 664 if (buffer.position() > 0) { 665 upstreamChannel().respond(Output.fromSink(buffer, true)); 666 } else { 667 buffer.unlockBuffer(); 668 } 669 outBuffer = null; 670 if (result.closeConnection()) { 671 upstreamChannel().respond(new Close()); 672 } 673 break; 674 } 675 676 } 677 678 /** 679 * Handle a {@link ProtocolSwitchAccepted} event from the 680 * application layer. 681 * 682 * @param event the event 683 * @param appChannel the app channel 684 */ 685 public void handleProtocolSwitchAccepted( 686 ProtocolSwitchAccepted event, WebAppMsgChannel appChannel) { 687 appChannel.setAssociated(URI.class, 688 event.requestEvent().requestUri()); 689 final HttpResponse response = event.requestEvent() 690 .httpRequest().response().get() 691 .setStatus(HttpStatus.SWITCHING_PROTOCOLS) 692 .setField(HttpField.UPGRADE, 693 new StringList(event.protocol())); 694 // We send the Upgraded event only after the response has 695 // successfully been encoded (and thus checked). 696 pendingUpgraded = new Upgraded(event.resourceName(), 697 event.protocol()); 698 respond(new Response(response)); 699 } 700 701 /** 702 * Handle output from the application layer. 703 * 704 * @param event the event 705 * @throws InterruptedException the interrupted exception 706 */ 707 @SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.NPathComplexity", 708 "PMD.AvoidInstantiatingObjectsInLoops", "PMD.CognitiveComplexity" }) 709 public void handleAppOutput(Output<?> event) 710 throws InterruptedException { 711 Buffer eventData = event.data(); 712 Buffer input; 713 if (eventData instanceof ByteBuffer) { 714 input = ((ByteBuffer) eventData).duplicate(); 715 } else if (eventData instanceof CharBuffer) { 716 input = ((CharBuffer) eventData).duplicate(); 717 } else { 718 return; 719 } 720 if (engine.switchedTo().equals(Optional.of("websocket")) 721 && currentWsMessage == null) { 722 // When switched to WebSockets, we only have Input and Output 723 // events. Add header automatically. 724 @SuppressWarnings("unchecked") 725 ServerEngine<?, MessageHeader> wsEngine 726 = (ServerEngine<?, MessageHeader>) engine; 727 currentWsMessage = new WsMessageHeader( 728 event.buffer().backingBuffer() instanceof CharBuffer, 729 true); 730 wsEngine.encode(currentWsMessage); 731 } 732 while (input.hasRemaining() || event.isEndOfRecord()) { 733 if (outBuffer == null) { 734 outBuffer = upstreamChannel().byteBufferPool().acquire(); 735 } 736 Codec.Result result = engine.encode(input, 737 outBuffer.backingBuffer(), event.isEndOfRecord()); 738 if (result.isOverflow()) { 739 upstreamChannel() 740 .respond(Output.fromSink(outBuffer, false)); 741 outBuffer = upstreamChannel().byteBufferPool().acquire(); 742 continue; 743 } 744 if (event.isEndOfRecord() || result.closeConnection()) { 745 if (outBuffer.position() > 0) { 746 upstreamChannel() 747 .respond(Output.fromSink(outBuffer, true)); 748 } else { 749 outBuffer.unlockBuffer(); 750 } 751 outBuffer = null; 752 if (result.closeConnection()) { 753 upstreamChannel().respond(new Close()); 754 } 755 break; 756 } 757 } 758 if (engine.switchedTo().equals(Optional.of("websocket")) 759 && event.isEndOfRecord()) { 760 currentWsMessage = null; 761 } 762 } 763 764 /** 765 * Handle a {@link Close} event from the application layer. 766 * 767 * @param event the event 768 * @throws InterruptedException the interrupted exception 769 */ 770 public void handleClose(Close event) throws InterruptedException { 771 if (engine.switchedTo().equals(Optional.of("websocket"))) { 772 fire(new Response(new WsCloseFrame(null, null)), this); 773 return; 774 } 775 upstreamChannel().respond(new Close()); 776 } 777 778 /** 779 * Handle a {@link Closed} event from the network by forwarding 780 * it to the application layer. 781 * 782 * @param event the event 783 */ 784 public void handleClosed(Closed<?> event) { 785 downPipeline.fire(new Closed<>(), this); 786 } 787 788 /** 789 * Handle a {@link Purge} event by forwarding it to the 790 * application layer. 791 * 792 * @param event the event 793 */ 794 public void handlePurge(Purge event) { 795 downPipeline.fire(new Purge(), this); 796 } 797 798 } 799 800}