use of com.helger.as2lib.session.AS2ComponentNotFoundException in project as2-lib by phax.
the class AS2MDNReceiverHandler method checkAsyncMDN.
/**
* verify if the mic is matched.
*
* @param aMsg
* Message
* @return <code>true</code> if the MDN was processed, <code>false</code> e.g.
* on MIC mismatch
* @throws AS2Exception
* In case of error; e.g. MIC mismatch
*/
public boolean checkAsyncMDN(@Nonnull final AS2Message aMsg) throws AS2Exception {
try {
// get the returned mic from mdn object
final String sReturnMIC = aMsg.getMDN().attrs().getAsString(AS2MessageMDN.MDNA_MIC);
final MIC aReturnMIC = MIC.parse(sReturnMIC);
// use original message id. to open the pending information file
// from pendinginfo folder.
final String sOrigMessageID = aMsg.getMDN().attrs().getAsString(AS2MessageMDN.MDNA_ORIG_MESSAGEID);
final String sPendingInfoFolder = AS2IOHelper.getSafeFileAndFolderName(getModule().getSession().getMessageProcessor().getPendingMDNInfoFolder());
if (StringHelper.hasNoText(sPendingInfoFolder)) {
LOGGER.error("The pending MDN info folder is not properly configured. Cannot check for async MDNs.");
return false;
}
final File aPendingInfoFile = new File(sPendingInfoFolder + FilenameHelper.UNIX_SEPARATOR_STR + AS2IOHelper.getFilenameFromMessageID(sOrigMessageID));
if (LOGGER.isInfoEnabled())
LOGGER.info("Trying to read original MIC and message id information from file '" + aPendingInfoFile.getAbsolutePath() + "'" + aMsg.getLoggingText());
final String sOriginalMIC;
final MIC aOriginalMIC;
final File aPendingFile;
try (final NonBlockingBufferedReader aPendingInfoReader = FileHelper.getBufferedReader(aPendingInfoFile, StandardCharsets.ISO_8859_1)) {
if (aPendingInfoReader == null) {
LOGGER.error("The pending info file '" + aPendingInfoFile.getAbsolutePath() + "' with the original MIC could not be opened for reading");
return false;
}
// Get the original mic from the first line of pending information
// file
sOriginalMIC = aPendingInfoReader.readLine();
aOriginalMIC = MIC.parse(sOriginalMIC);
// Get the original pending file from the second line of pending
// information file
aPendingFile = new File(aPendingInfoReader.readLine());
}
final String sDisposition = aMsg.getMDN().attrs().getAsString(AS2MessageMDN.MDNA_DISPOSITION);
if (LOGGER.isInfoEnabled())
LOGGER.info("received MDN [" + sDisposition + "]" + aMsg.getLoggingText());
final boolean bMICMatch = aOriginalMIC != null && aReturnMIC != null && aReturnMIC.equals(aOriginalMIC);
if (!bMICMatch) {
if (LOGGER.isInfoEnabled())
LOGGER.info("MIC was not matched, so the pending file '" + aPendingFile.getAbsolutePath() + "' will NOT be deleted.");
// MIC was not matched
m_aMICMatchingHandler.onMICMismatch(aMsg, sOriginalMIC, sReturnMIC);
return false;
}
// MIC was matched
m_aMICMatchingHandler.onMICMatch(aMsg, sReturnMIC);
if (LOGGER.isInfoEnabled())
LOGGER.info("Delete pendinginfo file '" + aPendingInfoFile.getName() + "' from pending folder '" + sPendingInfoFolder + "'" + aMsg.getLoggingText());
if (!aPendingInfoFile.delete()) {
if (LOGGER.isErrorEnabled())
LOGGER.error("Error delete pendinginfo file '" + aPendingFile.getAbsolutePath() + "'");
}
if (LOGGER.isInfoEnabled())
LOGGER.info("Delete pending file '" + aPendingFile.getName() + "' from pending folder '" + aPendingFile.getParent() + "'" + aMsg.getLoggingText());
if (!aPendingFile.delete()) {
if (LOGGER.isErrorEnabled())
LOGGER.error("Error delete pending file '" + aPendingFile.getAbsolutePath() + "'");
}
} catch (final IOException | AS2ComponentNotFoundException ex) {
LOGGER.error("Error checking async MDN", ex);
return false;
}
return true;
}
use of com.helger.as2lib.session.AS2ComponentNotFoundException in project as2-lib by phax.
the class AS2MDNReceiverHandler method receiveMDN.
// Asynch MDN 2007-03-12
/**
* method for receiving and processing Async MDN sent from receiver.
*
* @param aMsg
* The MDN message
* @param aData
* The MDN content
* @param aResponseHandler
* The HTTP response handler for setting the correct HTTP response code
* @param aResHelper
* Resource helper
* @throws AS2Exception
* In case of error
* @throws IOException
* In case of IO error
*/
protected final void receiveMDN(@Nonnull final AS2Message aMsg, final byte[] aData, @Nonnull final IAS2HttpResponseHandler aResponseHandler, @Nonnull final AS2ResourceHelper aResHelper) throws AS2Exception, IOException {
try {
// Create a MessageMDN and copy HTTP headers
final IMessageMDN aMDN = new AS2MessageMDN(aMsg);
// copy headers from msg to MDN from msg
aMDN.headers().setAllHeaders(aMsg.headers());
final MimeBodyPart aPart = new MimeBodyPart(AS2HttpHelper.getAsInternetHeaders(aMDN.headers()), aData);
aMDN.setData(aPart);
// get the MDN partnership info
aMDN.partnership().setSenderAS2ID(aMDN.getHeader(CHttpHeader.AS2_FROM));
aMDN.partnership().setReceiverAS2ID(aMDN.getHeader(CHttpHeader.AS2_TO));
// Set the appropriate keystore aliases
aMDN.partnership().setSenderX509Alias(aMsg.partnership().getReceiverX509Alias());
aMDN.partnership().setReceiverX509Alias(aMsg.partnership().getSenderX509Alias());
// Update the partnership
getModule().getSession().getPartnershipFactory().updatePartnership(aMDN, false);
final ICertificateFactory aCertFactory = getModule().getSession().getCertificateFactory();
final X509Certificate aSenderCert = aCertFactory.getCertificate(aMDN, ECertificatePartnershipType.SENDER);
final boolean bUseCertificateInBodyPart;
final ETriState eUseCertificateInBodyPart = aMsg.partnership().getVerifyUseCertificateInBodyPart();
if (eUseCertificateInBodyPart.isDefined()) {
// Use per partnership
bUseCertificateInBodyPart = eUseCertificateInBodyPart.getAsBooleanValue();
} else {
// Use global value
bUseCertificateInBodyPart = getModule().getSession().isCryptoVerifyUseCertificateInBodyPart();
}
AS2Helper.parseMDN(aMsg, aSenderCert, bUseCertificateInBodyPart, getVerificationCertificateConsumer(), aResHelper);
// in order to name & save the mdn with the original AS2-From + AS2-To +
// Message id.,
// the 3 msg attributes have to be reset before calling MDNFileModule
aMsg.partnership().setSenderAS2ID(aMDN.getHeader(CHttpHeader.AS2_TO));
aMsg.partnership().setReceiverAS2ID(aMDN.getHeader(CHttpHeader.AS2_FROM));
getModule().getSession().getPartnershipFactory().updatePartnership(aMsg, false);
aMsg.setMessageID(aMDN.attrs().getAsString(AS2MessageMDN.MDNA_ORIG_MESSAGEID));
try {
getModule().getSession().getMessageProcessor().handle(IProcessorStorageModule.DO_STOREMDN, aMsg, null);
} catch (final AS2ComponentNotFoundException | AS2NoModuleException ex) {
// No message processor found
// Or no module found in message processor
}
// check if the mic (message integrity check) is correct
final boolean bMICMatch = checkAsyncMDN(aMsg);
HTTPHelper.sendSimpleHTTPResponse(aResponseHandler, bMICMatch ? CHttp.HTTP_OK : CHttp.HTTP_NOT_FOUND);
final String sDisposition = aMDN.attrs().getAsString(AS2MessageMDN.MDNA_DISPOSITION);
if (m_aIncomingMDNCallback != null)
m_aIncomingMDNCallback.onIncomingMDN(false, aMDN, aMDN.getHeader(CHttpHeader.AS2_FROM), aMDN.getHeader(CHttpHeader.AS2_TO), sDisposition, aMDN.attrs().getAsString(AS2MessageMDN.MDNA_MIC), aMDN.attrs().getAsString(AS2MessageMDN.MDNA_ORIG_MESSAGEID), aMDN.attrs().getAsBoolean(AS2Message.ATTRIBUTE_RECEIVED_SIGNED, false), bMICMatch);
DispositionType.createFromString(sDisposition).validate(aMsg, aMDN.getText());
} catch (final IOException ex) {
HTTPHelper.sendSimpleHTTPResponse(aResponseHandler, CHttp.HTTP_BAD_REQUEST);
throw ex;
} catch (final Exception ex) {
HTTPHelper.sendSimpleHTTPResponse(aResponseHandler, CHttp.HTTP_BAD_REQUEST);
throw WrappedAS2Exception.wrap(ex).setSourceMsg(aMsg);
}
}
use of com.helger.as2lib.session.AS2ComponentNotFoundException in project as2-lib by phax.
the class AsynchMDNSenderModule method _sendViaHTTP.
private void _sendViaHTTP(@Nonnull final AS2Message aMsg, @Nonnull final DispositionType aDisposition, @Nullable final IHTTPOutgoingDumper aOutgoingDumper, @Nonnull final AS2ResourceHelper aResHelper) throws AS2Exception, IOException, MessagingException {
final IMessageMDN aMdn = aMsg.getMDN();
// Create a HTTP connection
final String sUrl = aMsg.getAsyncMDNurl();
final EHttpMethod eRequestMethod = EHttpMethod.POST;
// MDN is a small message. We will always use CHttp
final AS2HttpClient aConn = getHttpClient(sUrl, eRequestMethod, getSession().getHttpProxy());
try {
if (aOutgoingDumper != null)
aOutgoingDumper.start(sUrl, aMsg);
if (LOGGER.isInfoEnabled())
LOGGER.info("Connecting to " + sUrl + aMsg.getLoggingText());
// Set all custom headers first (so that they are overridden with the
// mandatory ones in here)
// Use HttpHeaderMap and not String to ensure name casing is identical!
final HttpHeaderMap aHeaderMap = aMdn.headers().getClone();
aHeaderMap.setHeader(CHttpHeader.CONNECTION, CAS2Header.DEFAULT_CONNECTION);
aHeaderMap.setHeader(CHttpHeader.USER_AGENT, CAS2Header.DEFAULT_USER_AGENT);
final boolean bQuoteHeaderValues = isQuoteHeaderValues();
final AS2HttpHeaderSetter aHeaderSetter = new AS2HttpHeaderSetter(aConn, aOutgoingDumper, bQuoteHeaderValues);
// Copy all the header from mdn to the RequestProperties of conn
// Unification needed, because original MDN headers may contain newlines
aHeaderMap.forEachSingleHeader(aHeaderSetter::setHttpHeader, true, false);
if (aOutgoingDumper != null)
aOutgoingDumper.finishedHeaders();
aMsg.attrs().putIn(CNetAttribute.MA_DESTINATION_IP, aConn.getURL().getHost());
aMsg.attrs().putIn(CNetAttribute.MA_DESTINATION_PORT, aConn.getURL().getPort());
final InputStream aMsgIS = aMdn.getData().getInputStream();
// Transfer the data
final StopWatch aSW = StopWatch.createdStarted();
final long nBytes = aConn.send(aMsgIS, (EContentTransferEncoding) null, aOutgoingDumper, aResHelper);
aSW.stop();
if (LOGGER.isInfoEnabled())
LOGGER.info("AS2 MDN transferred " + AS2IOHelper.getTransferRate(nBytes, aSW) + aMsg.getLoggingText());
if (aOutgoingDumper != null)
aOutgoingDumper.finishedPayload();
final int nHttpResponseCode = aConn.getResponseCode();
if (getOutgoingHttpCallback() != null)
getOutgoingHttpCallback().onOutgoingHttpMessage(false, aMsg.getAS2From(), aMsg.getAS2To(), aMsg.getMessageID(), (MIC) null, (EContentTransferEncoding) null, sUrl, nHttpResponseCode);
// Check the HTTP Response code
if (AS2HttpClient.isErrorResponseCode(nHttpResponseCode)) {
if (LOGGER.isErrorEnabled())
LOGGER.error("sent AsyncMDN [" + aDisposition.getAsString() + "] Fail(" + nHttpResponseCode + ") " + aMsg.getLoggingText());
throw new AS2HttpResponseException(sUrl, nHttpResponseCode, aConn.getResponseMessage());
}
if (LOGGER.isInfoEnabled())
LOGGER.info("sent AsyncMDN [" + aDisposition.getAsString() + "] OK(" + nHttpResponseCode + ") " + aMsg.getLoggingText());
// log & store mdn into backup folder.
try {
getSession().getMessageProcessor().handle(IProcessorStorageModule.DO_STOREMDN, aMsg, null);
} catch (final AS2ComponentNotFoundException | AS2NoModuleException ex) {
// No message processor found
// Or no module found in message processor
}
} finally {
aConn.disconnect();
}
}
use of com.helger.as2lib.session.AS2ComponentNotFoundException in project as2-lib by phax.
the class AS2ReceiverHandler method sendMDN.
protected void sendMDN(@Nonnull final String sClientInfo, @Nonnull final IAS2HttpResponseHandler aResponseHandler, @Nonnull final AS2Message aMsg, @Nonnull final DispositionType aDisposition, @Nonnull final String sText, @Nonnull final ESuccess eSuccess) {
final boolean bAllowErrorMDN = !aMsg.partnership().isBlockErrorMDN();
if (eSuccess.isSuccess() || bAllowErrorMDN) {
try {
final IAS2Session aSession = m_aReceiverModule.getSession();
final IMessageMDN aMdn = AS2Helper.createMDN(aSession, aMsg, aDisposition, sText);
if (aMsg.isRequestingAsynchMDN()) {
// if asyncMDN requested, close existing synchronous connection and
// initiate separate MDN send
final HttpHeaderMap aHeaders = new HttpHeaderMap();
aHeaders.setContentLength(0);
try (final NonBlockingByteArrayOutputStream aData = new NonBlockingByteArrayOutputStream()) {
// Empty data
// Ideally this would be HTTP 204 (no content)
aResponseHandler.sendHttpResponse(CHttp.HTTP_OK, aHeaders, aData);
}
if (LOGGER.isInfoEnabled())
LOGGER.info("Setup to send async MDN [" + aDisposition.getAsString() + "] " + sClientInfo + aMsg.getLoggingText());
// trigger explicit async sending
aSession.getMessageProcessor().handle(IProcessorSenderModule.DO_SEND_ASYNC_MDN, aMsg, null);
} else {
// otherwise, send sync MDN back on same connection
if (LOGGER.isInfoEnabled())
LOGGER.info("Sending back sync MDN [" + aDisposition.getAsString() + "] " + sClientInfo + aMsg.getLoggingText());
// Get data and therefore content length for sync MDN
try (final NonBlockingByteArrayOutputStream aData = new NonBlockingByteArrayOutputStream()) {
final MimeBodyPart aPart = aMdn.getData();
StreamHelper.copyInputStreamToOutputStream(aPart.getInputStream(), aData);
aMdn.headers().setContentLength(aData.size());
// start HTTP response
aResponseHandler.sendHttpResponse(CHttp.HTTP_OK, aMdn.headers(), aData);
}
// Save sent MDN for later examination
try {
aSession.getMessageProcessor().handle(IProcessorStorageModule.DO_STOREMDN, aMsg, null);
} catch (final AS2ComponentNotFoundException | AS2NoModuleException ex) {
// No message processor found
// or No module found in message processor
}
if (LOGGER.isInfoEnabled())
LOGGER.info("sent MDN [" + aDisposition.getAsString() + "] " + sClientInfo + aMsg.getLoggingText());
}
} catch (final Exception ex) {
WrappedAS2Exception.wrap(ex).terminate(aMsg);
}
}
}
use of com.helger.as2lib.session.AS2ComponentNotFoundException in project as2-lib by phax.
the class AS2SenderModule method receiveSyncMDN.
/**
* @param aMsg
* AS2Message
* @param aHttpClient
* URLConnection
* @param aOriginalMIC
* mic value from original msg
* @param aIncomingDumper
* Incoming dumper. May be <code>null</code>.
* @param aResHelper
* Resource helper
* @throws AS2Exception
* in case of an error
* @throws IOException
* in case of an IO error
*/
protected void receiveSyncMDN(@Nonnull final AS2Message aMsg, @Nonnull final AS2HttpClient aHttpClient, @Nonnull final MIC aOriginalMIC, @Nullable final IHTTPIncomingDumper aIncomingDumper, @Nonnull final AS2ResourceHelper aResHelper) throws AS2Exception, IOException {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Receiving synchronous MDN for message" + aMsg.getLoggingText());
try {
// Create a MessageMDN and copy HTTP headers
final IMessageMDN aMDN = new AS2MessageMDN(aMsg);
// Bug in ph-commons 9.1.3 in addAllHeaders!
aMDN.headers().addAllHeaders(aHttpClient.getResponseHeaderFields());
// Receive the MDN data
final InputStream aConnIS = aHttpClient.getInputStream();
final NonBlockingByteArrayOutputStream aMDNStream = new NonBlockingByteArrayOutputStream();
// Retrieve the whole MDN content
StreamHelper.copyByteStream().from(aConnIS).closeFrom(true).to(aMDNStream).closeTo(true).limit(StringParser.parseLong(aMDN.getHeader(CHttpHeader.CONTENT_LENGTH), -1)).build();
// Dump collected message
if (aIncomingDumper != null)
aIncomingDumper.dumpIncomingRequest(aMDN.headers().getAllHeaderLines(true), aMDNStream.getBufferOrCopy(), aMDN);
if (LOGGER.isTraceEnabled()) {
// Debug print the whole MDN stream
LOGGER.trace("Retrieved MDN stream data:\n" + aMDNStream.getAsString(StandardCharsets.ISO_8859_1));
}
final MimeBodyPart aPart = new MimeBodyPart(AS2HttpHelper.getAsInternetHeaders(aMDN.headers()), aMDNStream.getBufferOrCopy());
aMDN.setData(aPart);
// get the MDN partnership info
aMDN.partnership().setSenderAS2ID(aMDN.getHeader(CHttpHeader.AS2_FROM));
aMDN.partnership().setReceiverAS2ID(aMDN.getHeader(CHttpHeader.AS2_TO));
// Set the appropriate key store aliases
aMDN.partnership().setSenderX509Alias(aMsg.partnership().getReceiverX509Alias());
aMDN.partnership().setReceiverX509Alias(aMsg.partnership().getSenderX509Alias());
// Update the partnership
getSession().getPartnershipFactory().updatePartnership(aMDN, false);
final ICertificateFactory aCertFactory = getSession().getCertificateFactory();
final X509Certificate aSenderCert = aCertFactory.getCertificate(aMDN, ECertificatePartnershipType.SENDER);
boolean bUseCertificateInBodyPart;
final ETriState eUseCertificateInBodyPart = aMsg.partnership().getVerifyUseCertificateInBodyPart();
if (eUseCertificateInBodyPart.isDefined()) {
// Use per partnership
bUseCertificateInBodyPart = eUseCertificateInBodyPart.getAsBooleanValue();
} else {
// Use global value
bUseCertificateInBodyPart = getSession().isCryptoVerifyUseCertificateInBodyPart();
}
AS2Helper.parseMDN(aMsg, aSenderCert, bUseCertificateInBodyPart, m_aVerificationCertificateConsumer, aResHelper);
try {
getSession().getMessageProcessor().handle(IProcessorStorageModule.DO_STOREMDN, aMsg, null);
} catch (final AS2ComponentNotFoundException | AS2NoModuleException ex) {
// No message processor found
// Or no module found in message processor
}
final String sDisposition = aMDN.attrs().getAsString(AS2MessageMDN.MDNA_DISPOSITION);
if (LOGGER.isInfoEnabled())
LOGGER.info("Received synchronous AS2 MDN [" + sDisposition + "]" + aMsg.getLoggingText());
// Asynch MDN 2007-03-12
// Verify if the original mic is equal to the mic in returned MDN
final String sReturnMIC = aMDN.attrs().getAsString(AS2MessageMDN.MDNA_MIC);
final MIC aReturnMIC = MIC.parse(sReturnMIC);
// Catch ReturnMIC == null in case the attribute is simply missing
final boolean bMICMatch = aOriginalMIC != null && aReturnMIC != null && aReturnMIC.equals(aOriginalMIC);
if (bMICMatch) {
// MIC was matched - all good
m_aMICMatchingHandler.onMICMatch(aMsg, sReturnMIC);
} else {
// file was sent completely but the returned mic was not matched,
m_aMICMatchingHandler.onMICMismatch(aMsg, aOriginalMIC == null ? null : aOriginalMIC.getAsAS2String(), sReturnMIC);
}
if (m_aIncomingMDNCallback != null)
m_aIncomingMDNCallback.onIncomingMDN(true, aMDN, aMDN.getHeader(CHttpHeader.AS2_FROM), aMDN.getHeader(CHttpHeader.AS2_TO), sDisposition, aMDN.attrs().getAsString(AS2MessageMDN.MDNA_MIC), aMDN.attrs().getAsString(AS2MessageMDN.MDNA_ORIG_MESSAGEID), aMDN.attrs().getAsBoolean(AS2Message.ATTRIBUTE_RECEIVED_SIGNED, false), bMICMatch);
DispositionType.createFromString(sDisposition).validate(aMsg, aMDN.getText());
} catch (final IOException ex) {
throw ex;
} catch (final Exception ex) {
throw WrappedAS2Exception.wrap(ex).setSourceMsg(aMsg);
}
}
Aggregations