Adjust window on read
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / ssh / client / NettyAwareChannelSubsystem.java
1 /*
2  * Copyright (c) 2019 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.nettyutil.handler.ssh.client;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import io.netty.buffer.Unpooled;
14 import io.netty.channel.ChannelHandlerContext;
15 import java.io.IOException;
16 import org.opendaylight.netconf.shaded.sshd.client.channel.ChannelSubsystem;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 /**
21  * A {@link ChannelSubsystem} for subsystem which routes incoming data to a particular {@link ChannelHandlerContext}.
22  */
23 @Beta
24 public class NettyAwareChannelSubsystem extends ChannelSubsystem {
25     private static final Logger LOG = LoggerFactory.getLogger(NettyAwareChannelSubsystem.class);
26
27     private final ChannelHandlerContext ctx;
28
29     public NettyAwareChannelSubsystem(final String subsystem, final ChannelHandlerContext ctx) {
30         super(subsystem);
31         this.ctx = requireNonNull(ctx);
32     }
33
34     @Override
35     protected void doWriteData(final byte[] data, final int off, final long len) throws IOException {
36         // If we're already closing, ignore incoming data
37         if (!isClosing()) {
38             // TODO: consider using context's allocator for heap buffer here
39             ctx.fireChannelRead(Unpooled.copiedBuffer(data, off, (int) len));
40             adjustWindow(len);
41         }
42     }
43
44     @Override
45     protected void doWriteExtendedData(final byte[] data, final int off, final long len) throws IOException {
46         // If we're already closing, ignore incoming data
47         if (!isClosing()) {
48             LOG.debug("Discarding {} bytes of extended data", len);
49             adjustWindow(len);
50         }
51     }
52
53     private void adjustWindow(final long len) throws IOException {
54         getLocalWindow().consumeAndCheck(len);
55     }
56
57     @Override
58     public void close() {
59         this.close(false);
60     }
61 }