Search in sources :

Example 11 with Wait

use of iso.std.iso_iec._24727.tech.schema.Wait in project open-ecard by ecsec.

the class RichClient method setup.

public void setup() {
    GUIDefaults.initialize();
    String title = LANG.translationForKey("client.startup.failed.headline", AppVersion.getName());
    String message = null;
    // Set up GUI
    SwingUserConsent gui = new SwingUserConsent(new SwingDialogWrapper());
    try {
        tray = new AppTray(this);
        tray.beginSetup();
        // Set up client environment
        env = new ClientEnv();
        // Set up the Dispatcher
        MessageDispatcher dispatcher = new MessageDispatcher(env);
        env.setDispatcher(dispatcher);
        // Set up EventDispatcherImpl
        eventDispatcher = new EventDispatcherImpl();
        env.setEventDispatcher(eventDispatcher);
        // Set up Management
        TinyManagement management = new TinyManagement(env);
        env.setManagement(management);
        // Set up MiddlewareConfig
        MiddlewareConfigLoader mwConfigLoader = new MiddlewareConfigLoader();
        List<MiddlewareSALConfig> mwSALConfigs = mwConfigLoader.getMiddlewareSALConfigs();
        // Set up CardRecognitionImpl
        recognition = new CardRecognitionImpl(env);
        recognition.setGUI(gui);
        env.setRecognition(recognition);
        // Set up StateCallbacks
        cardStates = new CardStateMap();
        SALStateCallback salCallback = new SALStateCallback(env, cardStates);
        eventDispatcher.add(salCallback);
        // Set up the IFD
        ifd = new IFD();
        ifd.addProtocol(ECardConstants.Protocol.PACE, new PACEProtocolFactory());
        ifd.setGUI(gui);
        ifd.setEnvironment(env);
        env.setIFD(ifd);
        // Set up SAL
        TinySAL mainSal = new TinySAL(env, cardStates);
        mainSal.setGUI(gui);
        sal = new SelectorSAL(mainSal, env);
        env.setSAL(sal);
        env.setCIFProvider(sal);
        // Set up Middleware SAL
        MwStateCallback mwCallback = new MwStateCallback(env, cardStates, mwConfigLoader);
        for (MiddlewareSALConfig mwSALConfig : mwSALConfigs) {
            if (!mwSALConfig.isDisabled()) {
                MiddlewareSAL mwSal = new MiddlewareSAL(env, cardStates, mwSALConfig, mwCallback);
                mwSal.setGui(gui);
                sal.addSpecializedSAL(mwSal);
            }
        }
        // Start up control interface
        SettingsAndDefaultViewWrapper guiWrapper = new SettingsAndDefaultViewWrapper();
        try {
            manager = new AddonManager(env, gui, cardStates, guiWrapper);
            guiWrapper.setAddonManager(manager);
            mainSal.setAddonManager(manager);
            // initialize http binding
            int port = 24727;
            boolean dispatcherMode = false;
            WinReg.HKEY hk = WinReg.HKEY_LOCAL_MACHINE;
            String regPath = "SOFTWARE\\" + OpenecardProperties.getProperty("registry.app_name");
            if (Platform.isWindows()) {
                LOG.debug("Checking if dispatcher mode should be used.");
                try {
                    if (regKeyExists(hk, regPath, "Dispatcher_Mode")) {
                        String value = Advapi32Util.registryGetStringValue(hk, regPath, "Dispatcher_Mode");
                        dispatcherMode = Boolean.valueOf(value);
                        // let socket chose its port
                        port = 0;
                    }
                } catch (Win32Exception ex) {
                    LOG.warn("Failed to read 'Dispatcher_Mode' registry key. Using normal operation mode.", ex);
                }
            }
            if (!dispatcherMode) {
                try {
                    port = Integer.parseInt(OpenecardProperties.getProperty("http-binding.port"));
                } catch (NumberFormatException ex) {
                    LOG.warn("Error in config file, HTTP binding port is malformed.");
                }
            }
            // start HTTP server
            httpBinding = new HttpBinding(port);
            httpBinding.setAddonManager(manager);
            httpBinding.start();
            if (dispatcherMode) {
                long waitTime = getRegInt(hk, regPath, "Retry_Wait_Time", 5000L);
                long timeout = getRegInt(hk, regPath, "DP_Timeout", 3600000L);
                // try to register with dispatcher service
                LOG.debug("Trying to register HTTP binding port with dispatcher service.");
                final int realPort = httpBinding.getPort();
                final URL regUrl = new URL("http://127.0.0.1:24727/dp/register");
                FutureTask ft = new FutureTask(new DispatcherRegistrator(regUrl, realPort, waitTime, timeout), 1);
                Thread registerThread = new Thread(ft, "Register-Dispatcher-Service");
                registerThread.setDaemon(true);
                registerThread.start();
                // wait until thread is finished
                ft.get();
            }
        } catch (BindException e) {
            message = LANG.translationForKey("client.startup.failed.portinuse", AppVersion.getName());
            throw e;
        }
        tray.endSetup(env, manager);
        // Initialize the EventManager
        eventDispatcher.add(tray.status(), EventType.TERMINAL_ADDED, EventType.TERMINAL_REMOVED, EventType.CARD_INSERTED, EventType.CARD_RECOGNIZED, EventType.CARD_REMOVED);
        // start event dispatcher
        eventDispatcher.start();
        // initialize SAL
        WSHelper.checkResult(sal.initialize(new Initialize()));
        // Perform an EstablishContext to get a ContextHandle
        try {
            EstablishContext establishContext = new EstablishContext();
            EstablishContextResponse establishContextResponse = ifd.establishContext(establishContext);
            WSHelper.checkResult(establishContextResponse);
            contextHandle = establishContextResponse.getContextHandle();
        } catch (WSHelper.WSException ex) {
            message = LANG.translationForKey("client.startup.failed.nocontext");
            throw ex;
        }
        // perform GC to bring down originally allocated memory
        new Timer().schedule(new GCTask(), 5000);
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);
        if (message == null || message.isEmpty()) {
            // Add exception message if no custom message is set
            message = ex.getMessage();
        }
        // Show dialog to the user and shut down the client
        String msg = String.format("%s%n%n%s", title, message);
        gui.obtainMessageDialog().showMessageDialog(msg, AppVersion.getName(), DialogType.ERROR_MESSAGE);
        teardown();
    } catch (Throwable ex) {
        LOG.error("Unexpected error occurred. Exiting client.", ex);
        System.exit(1);
    }
}
Also used : SALStateCallback(org.openecard.common.sal.state.SALStateCallback) EventDispatcherImpl(org.openecard.common.event.EventDispatcherImpl) IFD(org.openecard.ifd.scio.IFD) WinReg(com.sun.jna.platform.win32.WinReg) CardRecognitionImpl(org.openecard.recognition.CardRecognitionImpl) Initialize(iso.std.iso_iec._24727.tech.schema.Initialize) MiddlewareSAL(org.openecard.mdlw.sal.MiddlewareSAL) URL(java.net.URL) SwingDialogWrapper(org.openecard.gui.swing.SwingDialogWrapper) MessageDispatcher(org.openecard.transport.dispatcher.MessageDispatcher) FutureTask(java.util.concurrent.FutureTask) HttpBinding(org.openecard.control.binding.http.HttpBinding) CardStateMap(org.openecard.common.sal.state.CardStateMap) MwStateCallback(org.openecard.mdlw.event.MwStateCallback) EstablishContext(iso.std.iso_iec._24727.tech.schema.EstablishContext) TinySAL(org.openecard.sal.TinySAL) WSHelper(org.openecard.common.WSHelper) MiddlewareConfigLoader(org.openecard.mdlw.sal.config.MiddlewareConfigLoader) BindException(java.net.BindException) EstablishContextResponse(iso.std.iso_iec._24727.tech.schema.EstablishContextResponse) PACEProtocolFactory(org.openecard.ifd.protocol.pace.PACEProtocolFactory) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Win32Exception(com.sun.jna.platform.win32.Win32Exception) BindException(java.net.BindException) HttpException(org.openecard.apache.http.HttpException) IOException(java.io.IOException) JoranException(ch.qos.logback.core.joran.spi.JoranException) Win32Exception(com.sun.jna.platform.win32.Win32Exception) AppTray(org.openecard.richclient.gui.AppTray) ClientEnv(org.openecard.common.ClientEnv) MiddlewareSALConfig(org.openecard.mdlw.sal.config.MiddlewareSALConfig) Timer(java.util.Timer) SwingUserConsent(org.openecard.gui.swing.SwingUserConsent) TinyManagement(org.openecard.management.TinyManagement) AddonManager(org.openecard.addon.AddonManager) SelectorSAL(org.openecard.sal.SelectorSAL) SettingsAndDefaultViewWrapper(org.openecard.richclient.gui.SettingsAndDefaultViewWrapper)

Example 12 with Wait

use of iso.std.iso_iec._24727.tech.schema.Wait in project open-ecard by ecsec.

the class EventWatcher method compare.

/**
 * Compares the current status against the expected status and returns the difference if any.
 * This function does not request new information from the hardware, but only uses the last state retrieved. The
 * result of this function can be used as events in
 * {@link org.openecard.ws.IFD#wait(iso.std.iso_iec._24727.tech.schema.Wait)}.
 *
 * @param expectedStatus Status known to the caller of the function.
 * @return The difference between the internal state of this object and the given reference status.
 */
@Nonnull
public List<IFDStatusType> compare(@Nonnull List<IFDStatusType> expectedStatus) {
    ArrayList<IFDStatusType> remaining = new ArrayList<>(currentState);
    for (IFDStatusType nextExpect : expectedStatus) {
        Iterator<IFDStatusType> it = remaining.iterator();
        boolean matchFound = false;
        // see if the current state contains the terminal that is expected to be present
        while (it.hasNext()) {
            IFDStatusType nextRemain = it.next();
            // found matching terminal
            if (nextRemain.getIFDName().equals(nextExpect.getIFDName())) {
                matchFound = true;
                // see if there is any difference between the two
                if (isStateEqual(nextRemain, nextExpect)) {
                    // no difference, so delete this entry
                    it.remove();
                }
                break;
            }
        }
        // if remaining does not contain the expected status, the terminal was removed
        if (!matchFound) {
            IFDStatusType removed = clone(nextExpect);
            removed.setIFDName(nextExpect.getIFDName());
            removed.setConnected(false);
            remaining.add(removed);
        }
    }
    // clone entries, to prevent altering the state of this object from the outside
    return clone(remaining);
}
Also used : ArrayList(java.util.ArrayList) IFDStatusType(iso.std.iso_iec._24727.tech.schema.IFDStatusType) Nonnull(javax.annotation.Nonnull)

Example 13 with Wait

use of iso.std.iso_iec._24727.tech.schema.Wait in project open-ecard by ecsec.

the class IFD method cancel.

@Override
public CancelResponse cancel(Cancel parameters) {
    CancelResponse response;
    // you thought of a different IFD obviously
    if (!ByteUtils.compare(ctxHandle, parameters.getContextHandle())) {
        String msg = "Invalid context handle specified.";
        Result r = WSHelper.makeResultError(ECardConstants.Minor.IFD.INVALID_CONTEXT_HANDLE, msg);
        response = WSHelper.makeResponse(CancelResponse.class, r);
        return response;
    }
    String ifdName = parameters.getIFDName();
    String session = parameters.getSessionIdentifier();
    if (session != null) {
        // async wait
        Future<List<IFDStatusType>> f = this.asyncWaitThreads.get(session);
        if (f != null) {
            f.cancel(true);
            response = WSHelper.makeResponse(CancelResponse.class, WSHelper.makeResultOK());
        } else {
            String msg = "No matching Wait call exists for the given session.";
            Result r = WSHelper.makeResultError(ECardConstants.Minor.IFD.IO.CANCEL_NOT_POSSIBLE, msg);
            response = WSHelper.makeResponse(CancelResponse.class, r);
        }
    } else if (ifdName != null) {
        // sync wait
        synchronized (this) {
            if (syncWaitThread != null) {
                syncWaitThread.cancel(true);
                // not really needed but seems cleaner
                syncWaitThread = null;
                response = WSHelper.makeResponse(CancelResponse.class, WSHelper.makeResultOK());
            } else {
                String msg = "No synchronous Wait to cancel.";
                Result r = WSHelper.makeResultError(ECardConstants.Minor.IFD.IO.CANCEL_NOT_POSSIBLE, msg);
                response = WSHelper.makeResponse(CancelResponse.class, r);
            }
        }
    } else {
        // nothing to cancel
        String msg = "Invalid parameters given.";
        response = WSHelper.makeResponse(CancelResponse.class, WSHelper.makeResultUnknownError(msg));
    }
    return response;
}
Also used : CancelResponse(iso.std.iso_iec._24727.tech.schema.CancelResponse) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) Result(oasis.names.tc.dss._1_0.core.schema.Result)

Example 14 with Wait

use of iso.std.iso_iec._24727.tech.schema.Wait in project open-ecard by ecsec.

the class ChangePINAction method execute.

@Override
public void execute() {
    // check if a german identity card is inserted, if not wait for it
    ConnectionHandleType cHandle = waitForCardType(GERMAN_IDENTITY_CARD);
    if (cHandle == null) {
        LOG.debug("User cancelled card insertion.");
        return;
    }
    cHandle = connectToRootApplication(cHandle);
    RecognizedState pinState = recognizeState(cHandle);
    boolean nativePace;
    try {
        nativePace = genericPACESupport(cHandle);
    } catch (WSException e) {
        LOG.error("Could not get capabilities from reader.");
        return;
    }
    ChangePINDialog uc = new ChangePINDialog(gui, dispatcher, cHandle, pinState, !nativePace);
    uc.show();
    Disconnect d = new Disconnect();
    d.setSlotHandle(cHandle.getSlotHandle());
    dispatcher.safeDeliver(d);
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) ChangePINDialog(org.openecard.plugins.pinplugin.gui.ChangePINDialog) Disconnect(iso.std.iso_iec._24727.tech.schema.Disconnect) WSException(org.openecard.common.WSHelper.WSException)

Example 15 with Wait

use of iso.std.iso_iec._24727.tech.schema.Wait in project open-ecard by ecsec.

the class UnblockPINAction method execute.

@Override
public void execute() {
    // check if a german identity card is inserted, if not wait for it
    ConnectionHandleType cHandle = waitForCardType(GERMAN_IDENTITY_CARD);
    if (cHandle == null) {
        logger.debug("User cancelled card insertion.");
        return;
    }
    cHandle = connectToRootApplication(cHandle);
    RecognizedState pinState = recognizeState(cHandle);
    boolean nativePace;
    try {
        nativePace = genericPACESupport(cHandle);
    } catch (WSException e) {
        logger.error("Could not get capabilities from reader.");
        return;
    }
    UnblockPINDialog uc = new UnblockPINDialog(gui, dispatcher, cHandle, pinState, !nativePace);
    uc.show();
    Disconnect d = new Disconnect();
    d.setSlotHandle(cHandle.getSlotHandle());
    dispatcher.safeDeliver(d);
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) UnblockPINDialog(org.openecard.plugins.pinplugin.gui.UnblockPINDialog) Disconnect(iso.std.iso_iec._24727.tech.schema.Disconnect) WSException(org.openecard.common.WSHelper.WSException)

Aggregations

ConnectionHandleType (iso.std.iso_iec._24727.tech.schema.ConnectionHandleType)6 Result (oasis.names.tc.dss._1_0.core.schema.Result)5 Disconnect (iso.std.iso_iec._24727.tech.schema.Disconnect)4 ArrayList (java.util.ArrayList)4 ChannelHandleType (iso.std.iso_iec._24727.tech.schema.ChannelHandleType)3 EstablishContextResponse (iso.std.iso_iec._24727.tech.schema.EstablishContextResponse)3 IFDStatusType (iso.std.iso_iec._24727.tech.schema.IFDStatusType)3 Wait (iso.std.iso_iec._24727.tech.schema.Wait)3 BeginTransaction (iso.std.iso_iec._24727.tech.schema.BeginTransaction)2 BeginTransactionResponse (iso.std.iso_iec._24727.tech.schema.BeginTransactionResponse)2 DIDAuthenticate (iso.std.iso_iec._24727.tech.schema.DIDAuthenticate)2 DIDAuthenticateResponse (iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse)2 DIDAuthenticationDataType (iso.std.iso_iec._24727.tech.schema.DIDAuthenticationDataType)2 PathSecurityType (iso.std.iso_iec._24727.tech.schema.PathSecurityType)2 Transmit (iso.std.iso_iec._24727.tech.schema.Transmit)2 TransmitResponse (iso.std.iso_iec._24727.tech.schema.TransmitResponse)2 WaitResponse (iso.std.iso_iec._24727.tech.schema.WaitResponse)2 BigInteger (java.math.BigInteger)2 WSException (org.openecard.common.WSHelper.WSException)2 Document (org.w3c.dom.Document)2