Clean up onUnderlayChannelEstablished
[netconf.git] / transport / transport-ssh / src / main / java / org / opendaylight / netconf / transport / ssh / SSHTransportStack.java
1 /*
2  * Copyright (c) 2022 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.ssh;
9
10 import java.util.Collection;
11 import java.util.Map;
12 import java.util.concurrent.ConcurrentHashMap;
13 import org.opendaylight.netconf.shaded.sshd.common.io.IoHandler;
14 import org.opendaylight.netconf.shaded.sshd.common.session.Session;
15 import org.opendaylight.netconf.shaded.sshd.netty.NettyIoService;
16 import org.opendaylight.netconf.transport.api.AbstractOverlayTransportStack;
17 import org.opendaylight.netconf.transport.api.TransportChannel;
18 import org.opendaylight.netconf.transport.api.TransportChannelListener;
19 import org.opendaylight.netconf.transport.api.TransportStack;
20
21 /**
22  * An SSH {@link TransportStack}. Instances of this class are built indirectly.
23  */
24 public abstract sealed class SSHTransportStack extends AbstractOverlayTransportStack<SSHTransportChannel>
25         permits SSHClient, SSHServer {
26     protected final Map<Long, UserAuthSessionListener.AuthHandler> sessionAuthHandlers = new ConcurrentHashMap<>();
27     protected final Map<Long, Session> sessions = new ConcurrentHashMap<>();
28     protected NettyIoService ioService;
29
30     SSHTransportStack(final TransportChannelListener listener) {
31         super(listener);
32     }
33
34     @Override
35     protected void onUnderlayChannelEstablished(final TransportChannel underlayChannel) {
36         final var channel = underlayChannel.channel();
37         final var ioSession = new SshIoSession(ioService, getSessionFactory(), channel.localAddress());
38         channel.pipeline().addLast(ioSession.getHandler());
39         // authentication triggering and handlers processing is performed by UserAuthSessionListener
40         sessionAuthHandlers.put(ioSession.getId(), new UserAuthSessionListener.AuthHandler(
41             // auth success
42             () -> addTransportChannel(new SSHTransportChannel(underlayChannel)),
43             // auth failure
44             () -> channel.close())
45         );
46     }
47
48     abstract IoHandler getSessionFactory();
49
50     public Collection<Session> getSessions() {
51         return sessions.values();
52     }
53
54 }