Refactor transport-http response delivery
[netconf.git] / transport / transport-http / src / main / java / org / opendaylight / netconf / transport / http / ServerChannelInitializer.java
1 /*
2  * Copyright (c) 2024 PANTHEON.tech s.r.o. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netconf.transport.http;
9
10 import static io.netty.buffer.Unpooled.EMPTY_BUFFER;
11 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
12 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
13 import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN;
14 import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
15 import static org.opendaylight.netconf.transport.http.Http2Utils.copyStreamId;
16
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.SettableFuture;
20 import io.netty.buffer.Unpooled;
21 import io.netty.channel.Channel;
22 import io.netty.channel.ChannelHandler;
23 import io.netty.channel.ChannelHandlerContext;
24 import io.netty.channel.ChannelInitializer;
25 import io.netty.channel.ChannelPipeline;
26 import io.netty.channel.SimpleChannelInboundHandler;
27 import io.netty.handler.codec.http.DefaultFullHttpResponse;
28 import io.netty.handler.codec.http.FullHttpRequest;
29 import io.netty.handler.codec.http.FullHttpResponse;
30 import io.netty.handler.codec.http.HttpMessage;
31 import io.netty.handler.codec.http.HttpObjectAggregator;
32 import io.netty.handler.codec.http.HttpServerCodec;
33 import io.netty.handler.codec.http.HttpServerKeepAliveHandler;
34 import io.netty.handler.codec.http.HttpServerUpgradeHandler;
35 import io.netty.handler.codec.http2.CleartextHttp2ServerUpgradeHandler;
36 import io.netty.handler.codec.http2.Http2CodecUtil;
37 import io.netty.handler.codec.http2.Http2ConnectionHandler;
38 import io.netty.handler.codec.http2.Http2ServerUpgradeCodec;
39 import io.netty.handler.ssl.ApplicationProtocolNames;
40 import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler;
41 import io.netty.handler.ssl.SslHandler;
42 import io.netty.util.AsciiString;
43 import io.netty.util.ReferenceCountUtil;
44 import java.nio.charset.StandardCharsets;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.http.server.rev240208.HttpServerGrouping;
46
47 /**
48  * Netty channel initializer for Http Server.
49  */
50 class ServerChannelInitializer extends ChannelInitializer<Channel> implements HttpChannelInitializer {
51     private static final int MAX_HTTP_CONTENT_LENGTH = 16 * 1024;
52
53     private final SettableFuture<Void> completeFuture = SettableFuture.create();
54     private final ChannelHandler authHandler;
55     private final RequestDispatcher dispatcher;
56
57     ServerChannelInitializer(final HttpServerGrouping httpParams, final RequestDispatcher dispatcher) {
58         authHandler = BasicAuthHandler.ofNullable(httpParams);
59         this.dispatcher = dispatcher;
60     }
61
62     @Override
63     public ListenableFuture<Void> completeFuture() {
64         return completeFuture;
65     }
66
67     @Override
68     protected void initChannel(final Channel channel) throws Exception {
69         final var pipeline = channel.pipeline();
70         final var ssl = pipeline.get(SslHandler.class) != null;
71
72         // External HTTP 2 to internal HTTP 1.1 adapter handler
73         final var connectionHandler = Http2Utils.connectionHandler(true, MAX_HTTP_CONTENT_LENGTH);
74         if (ssl) {
75             // Application protocol negotiator over TLS
76             pipeline.addLast(apnHandler(connectionHandler));
77         } else {
78             // Cleartext upgrade flow
79             final var sourceCodec = new HttpServerCodec();
80             final var upgradeHandler =
81                 new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory(connectionHandler));
82             pipeline.addLast(new CleartextHttp2ServerUpgradeHandler(sourceCodec, upgradeHandler, connectionHandler),
83                 upgradeResultHandler());
84         }
85
86         // signal server transport is ready to accept requests
87         completeFuture.set(null);
88     }
89
90     private void configureEndOfPipeline(final ChannelPipeline pipeline) {
91         if (authHandler != null) {
92             pipeline.addLast(authHandler);
93         }
94         pipeline.addLast(serverHandler(dispatcher));
95     }
96
97     private ChannelHandler apnHandler(final ChannelHandler connectionHandler) {
98         return new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {
99             @Override
100             protected void configurePipeline(final ChannelHandlerContext ctx, final String protocol) throws Exception {
101                 final var pipeline = ctx.pipeline();
102                 if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
103                     pipeline.addLast(connectionHandler);
104                     configureEndOfPipeline(pipeline);
105                     return;
106                 }
107                 if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
108                     pipeline.addLast(new HttpServerCodec(),
109                         new HttpServerKeepAliveHandler(),
110                         new HttpObjectAggregator(MAX_HTTP_CONTENT_LENGTH));
111                     configureEndOfPipeline(pipeline);
112                     return;
113                 }
114                 throw new IllegalStateException("unknown protocol: " + protocol);
115             }
116         };
117     }
118
119     private ChannelHandler upgradeResultHandler() {
120         // the handler processes cleartext upgrade result
121
122         return new SimpleChannelInboundHandler<HttpMessage>() {
123             @Override
124             protected void channelRead0(final ChannelHandlerContext ctx, final HttpMessage request) throws Exception {
125                 // if there was no upgrade to HTTP/2 the incoming message is accepted via channel read;
126                 // configure HTTP 1.1 flow, pass the message further the pipeline, remove self as no longer required
127                 final var pipeline = ctx.pipeline();
128                 pipeline.addLast(new HttpServerKeepAliveHandler(), new HttpObjectAggregator(MAX_HTTP_CONTENT_LENGTH));
129                 configureEndOfPipeline(pipeline);
130                 ctx.fireChannelRead(ReferenceCountUtil.retain(request));
131                 pipeline.remove(this);
132             }
133
134             @Override
135             public void userEventTriggered(final ChannelHandlerContext ctx, final Object event) throws Exception {
136                 // if there was upgrade to HTTP/2 the upgrade event is fired further the pipeline;
137                 // on event occurrence it's only required to complete the configuration for future requests,
138                 // then remove self as no longer required
139                 if (event instanceof HttpServerUpgradeHandler.UpgradeEvent) {
140                     final var pipeline = ctx.pipeline();
141                     configureEndOfPipeline(pipeline);
142                     pipeline.remove(this);
143                 }
144             }
145         };
146     }
147
148     private static HttpServerUpgradeHandler.UpgradeCodecFactory upgradeCodecFactory(
149             final Http2ConnectionHandler connectionHandler) {
150         return protocol -> AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)
151             ? new Http2ServerUpgradeCodec(connectionHandler) : null;
152     }
153
154     private static ChannelHandler serverHandler(final RequestDispatcher dispatcher) {
155         return new SimpleChannelInboundHandler<FullHttpRequest>() {
156             @Override
157             protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) {
158                 dispatcher.dispatch(request.retain(), new FutureCallback<>() {
159                     @Override
160                     public void onSuccess(final FullHttpResponse response) {
161                         copyStreamId(request, response);
162                         request.release();
163                         ctx.writeAndFlush(response);
164                     }
165
166                     @Override
167                     public void onFailure(final Throwable throwable) {
168                         final var message = throwable.getMessage();
169                         final var content = message == null ? EMPTY_BUFFER
170                             : Unpooled.wrappedBuffer(message.getBytes(StandardCharsets.UTF_8));
171                         final var response = new DefaultFullHttpResponse(request.protocolVersion(),
172                             INTERNAL_SERVER_ERROR, content);
173                         response.headers()
174                             .set(CONTENT_TYPE, TEXT_PLAIN)
175                             .setInt(CONTENT_LENGTH, response.content().readableBytes());
176                         onSuccess(response);
177                     }
178                 });
179             }
180         };
181     }
182 }