@Override public TransportException chain(Throwable t) { if (t instanceof TransportException) return (TransportException) t; else return new TransportException(t); } };
public void makeDirectory(InvocationContext context) throws ProviderException { ApplicationDeploymentDescriptionType app = context.getExecutionDescription().getApp().getType(); Session session = null; try { session = getSession(context); StringBuilder commandString = new StringBuilder(); commandString.append("mkdir -p "); commandString.append(app.getScratchWorkingDirectory()); commandString.append(" ; "); commandString.append("mkdir -p "); commandString.append(app.getStaticWorkingDirectory()); commandString.append(" ; "); commandString.append("mkdir -p "); commandString.append(app.getInputDataDirectory()); commandString.append(" ; "); commandString.append("mkdir -p "); commandString.append(app.getOutputDataDirectory()); Command cmd = session.exec(commandString.toString()); cmd.join(COMMAND_EXECUTION_TIMEOUT, TimeUnit.SECONDS); } catch (ConnectionException e) { throw new ProviderException(e.getMessage(), e); } catch (TransportException e) { throw new ProviderException(e.getMessage(), e); } catch (IOException e) { throw new ProviderException(e.getMessage(), e); } finally { closeSession(session); } }
public Map<String, ?> processOutput(InvocationContext context) throws ProviderException { ApplicationDeploymentDescriptionType app = context.getExecutionDescription().getApp().getType(); try { // Get the Stdouts and StdErrs String timeStampedServiceName = GfacUtils.createUniqueNameForService(context.getServiceName()); File localStdOutFile = File.createTempFile(timeStampedServiceName, "stdout"); File localStdErrFile = File.createTempFile(timeStampedServiceName, "stderr"); SCPFileTransfer fileTransfer = ssh.newSCPFileTransfer(); fileTransfer.download(app.getStandardOutput(), localStdOutFile.getAbsolutePath()); fileTransfer.download(app.getStandardError(), localStdErrFile.getAbsolutePath()); String stdOutStr = GfacUtils.readFileToString(localStdOutFile.getAbsolutePath()); String stdErrStr = GfacUtils.readFileToString(localStdErrFile.getAbsolutePath()); return OutputUtils.fillOutputFromStdout(context.<ActualParameter> getOutput(), stdOutStr); } catch (XmlException e) { throw new ProviderException("Cannot read output:" + e.getMessage(), e); } catch (ConnectionException e) { throw new ProviderException(e.getMessage(), e); } catch (TransportException e) { throw new ProviderException(e.getMessage(), e); } catch (IOException e) { throw new ProviderException(e.getMessage(), e); } }
@SuppressWarnings("PMD.CompareObjectsWithEquals") private static void ensureReceivedMatchesExpected(Message got, Message expected) throws TransportException { if (got != expected) throw new TransportException(DisconnectReason.PROTOCOL_ERROR, "Was expecting " + expected); }
private static String firstMatch(List<String> a, List<String> b) throws TransportException { for (String aa : a) for (String bb : b) if (aa.equals(bb)) return aa; throw new TransportException("Unable to reach a settlement: " + a + " and " + b); }
private synchronized void ensureKexOngoing() throws TransportException { if (!isKexOngoing()) throw new TransportException(DisconnectReason.PROTOCOL_ERROR, "Key exchange packet received when key exchange was not ongoing"); }
private void checkPacketLength(int len) throws TransportException { if (len < 5 || len > MAX_PACKET_LEN) { // Check packet length validity log.error("Error decoding packet (invalid length) {}", inputBuffer.printHex()); throw new TransportException(DisconnectReason.PROTOCOL_ERROR, "invalid packet length: " + len); } }
@Override public boolean next(Message msg, SSHPacket buffer) throws GeneralSecurityException, TransportException { log.debug("Got message {}", msg); try { switch (msg) { case KEXDH_31: return parseGexGroup(buffer); case KEX_DH_GEX_REPLY: return parseGexReply(buffer); } } catch (Buffer.BufferException be) { throw new TransportException(be); } throw new TransportException("Unexpected message " + msg); }
private void gotDisconnect(SSHPacket buf) throws TransportException { try { final DisconnectReason code = DisconnectReason.fromInt(buf.readUInt32AsInt()); final String message = buf.readString(); log.info("Received SSH_MSG_DISCONNECT (reason={}, msg={})", code, message); throw new TransportException(code, message); } catch (Buffer.BufferException be) { throw new TransportException(be); } }
private void gotDebug(SSHPacket buf) throws TransportException { try { final boolean display = buf.readBoolean(); final String message = buf.readString(); log.debug("Received SSH_MSG_DEBUG (display={}) '{}'", display, message); } catch (Buffer.BufferException be) { throw new TransportException(be); } }
private void receiveServerIdent() throws IOException { final Buffer.PlainBuffer buf = new Buffer.PlainBuffer(); while ((serverID = readIdentification(buf)).isEmpty()) { int b = connInfo.in.read(); if (b == -1) { log.error("Received end of connection, but no identification received. "); throw new TransportException("Server closed connection during identification exchange"); } buf.putByte((byte) b); } }
/** * Reads the identification string from the SSH server. This is the very first string that is sent upon connection * by the server. It takes the form of, e.g. "SSH-2.0-OpenSSH_ver". * <p/> * Several concerns are taken care of here, e.g. verifying protocol version, correct line endings as specified in * RFC and such. * <p/> * This is not efficient but is only done once. * * @param buffer The buffer to read from. * @return empty string if full ident string has not yet been received * @throws IOException */ private String readIdentification(Buffer.PlainBuffer buffer) throws IOException { String ident = new IdentificationStringParser(buffer, loggerFactory).parseIdentificationString(); if (ident.isEmpty()) { return ident; } if (!ident.startsWith("SSH-2.0-") && !ident.startsWith("SSH-1.99-")) throw new TransportException(DisconnectReason.PROTOCOL_VERSION_NOT_SUPPORTED, "Server does not support SSHv2, identified as: " + ident); return ident; }
private String readIdentification(Buffer.PlainBuffer lineBuffer) throws Buffer.BufferException, TransportException { byte[] bytes = new byte[lineBuffer.available()]; lineBuffer.readRawBytes(bytes); if (bytes.length > 255) { log.error("Incorrect identification String received, line was longer than expected: {}", new String(bytes)); log.error("Just for good measure, bytes were: {}", ByteArrayUtils.printHex(bytes, 0, bytes.length)); throw new TransportException("Incorrect identification: line too long: " + ByteArrayUtils.printHex(bytes, 0, bytes.length)); } if (bytes[bytes.length - 2] != '\r') { String ident = new String(bytes, 0, bytes.length - 1); log.warn("Server identification has bad line ending, was expecting a '\\r\\n' however got: '{}' (hex: {})", (char) (bytes[bytes.length - 2] & 0xFF), Integer.toHexString(bytes[bytes.length - 2] & 0xFF)); log.warn("Will treat the identification of this server '{}' leniently", ident); return ident; // log.error("Data received up til here was: {}", new String(bytes)); // throw new TransportException("Incorrect identification: bad line ending: " + ByteArrayUtils.toHex(bytes, 0, bytes.length)); } // Strip off the \r\n return new String(bytes, 0, bytes.length - 2); }
private int decryptLength() throws TransportException { decryptBuffer(0, cipherSize); final int len; // Read packet length try { len = inputBuffer.readUInt32AsInt(); } catch (Buffer.BufferException be) { throw new TransportException(be); } checkPacketLength(len); return len; }
/** * Got an SSH_MSG_UNIMPLEMENTED, so lets see where we're at and act accordingly. * * @param packet The 'unimplemented' packet received * @throws TransportException */ private void gotUnimplemented(SSHPacket packet) throws SSHException { long seqNum = packet.readUInt32(); log.debug("Received SSH_MSG_UNIMPLEMENTED #{}", seqNum); if (kexer.isKexOngoing()) throw new TransportException("Received SSH_MSG_UNIMPLEMENTED while exchanging keys"); getService().notifyUnimplemented(seqNum); }
private void gotServiceAccept() throws TransportException { serviceAccept.lock(); try { if (!serviceAccept.hasWaiters()) throw new TransportException(DisconnectReason.PROTOCOL_ERROR, "Got a service accept notification when none was awaited"); serviceAccept.set(); } finally { serviceAccept.unlock(); } }
private void checkMAC(final byte[] data) throws TransportException { mac.update(seq); // seq num mac.update(data, 0, packetLength + 4); // packetLength+4 = entire packet w/o mac mac.doFinal(macResult, 0); // compute // Check against the received MAC if (!ByteArrayUtils.equals(macResult, 0, data, packetLength + 4, mac.getBlockSize())) { throw new TransportException(DisconnectReason.MAC_ERROR, "MAC Error"); } }
@Override public void init(String remoteHost, int remotePort, InputStream in, OutputStream out) throws TransportException { connInfo = new ConnInfo(remoteHost, remotePort, in, out); try { if (config.isWaitForServerIdentBeforeSendingClientIdent()) { receiveServerIdent(); sendClientIdent(); } else { sendClientIdent(); receiveServerIdent(); } log.info("Server identity string: {}", serverID); } catch (IOException e) { throw new TransportException(e); } reader.start(); }
@Override public long write(SSHPacket payload) throws TransportException { writeLock.lock(); try { if (kexer.isKexOngoing()) { // Only transport layer packets (1 to 49) allowed except SERVICE_REQUEST final Message m = Message.fromByte(payload.array()[payload.rpos()]); if (!m.in(1, 49) || m == Message.SERVICE_REQUEST) { assert m != Message.KEXINIT; kexer.waitForDone(); } } else if (encoder.getSequenceNumber() == 0) // We get here every 2**32th packet kexer.startKex(true); final long seq = encoder.encode(payload); try { connInfo.out.write(payload.array(), payload.rpos(), payload.available()); connInfo.out.flush(); } catch (IOException ioe) { throw new TransportException(ioe); } return seq; } finally { writeLock.unlock(); } }
throw new TransportException("Broken transport; encountered EOF"); } else { needed = decoder.received(recvbuf, read);