Search in sources :

Example 1 with EContentTransferEncoding

use of com.helger.mail.cte.EContentTransferEncoding 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();
    }
}
Also used : EContentTransferEncoding(com.helger.mail.cte.EContentTransferEncoding) InputStream(java.io.InputStream) MIC(com.helger.as2lib.crypto.MIC) StopWatch(com.helger.commons.timing.StopWatch) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) AS2NoModuleException(com.helger.as2lib.processor.AS2NoModuleException) AS2HttpHeaderSetter(com.helger.as2lib.util.http.AS2HttpHeaderSetter) EHttpMethod(com.helger.commons.http.EHttpMethod) AS2ComponentNotFoundException(com.helger.as2lib.session.AS2ComponentNotFoundException) IMessageMDN(com.helger.as2lib.message.IMessageMDN) AS2HttpClient(com.helger.as2lib.util.http.AS2HttpClient)

Example 2 with EContentTransferEncoding

use of com.helger.mail.cte.EContentTransferEncoding in project as2-lib by phax.

the class BCCryptoHelperTest method testEncryptWithAllCTEs.

@Test
public void testEncryptWithAllCTEs() throws Exception {
    final MimeBodyPart aPart = new MimeBodyPart();
    aPart.setText("Hello world");
    for (final EContentTransferEncoding eCTE : EContentTransferEncoding.values()) {
        final MimeBodyPart aEncrypted = AS2Helper.getCryptoHelper().encrypt(aPart, CERT_ENCRYPT, ECryptoAlgorithmCrypt.CRYPT_AES256_GCM, eCTE);
        assertNotNull(aEncrypted);
        assertArrayEquals(new String[] { "application/pkcs7-mime; name=\"smime.p7m\"; smime-type=enveloped-data" }, aEncrypted.getHeader(CHttpHeader.CONTENT_TYPE));
        assertArrayEquals(new String[] { "attachment; filename=\"smime.p7m\"" }, aEncrypted.getHeader(CHttpHeader.CONTENT_DISPOSITION));
    }
}
Also used : EContentTransferEncoding(com.helger.mail.cte.EContentTransferEncoding) MimeBodyPart(javax.mail.internet.MimeBodyPart) Test(org.junit.Test)

Example 3 with EContentTransferEncoding

use of com.helger.mail.cte.EContentTransferEncoding in project phase4 by phax.

the class MimeMessageCreator method generateMimeMessage.

@Nonnull
public static AS4MimeMessage generateMimeMessage(@Nonnull final ESoapVersion eSoapVersion, @Nonnull final Document aSoapEnvelope, @Nullable final ICommonsList<WSS4JAttachment> aEncryptedAttachments) throws MessagingException {
    ValueEnforcer.notNull(eSoapVersion, "SoapVersion");
    ValueEnforcer.notNull(aSoapEnvelope, "SoapEnvelope");
    final Charset aCharset = AS4XMLHelper.XWS.getCharset();
    final SoapMimeMultipart aMimeMultipart = new SoapMimeMultipart(eSoapVersion, aCharset);
    final EContentTransferEncoding eCTE = EContentTransferEncoding.BINARY;
    final String sContentType = eSoapVersion.getMimeType(aCharset).getAsString();
    {
        // Message Itself (repeatable)
        final MimeBodyPart aMessagePart = new MimeBodyPart();
        aMessagePart.setDataHandler(new DataHandler(new DOMSource(aSoapEnvelope), sContentType));
        aMessagePart.setHeader(CHttpHeader.CONTENT_TRANSFER_ENCODING, eCTE.getID());
        aMimeMultipart.addBodyPart(aMessagePart);
    }
    boolean bIsRepeatable = true;
    if (aEncryptedAttachments != null)
        for (final WSS4JAttachment aEncryptedAttachment : aEncryptedAttachments) {
            aEncryptedAttachment.addToMimeMultipart(aMimeMultipart);
            if (!aEncryptedAttachment.isRepeatable())
                bIsRepeatable = false;
        }
    // Build main message
    final AS4MimeMessage aMsg = new AS4MimeMessage((Session) null, bIsRepeatable);
    aMsg.setContent(aMimeMultipart);
    aMsg.saveChanges();
    return aMsg;
}
Also used : EContentTransferEncoding(com.helger.mail.cte.EContentTransferEncoding) DOMSource(javax.xml.transform.dom.DOMSource) Charset(java.nio.charset.Charset) DataHandler(javax.activation.DataHandler) MimeBodyPart(javax.mail.internet.MimeBodyPart) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment) Nonnull(javax.annotation.Nonnull)

Example 4 with EContentTransferEncoding

use of com.helger.mail.cte.EContentTransferEncoding in project as2-lib by phax.

the class AS2SenderModule method handle.

public void handle(@Nonnull final String sAction, @Nonnull final IMessage aBaseMsg, @Nullable final Map<String, Object> aOptions) throws AS2Exception {
    final AS2Message aMsg = (AS2Message) aBaseMsg;
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Submitting message" + aMsg.getLoggingText());
    // verify all required information is present for sending
    checkRequired(aMsg);
    final int nRetries = getRetryCount(aMsg.partnership(), aOptions);
    try (final AS2ResourceHelper aResHelper = new AS2ResourceHelper()) {
        // Get Content-Transfer-Encoding to use
        final String sContentTransferEncoding = aMsg.partnership().getContentTransferEncodingSend(EContentTransferEncoding.AS2_DEFAULT.getID());
        final EContentTransferEncoding eCTE = EContentTransferEncoding.getFromIDCaseInsensitiveOrDefault(sContentTransferEncoding, EContentTransferEncoding.AS2_DEFAULT);
        // compress and/or sign and/or encrypt the message if needed
        final MimeBodyPart aSecuredData = secure(aMsg, eCTE);
        // Calculate MIC after compress/sign/crypt was handled, because the
        // message data might change if compression before signing is active.
        final MIC aMIC;
        if (aMsg.isRequestingMDN())
            aMIC = calculateAndStoreMIC(aMsg);
        else
            aMIC = null;
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Setting message content type to '" + aSecuredData.getContentType() + "'");
        aMsg.setContentType(aSecuredData.getContentType());
        try (final IHTTPOutgoingDumper aOutgoingDumper = getHttpOutgoingDumper(aMsg)) {
            final IHTTPIncomingDumper aIncomingDumper = getEffectiveHttpIncomingDumper();
            // Use no CTE, because it was set on all MIME parts
            _sendViaHTTP(aMsg, aSecuredData, aMIC, true ? null : eCTE, aOutgoingDumper, aIncomingDumper, aResHelper);
        }
    } catch (final AS2HttpResponseException ex) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error("Http Response Error " + ex.getMessage());
        ex.terminate(aMsg);
        if (!doResend(IProcessorSenderModule.DO_SEND, aMsg, ex, nRetries))
            throw ex;
    } catch (final IOException ex) {
        // Re-send if a network error occurs during transmission
        final AS2Exception wioe = WrappedAS2Exception.wrap(ex).setSourceMsg(aMsg).terminate();
        if (!doResend(IProcessorSenderModule.DO_SEND, aMsg, wioe, nRetries))
            throw wioe;
    } catch (final Exception ex) {
        // Propagate error if it can't be handled by a re-send
        throw WrappedAS2Exception.wrap(ex);
    }
}
Also used : EContentTransferEncoding(com.helger.mail.cte.EContentTransferEncoding) MIC(com.helger.as2lib.crypto.MIC) IHTTPOutgoingDumper(com.helger.as2lib.util.dump.IHTTPOutgoingDumper) IOException(java.io.IOException) MessagingException(javax.mail.MessagingException) AS2NoModuleException(com.helger.as2lib.processor.AS2NoModuleException) AS2DispositionException(com.helger.as2lib.disposition.AS2DispositionException) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) IOException(java.io.IOException) AS2InvalidParameterException(com.helger.as2lib.params.AS2InvalidParameterException) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) AS2ComponentNotFoundException(com.helger.as2lib.session.AS2ComponentNotFoundException) IHTTPIncomingDumper(com.helger.as2lib.util.dump.IHTTPIncomingDumper) AS2ResourceHelper(com.helger.as2lib.util.AS2ResourceHelper) AS2Message(com.helger.as2lib.message.AS2Message) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 5 with EContentTransferEncoding

use of com.helger.mail.cte.EContentTransferEncoding in project as2-lib by phax.

the class MainSendToMendelsonTestServerPlayground method main.

public static void main(final String[] args) throws Exception {
    // Enable or disable debug mode
    if (false)
        GlobalDebug.setDebugModeDirect(false);
    Proxy aHttpProxy = null;
    if (false)
        aHttpProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("172.30.9.6", 8080));
    IHTTPOutgoingDumperFactory aOutgoingDumperFactory = null;
    if (false)
        aOutgoingDumperFactory = x -> new HTTPOutgoingDumperStreamBased(System.out);
    if (false)
        HTTPHelper.setHTTPIncomingDumperFactory(() -> new HTTPIncomingDumperStreamBased(new NonClosingOutputStream(System.out)));
    // Start client configuration
    final AS2ClientSettings aSettings = new AS2ClientSettings();
    aSettings.setKeyStore(EKeyStoreType.PKCS12, new File("src/test/resources/mendelson/key3.pfx"), "test");
    // Fixed sender
    aSettings.setSenderData("mycompanyAS2", "phax.as2-lib@github.com", "key3");
    // Fixed receiver - key alias must be "mendelsontestAS2"
    aSettings.setReceiverData("mendelsontestAS2", "mendelsontestAS2", "http://testas2.mendelson-e-c.com:8080/as2/HttpReceiver");
    final X509Certificate aReceiverCertificate = AS2KeyStoreHelper.readX509Certificate("src/test/resources/mendelson/key4.cer");
    aSettings.setReceiverCertificate(aReceiverCertificate);
    // AS2 stuff
    aSettings.setPartnershipName(aSettings.getSenderAS2ID() + "_" + aSettings.getReceiverAS2ID());
    // When a signed message is used, the algorithm for MIC and message must be
    // identical
    final ECryptoAlgorithmSign eSignAlgo = ECryptoAlgorithmSign.DIGEST_SHA1;
    // Encryption is required for Mendelson
    // CRYPT_AES256_GCM is not supported
    // CRYPT_AES256_CBC is supported
    // CRYPT_AES192_GCM is not supported
    // CRYPT_AES192_CBC is supported
    // CRYPT_AES128_GCM is not supported
    // CRYPT_AES128_CBC is supported
    // CRYPT_3DES is supported
    final ECryptoAlgorithmCrypt eCryptAlgo = ECryptoAlgorithmCrypt.CRYPT_3DES;
    final ECompressionType eCompress = ECompressionType.ZLIB;
    final boolean bCompressBeforeSigning = true;
    if (eSignAlgo != null)
        aSettings.setMDNOptions(new DispositionOptions().setMICAlg(eSignAlgo).setMICAlgImportance(DispositionOptions.IMPORTANCE_REQUIRED).setProtocol(DispositionOptions.PROTOCOL_PKCS7_SIGNATURE).setProtocolImportance(DispositionOptions.IMPORTANCE_REQUIRED));
    if (false)
        aSettings.setMDNOptions("");
    aSettings.setEncryptAndSign(eCryptAlgo, eSignAlgo);
    aSettings.setCompress(eCompress, bCompressBeforeSigning);
    aSettings.setMessageIDFormat("github-phax-as2-lib-$date.uuuuMMdd-HHmmssZ$-$rand.1234$@$msg.sender.as2_id$_$msg.receiver.as2_id$");
    aSettings.setRetryCount(1);
    aSettings.setConnectTimeoutMS(10_000);
    aSettings.setReadTimeoutMS(10_000);
    aSettings.setHttpOutgoingDumperFactory(aOutgoingDumperFactory);
    // Build client request
    final AS2ClientRequest aRequest = new AS2ClientRequest("AS2 test message from as2-lib");
    if (false)
        aRequest.setData(new File("src/test/resources/mendelson/testcontent.attachment"), StandardCharsets.ISO_8859_1);
    else
        aRequest.setData(new DataHandler(new FileDataSource(new File("src/test/resources/mendelson/testcontent.attachment"))));
    aRequest.setContentType(CMimeType.TEXT_PLAIN.getAsString());
    // "CTE" and "compress before sign" have impact on MIC matching
    // EContentTransferEncoding._7BIT MIC is matched
    // EContentTransferEncoding._8BIT MIC is matched
    // EContentTransferEncoding.BINARY MIC is matched
    // EContentTransferEncoding.QUOTED_PRINTABLE - not supported by Mendelson
    // EContentTransferEncoding.BASE64 MIC is matched
    aRequest.setContentTransferEncoding(EContentTransferEncoding.BASE64);
    // Send message
    final AS2ClientResponse aResponse = new AS2Client().setHttpProxy(aHttpProxy).sendSynchronous(aSettings, aRequest);
    if (aResponse.hasException())
        LOGGER.info(aResponse.getAsString());
    LOGGER.info("Done");
}
Also used : X509Certificate(java.security.cert.X509Certificate) HTTPIncomingDumperStreamBased(com.helger.as2lib.util.dump.HTTPIncomingDumperStreamBased) ECryptoAlgorithmSign(com.helger.as2lib.crypto.ECryptoAlgorithmSign) DispositionOptions(com.helger.as2lib.disposition.DispositionOptions) AS2Client(com.helger.as2lib.client.AS2Client) ECryptoAlgorithmCrypt(com.helger.as2lib.crypto.ECryptoAlgorithmCrypt) HTTPOutgoingDumperStreamBased(com.helger.as2lib.util.dump.HTTPOutgoingDumperStreamBased) LoggerFactory(org.slf4j.LoggerFactory) HTTPHelper(com.helger.as2lib.util.http.HTTPHelper) AS2ClientRequest(com.helger.as2lib.client.AS2ClientRequest) NonClosingOutputStream(com.helger.commons.io.stream.NonClosingOutputStream) DataHandler(javax.activation.DataHandler) CMimeType(com.helger.commons.mime.CMimeType) Proxy(java.net.Proxy) FileDataSource(javax.activation.FileDataSource) GlobalDebug(com.helger.commons.debug.GlobalDebug) Logger(org.slf4j.Logger) EContentTransferEncoding(com.helger.mail.cte.EContentTransferEncoding) AS2ClientResponse(com.helger.as2lib.client.AS2ClientResponse) AS2KeyStoreHelper(com.helger.as2lib.util.cert.AS2KeyStoreHelper) ECompressionType(com.helger.as2lib.crypto.ECompressionType) SystemProperties(com.helger.commons.system.SystemProperties) InetSocketAddress(java.net.InetSocketAddress) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) IHTTPOutgoingDumperFactory(com.helger.as2lib.util.dump.IHTTPOutgoingDumperFactory) AS2ClientSettings(com.helger.as2lib.client.AS2ClientSettings) EKeyStoreType(com.helger.security.keystore.EKeyStoreType) InetSocketAddress(java.net.InetSocketAddress) DispositionOptions(com.helger.as2lib.disposition.DispositionOptions) HTTPIncomingDumperStreamBased(com.helger.as2lib.util.dump.HTTPIncomingDumperStreamBased) DataHandler(javax.activation.DataHandler) X509Certificate(java.security.cert.X509Certificate) ECryptoAlgorithmCrypt(com.helger.as2lib.crypto.ECryptoAlgorithmCrypt) AS2ClientSettings(com.helger.as2lib.client.AS2ClientSettings) Proxy(java.net.Proxy) ECompressionType(com.helger.as2lib.crypto.ECompressionType) HTTPOutgoingDumperStreamBased(com.helger.as2lib.util.dump.HTTPOutgoingDumperStreamBased) IHTTPOutgoingDumperFactory(com.helger.as2lib.util.dump.IHTTPOutgoingDumperFactory) FileDataSource(javax.activation.FileDataSource) AS2Client(com.helger.as2lib.client.AS2Client) NonClosingOutputStream(com.helger.commons.io.stream.NonClosingOutputStream) File(java.io.File) AS2ClientRequest(com.helger.as2lib.client.AS2ClientRequest) ECryptoAlgorithmSign(com.helger.as2lib.crypto.ECryptoAlgorithmSign) AS2ClientResponse(com.helger.as2lib.client.AS2ClientResponse)

Aggregations

EContentTransferEncoding (com.helger.mail.cte.EContentTransferEncoding)6 MimeBodyPart (javax.mail.internet.MimeBodyPart)4 MIC (com.helger.as2lib.crypto.MIC)2 AS2NoModuleException (com.helger.as2lib.processor.AS2NoModuleException)2 AS2ComponentNotFoundException (com.helger.as2lib.session.AS2ComponentNotFoundException)2 DataHandler (javax.activation.DataHandler)2 AS2Client (com.helger.as2lib.client.AS2Client)1 AS2ClientRequest (com.helger.as2lib.client.AS2ClientRequest)1 AS2ClientResponse (com.helger.as2lib.client.AS2ClientResponse)1 AS2ClientSettings (com.helger.as2lib.client.AS2ClientSettings)1 ECompressionType (com.helger.as2lib.crypto.ECompressionType)1 ECryptoAlgorithmCrypt (com.helger.as2lib.crypto.ECryptoAlgorithmCrypt)1 ECryptoAlgorithmSign (com.helger.as2lib.crypto.ECryptoAlgorithmSign)1 AS2DispositionException (com.helger.as2lib.disposition.AS2DispositionException)1 DispositionOptions (com.helger.as2lib.disposition.DispositionOptions)1 AS2Exception (com.helger.as2lib.exception.AS2Exception)1 WrappedAS2Exception (com.helger.as2lib.exception.WrappedAS2Exception)1 AS2Message (com.helger.as2lib.message.AS2Message)1 IMessageMDN (com.helger.as2lib.message.IMessageMDN)1 AS2InvalidParameterException (com.helger.as2lib.params.AS2InvalidParameterException)1