/
AbstractConnectionService.java
727 lines (649 loc) · 27.7 KB
/
AbstractConnectionService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sshd.common.session.helpers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.IntUnaryOperator;
import org.apache.sshd.agent.common.AgentForwardSupport;
import org.apache.sshd.agent.common.DefaultAgentForwardSupport;
import org.apache.sshd.client.channel.AbstractClientChannel;
import org.apache.sshd.common.Closeable;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.SshConstants;
import org.apache.sshd.common.SshException;
import org.apache.sshd.common.channel.AbstractChannel;
import org.apache.sshd.common.channel.Channel;
import org.apache.sshd.common.channel.RequestHandler;
import org.apache.sshd.common.channel.Window;
import org.apache.sshd.common.channel.exception.SshChannelNotFoundException;
import org.apache.sshd.common.channel.exception.SshChannelOpenException;
import org.apache.sshd.common.forward.ForwardingFilter;
import org.apache.sshd.common.forward.ForwardingFilterFactory;
import org.apache.sshd.common.forward.PortForwardingEventListener;
import org.apache.sshd.common.forward.PortForwardingEventListenerManager;
import org.apache.sshd.common.io.AbstractIoWriteFuture;
import org.apache.sshd.common.io.IoWriteFuture;
import org.apache.sshd.common.session.ConnectionService;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.common.util.EventListenerUtils;
import org.apache.sshd.common.util.GenericUtils;
import org.apache.sshd.common.util.Int2IntFunction;
import org.apache.sshd.common.util.ValidateUtils;
import org.apache.sshd.common.util.buffer.Buffer;
import org.apache.sshd.common.util.closeable.AbstractInnerCloseable;
import org.apache.sshd.server.x11.DefaultX11ForwardSupport;
import org.apache.sshd.server.x11.X11ForwardSupport;
/**
* Base implementation of ConnectionService.
*
* @param <S> Type of {@link AbstractSession} being used
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public abstract class AbstractConnectionService<S extends AbstractSession>
extends AbstractInnerCloseable
implements ConnectionService {
/**
* Property that can be used to configure max. allowed concurrent active channels
*
* @see #registerChannel(Channel)
*/
public static final String MAX_CONCURRENT_CHANNELS_PROP = "max-sshd-channels";
/**
* Default value for {@link #MAX_CONCURRENT_CHANNELS_PROP} is none specified
*/
public static final int DEFAULT_MAX_CHANNELS = Integer.MAX_VALUE;
/**
* Default growth factor function used to resize response buffers
*/
public static final IntUnaryOperator RESPONSE_BUFFER_GROWTH_FACTOR = Int2IntFunction.add(Byte.SIZE);
/**
* Map of channels keyed by the identifier
*/
protected final Map<Integer, Channel> channels = new ConcurrentHashMap<>();
/**
* Next channel identifier
*/
protected final AtomicInteger nextChannelId = new AtomicInteger(0);
private final AtomicReference<AgentForwardSupport> agentForwardHolder = new AtomicReference<>();
private final AtomicReference<X11ForwardSupport> x11ForwardHolder = new AtomicReference<>();
private final AtomicReference<ForwardingFilter> forwarderHolder = new AtomicReference<>();
private final AtomicBoolean allowMoreSessions = new AtomicBoolean(true);
private final Collection<PortForwardingEventListener> listeners = new CopyOnWriteArraySet<>();
private final Collection<PortForwardingEventListenerManager> managersHolder = new CopyOnWriteArraySet<>();
private final PortForwardingEventListener listenerProxy;
private final S sessionInstance;
protected AbstractConnectionService(S session) {
sessionInstance = Objects.requireNonNull(session, "No session");
listenerProxy = EventListenerUtils.proxyWrapper(PortForwardingEventListener.class, getClass().getClassLoader(), listeners);
}
@Override
public PortForwardingEventListener getPortForwardingEventListenerProxy() {
return listenerProxy;
}
@Override
public void addPortForwardingEventListener(PortForwardingEventListener listener) {
listeners.add(PortForwardingEventListener.validateListener(listener));
}
@Override
public void removePortForwardingEventListener(PortForwardingEventListener listener) {
if (listener == null) {
return;
}
listeners.remove(PortForwardingEventListener.validateListener(listener));
}
@Override
public Collection<PortForwardingEventListenerManager> getRegisteredManagers() {
return managersHolder.isEmpty() ? Collections.emptyList() : new ArrayList<>(managersHolder);
}
@Override
public boolean addPortForwardingEventListenerManager(PortForwardingEventListenerManager manager) {
return managersHolder.add(Objects.requireNonNull(manager, "No manager"));
}
@Override
public boolean removePortForwardingEventListenerManager(PortForwardingEventListenerManager manager) {
if (manager == null) {
return false;
}
return managersHolder.remove(manager);
}
public Collection<Channel> getChannels() {
return channels.values();
}
@Override
public S getSession() {
return sessionInstance;
}
@Override
public void start() {
// do nothing
}
@Override
public ForwardingFilter getForwardingFilter() {
ForwardingFilter forwarder;
S session = getSession();
synchronized (forwarderHolder) {
forwarder = forwarderHolder.get();
if (forwarder != null) {
return forwarder;
}
forwarder = ValidateUtils.checkNotNull(createForwardingFilter(session), "No forwarder created for %s", session);
forwarderHolder.set(forwarder);
}
if (log.isDebugEnabled()) {
log.debug("getForwardingFilter({}) created instance", session);
}
return forwarder;
}
@Override
protected void preClose() {
this.listeners.clear();
this.managersHolder.clear();
super.preClose();
}
protected ForwardingFilter createForwardingFilter(S session) {
FactoryManager manager =
Objects.requireNonNull(session.getFactoryManager(), "No factory manager");
ForwardingFilterFactory factory =
Objects.requireNonNull(manager.getForwarderFactory(), "No forwarder factory");
ForwardingFilter forwarder = factory.create(this);
forwarder.addPortForwardingEventListenerManager(this);
return forwarder;
}
@Override
public X11ForwardSupport getX11ForwardSupport() {
X11ForwardSupport x11Support;
S session = getSession();
synchronized (x11ForwardHolder) {
x11Support = x11ForwardHolder.get();
if (x11Support != null) {
return x11Support;
}
x11Support = ValidateUtils.checkNotNull(createX11ForwardSupport(session), "No X11 forwarder created for %s", session);
x11ForwardHolder.set(x11Support);
}
if (log.isDebugEnabled()) {
log.debug("getX11ForwardSupport({}) created instance", session);
}
return x11Support;
}
protected X11ForwardSupport createX11ForwardSupport(S session) {
return new DefaultX11ForwardSupport(this);
}
@Override
public AgentForwardSupport getAgentForwardSupport() {
AgentForwardSupport agentForward;
S session = getSession();
synchronized (agentForwardHolder) {
agentForward = agentForwardHolder.get();
if (agentForward != null) {
return agentForward;
}
agentForward = ValidateUtils.checkNotNull(createAgentForwardSupport(session), "No agent forward created for %s", session);
agentForwardHolder.set(agentForward);
}
if (log.isDebugEnabled()) {
log.debug("getAgentForwardSupport({}) created instance", session);
}
return agentForward;
}
protected AgentForwardSupport createAgentForwardSupport(S session) {
return new DefaultAgentForwardSupport(this);
}
@Override
protected Closeable getInnerCloseable() {
return builder()
.sequential(forwarderHolder.get(), agentForwardHolder.get(), x11ForwardHolder.get())
.parallel(toString(), channels.values())
.build();
}
protected int getNextChannelId() {
return nextChannelId.getAndIncrement();
}
@Override
public int registerChannel(Channel channel) throws IOException {
Session session = getSession();
int maxChannels = session.getIntProperty(MAX_CONCURRENT_CHANNELS_PROP, DEFAULT_MAX_CHANNELS);
int curSize = channels.size();
if (curSize > maxChannels) {
throw new IllegalStateException("Currently active channels (" + curSize + ") at max.: " + maxChannels);
}
int channelId = getNextChannelId();
channel.init(this, session, channelId);
boolean registered = false;
synchronized (lock) {
if (!isClosing()) {
channels.put(channelId, channel);
registered = true;
}
}
if (!registered) {
handleChannelRegistrationFailure(channel, channelId);
}
if (log.isDebugEnabled()) {
log.debug("registerChannel({})[id={}] {}", this, channelId, channel);
}
return channelId;
}
protected void handleChannelRegistrationFailure(Channel channel, int channelId) throws IOException {
RuntimeException reason = new IllegalStateException("Channel id=" + channelId + " not registered because session is being closed: " + this);
AbstractChannel notifier =
ValidateUtils.checkInstanceOf(channel, AbstractChannel.class, "Non abstract channel for id=%d", channelId);
notifier.signalChannelClosed(reason);
throw reason;
}
/**
* Remove this channel from the list of managed channels
*
* @param channel the channel
*/
@Override
public void unregisterChannel(Channel channel) {
int channelId = channel.getId();
Channel result = channels.remove(channelId);
if (log.isDebugEnabled()) {
log.debug("unregisterChannel({}) result={}", channel, result);
}
}
@Override
public void process(int cmd, Buffer buffer) throws Exception {
switch (cmd) {
case SshConstants.SSH_MSG_CHANNEL_OPEN:
channelOpen(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
channelOpenConfirmation(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_OPEN_FAILURE:
channelOpenFailure(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_REQUEST:
channelRequest(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_DATA:
channelData(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_EXTENDED_DATA:
channelExtendedData(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_FAILURE:
channelFailure(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_SUCCESS:
channelSuccess(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_WINDOW_ADJUST:
channelWindowAdjust(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_EOF:
channelEof(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_CLOSE:
channelClose(buffer);
break;
case SshConstants.SSH_MSG_GLOBAL_REQUEST:
globalRequest(buffer);
break;
case SshConstants.SSH_MSG_REQUEST_SUCCESS:
requestSuccess(buffer);
break;
case SshConstants.SSH_MSG_REQUEST_FAILURE:
requestFailure(buffer);
break;
default:
throw new IllegalStateException("Unsupported command: " + SshConstants.getCommandMessageName(cmd));
}
}
@Override
public boolean isAllowMoreSessions() {
return allowMoreSessions.get();
}
@Override
public void setAllowMoreSessions(boolean allow) {
if (log.isDebugEnabled()) {
log.debug("setAllowMoreSessions({}): {}", this, allow);
}
allowMoreSessions.set(allow);
}
public void channelOpenConfirmation(Buffer buffer) throws IOException {
Channel channel = getChannel(buffer);
int sender = buffer.getInt();
long rwsize = buffer.getUInt();
long rmpsize = buffer.getUInt();
if (log.isDebugEnabled()) {
log.debug("channelOpenConfirmation({}) SSH_MSG_CHANNEL_OPEN_CONFIRMATION sender={}, window-size={}, packet-size={}",
channel, sender, rwsize, rmpsize);
}
/*
* NOTE: the 'sender' of the SSH_MSG_CHANNEL_OPEN_CONFIRMATION is the
* recipient on the client side - see rfc4254 section 5.1:
*
* 'sender channel' is the channel number allocated by the other side
*
* in our case, the server
*/
channel.handleOpenSuccess(sender, rwsize, rmpsize, buffer);
}
public void channelOpenFailure(Buffer buffer) throws IOException {
AbstractClientChannel channel = (AbstractClientChannel) getChannel(buffer);
int id = channel.getId();
if (log.isDebugEnabled()) {
log.debug("channelOpenFailure({}) Received SSH_MSG_CHANNEL_OPEN_FAILURE", channel);
}
channels.remove(id);
channel.handleOpenFailure(buffer);
}
/**
* Process incoming data on a channel
*
* @param buffer the buffer containing the data
* @throws IOException if an error occurs
*/
public void channelData(Buffer buffer) throws IOException {
Channel channel = getChannel(buffer);
channel.handleData(buffer);
}
/**
* Process incoming extended data on a channel
*
* @param buffer the buffer containing the data
* @throws IOException if an error occurs
*/
public void channelExtendedData(Buffer buffer) throws IOException {
Channel channel = getChannel(buffer);
channel.handleExtendedData(buffer);
}
/**
* Process a window adjust packet on a channel
*
* @param buffer the buffer containing the window adjustment parameters
* @throws IOException if an error occurs
*/
public void channelWindowAdjust(Buffer buffer) throws IOException {
try {
// Do not use getChannel to avoid the session being closed
// if receiving the SSH_MSG_CHANNEL_WINDOW_ADJUST on an already closed channel
int recipient = buffer.getInt();
Channel channel = channels.get(recipient);
if (channel != null) {
channel.handleWindowAdjust(buffer);
} else {
log.warn("Received SSH_MSG_CHANNEL_WINDOW_ADJUST on unknown channel " + recipient);
}
} catch (SshException e) {
if (log.isDebugEnabled()) {
log.debug("channelWindowAdjust {} error: {}", e.getClass().getSimpleName(), e.getMessage());
}
}
}
/**
* Process end of file on a channel
*
* @param buffer the buffer containing the packet
* @throws IOException if an error occurs
*/
public void channelEof(Buffer buffer) throws IOException {
// Do not use getChannel to avoid the session being closed
// if receiving the SSH_MSG_CHANNEL_EOF on an already closed channel
int recipient = buffer.getInt();
Channel channel = channels.get(recipient);
if (channel != null) {
channel.handleEof();
} else {
log.warn("Received SSH_MSG_CHANNEL_EOF on unknown channel " + recipient);
}
}
/**
* Close a channel due to a close packet received
*
* @param buffer the buffer containing the packet
* @throws IOException if an error occurs
*/
public void channelClose(Buffer buffer) throws IOException {
// Do not use getChannel to avoid the session being closed
// if receiving the SSH_MSG_CHANNEL_CLOSE on an already closed channel
int recipient = buffer.getInt();
Channel channel = channels.get(recipient);
if (channel != null) {
channel.handleClose();
} else {
log.warn("Received SSH_MSG_CHANNEL_CLOSE on unknown channel " + recipient);
}
}
/**
* Service a request on a channel
*
* @param buffer the buffer containing the request
* @throws IOException if an error occurs
*/
public void channelRequest(Buffer buffer) throws IOException {
Channel channel = getChannel(buffer);
channel.handleRequest(buffer);
}
/**
* Process a failure on a channel
*
* @param buffer the buffer containing the packet
* @throws IOException if an error occurs
*/
public void channelFailure(Buffer buffer) throws IOException {
Channel channel = getChannel(buffer);
channel.handleFailure();
}
/**
* Process a success on a channel
*
* @param buffer the buffer containing the packet
* @throws IOException if an error occurs
*/
public void channelSuccess(Buffer buffer) throws IOException {
Channel channel = getChannel(buffer);
channel.handleSuccess();
}
/**
* Retrieve the channel designated by the given packet
*
* @param buffer the incoming packet
* @return the target channel
* @throws IOException if the channel does not exists
*/
protected Channel getChannel(Buffer buffer) throws IOException {
return getChannel(buffer.getInt(), buffer);
}
protected Channel getChannel(int recipient, Buffer buffer) throws IOException {
Channel channel = channels.get(recipient);
if (channel == null) {
byte[] data = buffer.array();
int curPos = buffer.rpos();
int cmd = (curPos >= 5) ? (data[curPos - 5] & 0xFF) : -1;
// Throw a special exception - SSHD-776
throw new SshChannelNotFoundException(recipient,
"Received " + SshConstants.getCommandMessageName(cmd) + " on unknown channel " + recipient);
}
return channel;
}
protected void channelOpen(Buffer buffer) throws Exception {
String type = buffer.getString();
final int sender = buffer.getInt();
final long rwsize = buffer.getUInt();
final long rmpsize = buffer.getUInt();
/*
* NOTE: the 'sender' is the identifier assigned by the remote side - the server in this case
*/
if (log.isDebugEnabled()) {
log.debug("channelOpen({}) SSH_MSG_CHANNEL_OPEN sender={}, type={}, window-size={}, packet-size={}",
this, sender, type, rwsize, rmpsize);
}
if (isClosing()) {
// TODO add language tag
sendChannelOpenFailure(buffer, sender, SshConstants.SSH_OPEN_CONNECT_FAILED, "Server is shutting down while attempting to open channel type=" + type, "");
return;
}
if (!isAllowMoreSessions()) {
// TODO add language tag
sendChannelOpenFailure(buffer, sender, SshConstants.SSH_OPEN_CONNECT_FAILED, "additional sessions disabled", "");
return;
}
final Session session = getSession();
FactoryManager manager = Objects.requireNonNull(session.getFactoryManager(), "No factory manager");
final Channel channel = NamedFactory.create(manager.getChannelFactories(), type);
if (channel == null) {
// TODO add language tag
sendChannelOpenFailure(buffer, sender, SshConstants.SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "Unsupported channel type: " + type, "");
return;
}
final int channelId = registerChannel(channel);
channel.open(sender, rwsize, rmpsize, buffer).addListener(future -> {
try {
if (future.isOpened()) {
Window window = channel.getLocalWindow();
if (log.isDebugEnabled()) {
log.debug("operationComplete({}) send SSH_MSG_CHANNEL_OPEN_CONFIRMATION recipient={}, sender={}, window-size={}, packet-size={}",
channel, sender, channelId, window.getSize(), window.getPacketSize());
}
Buffer buf = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN_CONFIRMATION, Integer.SIZE);
buf.putInt(sender); // remote (server side) identifier
buf.putInt(channelId); // local (client side) identifier
buf.putInt(window.getSize());
buf.putInt(window.getPacketSize());
session.writePacket(buf);
} else {
Throwable exception = future.getException();
if (exception != null) {
String message = exception.getMessage();
int reasonCode = 0;
if (exception instanceof SshChannelOpenException) {
reasonCode = ((SshChannelOpenException) exception).getReasonCode();
} else {
message = exception.getClass().getSimpleName() + " while opening channel: " + message;
}
Buffer buf = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN_FAILURE, message.length() + Long.SIZE);
sendChannelOpenFailure(buf, sender, reasonCode, message, "");
}
}
} catch (IOException e) {
if (log.isDebugEnabled()) {
log.debug("operationComplete({}) {}: {}",
AbstractConnectionService.this, e.getClass().getSimpleName(), e.getMessage());
}
session.exceptionCaught(e);
}
});
}
protected IoWriteFuture sendChannelOpenFailure(Buffer buffer, int sender, int reasonCode, String message, String lang) throws IOException {
if (log.isDebugEnabled()) {
log.debug("sendChannelOpenFailure({}) sender={}, reason={}, lang={}, message='{}'",
this, sender, SshConstants.getOpenErrorCodeName(reasonCode), lang, message);
}
Session session = getSession();
Buffer buf = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN_FAILURE,
Long.SIZE + GenericUtils.length(message) + GenericUtils.length(lang));
buf.putInt(sender);
buf.putInt(reasonCode);
buf.putString(message);
buf.putString(lang);
return session.writePacket(buf);
}
/**
* Process global requests
*
* @param buffer The request {@link Buffer}
* @throws Exception If failed to process the request
*/
protected void globalRequest(Buffer buffer) throws Exception {
String req = buffer.getString();
boolean wantReply = buffer.getBoolean();
if (log.isDebugEnabled()) {
log.debug("globalRequest({}) received SSH_MSG_GLOBAL_REQUEST {} want-reply={}",
this, req, wantReply);
}
Session session = getSession();
FactoryManager manager =
Objects.requireNonNull(session.getFactoryManager(), "No factory manager");
List<RequestHandler<ConnectionService>> handlers = manager.getGlobalRequestHandlers();
if (GenericUtils.size(handlers) > 0) {
for (RequestHandler<ConnectionService> handler : handlers) {
RequestHandler.Result result;
try {
result = handler.process(this, req, wantReply, buffer);
} catch (Throwable e) {
log.warn("globalRequest({})[{}, want-reply={}] failed ({}) to process: {}",
this, req, wantReply, e.getClass().getSimpleName(), e.getMessage());
if (log.isDebugEnabled()) {
log.debug("globalRequest(" + this + ")[" + req + ", want-reply=" + wantReply + "] failure details", e);
}
result = RequestHandler.Result.ReplyFailure;
}
// if Unsupported then check the next handler in line
if (RequestHandler.Result.Unsupported.equals(result)) {
if (log.isTraceEnabled()) {
log.trace("globalRequest({}) {}#process({})[want-reply={}] : {}",
this, handler.getClass().getSimpleName(), req, wantReply, result);
}
} else {
sendGlobalResponse(buffer, req, result, wantReply);
return;
}
}
}
handleUnknownRequest(buffer, req, wantReply);
}
protected void handleUnknownRequest(Buffer buffer, String req, boolean wantReply) throws IOException {
log.warn("handleUnknownRequest({}) unknown global request: {}", this, req);
sendGlobalResponse(buffer, req, RequestHandler.Result.Unsupported, wantReply);
}
protected IoWriteFuture sendGlobalResponse(Buffer buffer, String req, RequestHandler.Result result, boolean wantReply) throws IOException {
if (log.isDebugEnabled()) {
log.debug("sendGlobalResponse({})[{}] result={}, want-reply={}", this, req, result, wantReply);
}
if (RequestHandler.Result.Replied.equals(result) || (!wantReply)) {
return new AbstractIoWriteFuture(req, null) {
{
setValue(Boolean.TRUE);
}
};
}
byte cmd = RequestHandler.Result.ReplySuccess.equals(result)
? SshConstants.SSH_MSG_REQUEST_SUCCESS
: SshConstants.SSH_MSG_REQUEST_FAILURE;
Session session = getSession();
Buffer rsp = session.createBuffer(cmd, 2);
return session.writePacket(rsp);
}
protected void requestSuccess(Buffer buffer) throws Exception {
getSession().requestSuccess(buffer);
}
protected void requestFailure(Buffer buffer) throws Exception {
getSession().requestFailure(buffer);
}
@Override
public String toString() {
return getClass().getSimpleName() + "[" + getSession() + "]";
}
}