| AnyConnect Secure Mobility Client 5.1.6.103

- Main Page
- Related Pages
- Classes
- Files

- Class List
- Class Hierarchy
- Class Members

Public Member Functions | Protected Member Functions

# CLIClientImpl Class Reference

`#include <CLIClientImpl.h>`

List of all members.

## Public Member Functions
void | printHostList ()
void | printDefaultHost ()
void | connect (std::string host, std::string user, std::string password, std::string group)
void | disconnect ()
void | showGroups (std::string host)
void | getStats ()
void | setUserData (ConnectPromptInfo &ConnectPrompt)
void | printGroupList (ConnectPromptInfo &ConnectPrompt)
std::wstring | convertMultiByteToWide (const std::string &sInputData)
void | EventAvailable ()
void | ProcessEvents ()
void | SetRequestType (RequestType e_RequestType)
## Protected Member Functions
void | StatsCB (VPNStats &stats)
void | StateCB (const VPNState state, const VPNSubState subState, const tstring stateString)
void | BannerCB (const tstring &banner)
void | PreConnectReminderCB (const tstring &rtstrPreConnectReminder)
void | NoticeCB (const tstring &notice, const MessageType type, const bool bSensitive=false)
void | ExitNoticeCB (const tstring &notice, const int returnCode)
void | ServiceReadyCB ()
void | UserPromptCB (ConnectPromptInfo &ConnectPrompt)
void | CertBlockedCB (const tstring &rtstrUntrustedServer)
void | CertWarningCB (const tstring &rtstrUntrustedServer, const std::list< tstring > &rltstrCertErrors, bool bAllowImport)

## Detailed Description

This is an example application demonstrating the implementation of the AnyConnect API

## Member Function Documentation

void CLIClientImpl::BannerCB | ( | const tstring & | banner | ) | `[protected, virtual]`

If a banner needs to be acknowledged, this CB delivers the banner to the client.

NOTE: Connection establishment will block until the method setBannerResponse() is called.

In a GUI, a banner would typically be displayed in a modal dialog with an accept or decline button selection.

See also:
  setBannerResponse() to set the user response to the banner.

Implements ClientIfcBase.

    {
            bool bBannerAccepted = true;
            setBannerResponse(bBannerAccepted);
    }

void CLIClientImpl::CertBlockedCB | ( | const tstring & | rtstrUntrustedServer | ) | `[protected, virtual]`

This method is called when the preference to block untrusted servers is enabled and the current VPN server being connected to is untrusted. Clients should present an error to the user notifying them that the current connection to rtstrUntrustedServer is being blocked. The client should also provide a way for the user to change the preference to block untrusted servers.

The user response must be indicated using setCertBlockedResponse

Implements ClientIfcBase.

    {
        setCertBlockedResponse(false);
    }

void CLIClientImpl::CertWarningCB | ( | const tstring & | rtstrUntrustedServer,
|  | const std::list< tstring > & | rltstrCertErrors,
|  | bool | bAllowImport
| ) |  | `[protected, virtual]`

This method is called when connections to untrusted VPN servers is allowed by policies and the current VPN server being connected to is untrusted. Clients should present a warning to the user notifying them that the current connection to rtstrUntrustedServer is unsafe. The reason the VPN server is untrusted is provided in rltstrCertErrors. The client should provide a way for the user to connect once, connect and always trust or cancel the connection. If bAllowImport is set to false then the always trust option should not be presented to users.

The user response must be indicated using setCertWarningResponse

Implements ClientIfcBase.

    {
        setCertWarningResponse(false, false);
    }

void CLIClientImpl::disconnect | ( |  | ) |

Use this method to initiate a disconnect of the active VPN connection.

An indication of VPN disconnect is received via the StateCB method.

Reimplemented from ClientIfc.

    {
        me_RequestType = REQ_DISCONNECT;
        ClientIfc::disconnect();
            // To ensure VPN service receive the disconnect message,
        // do a short sleep before CLI terminates.
        //
        // NOTE: This is done only for demonstration purposes and would not be
        // needed in a GUI or other program that runs continuously. A more elegant way
            // to handle this case is to terminate the CLI after checking the disconnect callback message
            // from API.
        //
    #ifdef _WIN32
        Sleep(1500);
    #else
        sleep(1);
    #endif
    }

void CLIClientImpl::EventAvailable | ( |  | ) | `[virtual]`

This method should be overridden by the client application to exercise some control over the delivery of events from the other protected methods in this class.

This might be necessary in cases where a GUI/CLI is being written and the data from this API needs to be delivered in the GUI/CLI or main thread. In this case, you should override this method and when it is called by the API post an event to your event queue (message pump, etc.). After this event executes in your GUI/CLI or main thread, call the method ClientIfc::ProcessEvents to have events delivered to your client application.

Reimplemented from ClientIfcBase.

    {
        mtx.lock();
        mb_eventAvailable = true;
        mtx.unlock();
    }

void CLIClientImpl::ExitNoticeCB | ( | const tstring & | tstrNotice,
|  | const int | returnCode
| ) |  | `[protected, virtual]`

This CB would likely occur only during a connection when it was detected that the software needed to be upgraded, or when Start Before Logon (SBL) is being used.

Unlike the other callback methods, this method provides a default implementation (calling the system's exit() function). If clients of the API wish to override this behavior, they are responsible for ensuring that the current running process exits with the return code specified by returnCode.

Caution: IF YOU OVERRIDE THIS METHOD AND DO NOT EXIT WITH THE PROPER CODE SOFTWARE UPDATE FUNCTIONALITY IN YOUR CLIENT WILL BREAK

Reimplemented from ClientIfcBase.

    {
    #ifdef UNICODE
        printf("ExitNoticeCB (%d): %S\n", returnCode, notice.c_str());
    #else
        printf("ExitNoticeCB (%d): %s\n", returnCode, notice.c_str());
    #endif
    }

void CLIClientImpl::getStats | ( | void |  | ) |

This method demonstrates accessing the statistics data delivered via the ClientIfc::StatsCB method.

Reimplemented from ClientIfc.

    {
        me_RequestType = REQ_STATISTICS;
        if (isConnected())
        {
            // To ensure we receive the first set of stats before we try to print,
            // do a short sleep.
            //
            // NOTE: This is done only for demonstration purposes and would not be
            // needed in a GUI or other program that runs continuously.
            //
            ClientIfc::getStats();
        }
        else
        {
            printf("Tunnel not up, no stats to print.\n");
            mb_exit = true;
        }
    }

void CLIClientImpl::NoticeCB | ( | const tstring & | notice,
|  | const MessageType | type,
|  | const bool | bSensitive = `false`
| ) |  | `[protected, virtual]`

Messages are delivered via the NoticeCB and can come from multiple sources. There are four message types (error, warning, info and status). See the MessageType enum in api.h for the list.

Clients using the API as an embedded application (not user visible) might want to further characterize messages. One option here is to use the AnyConnect message catalog and assign message codes as the translations for various messages. An application could then track messages based on its own error code scheme.

Implements ClientIfcBase.

    {
        std::string msgType;
        switch(type)
            {
                case MsgType_Error:
                    msgType = "Error";
                    break;
                case MsgType_Warn:
                    msgType = "Warn";
                    break;
                case MsgType_Info:
                    msgType = "Info";
                    break;
                default:
                    msgType = "Unknown";
                    break;
            }

    #ifdef UNICODE
        printf("Notice (%s): %S\n", msgType.c_str(), notice.c_str());
    #else
        printf("Notice (%s): %s\n", msgType.c_str(), notice.c_str());
    #endif
    }

void CLIClientImpl::PreConnectReminderCB | ( | const tstring & | rtstrPreConnectReminder | ) | `[protected, virtual]`

If a pre-connect reminder needs to be acknowledged, this CB delivers the pre-connect reminder to the client.

NOTE: Connection establishment will block until the method setPreConnectReminderResponse() is called.

In a GUI, a pre-connect reminder would typically be displayed in a modal dialog with an OK button selection.

See also:
  setPreConnectReminderResponse() to set the user acknowledgement to the pre-connect reminder message.

Reimplemented from ClientIfcBase.

    {
    #ifdef UNICODE
       printf("\n%S", rtstrPreConnectReminder.c_str());
    #else
       printf("\n%s", rtstrPreConnectReminder.c_str());
    #endif

        printf( "Press enter key to continue... " );
        std::cin.get();
        setPreConnectReminderResponse();
    }

void CLIClientImpl::ProcessEvents | ( |  | ) |

When the method ClientIfc::EventAvailable has been overridden in the client application, this method must be called to receive events.

It is expected that GUI programs will use EventAvailable as a signal, allowing them to set an event using their native event handler. When that event fires, the application can call ProcessEvents, which causes the API to deliver events in the client's main thread.

Reimplemented from ClientIfc.

    {
        while (!mb_exit)
        {
            mtx.lock();
            if (mb_eventAvailable)
            {
                mb_eventAvailable = false;
                ClientIfc::ProcessEvents();
            }
            mtx.unlock();
            std::this_thread::sleep_for(std::chrono::milliseconds(20));
        }
    }

void CLIClientImpl::ServiceReadyCB | ( |  | ) | `[protected, virtual]`

Under normal operating conditions, this CB is called as soon as the attach method completes. In case the service (vpn agent) is not ready, this CB is not called until it is.

Any API calls made prior to this CB being called will result in a NoticeCB error message.

Implements ClientIfcBase.

    { }

void CLIClientImpl::setUserData | ( | ConnectPromptInfo & | ConnectPrompt | ) |

Method with example of parsing ConnectPromptInfo.

This method is triggered by an API call on the method UserPromptCB(ConnectPromptInfo &).

    {
    #ifdef UNICODE
        printf("User Message: %S\n", ConnectPrompt.getMessage().c_str());
    #else
        printf("User Message: %s\n", ConnectPrompt.getMessage().c_str());
    #endif

        // Create a list to hold the names of the individual PromptEntry objects.
        //
        std::list<tstring> promptNames;
        // Get the list of names associated with the PromptEntry objects.
        //
        ConnectPrompt.getListPromptNames(promptNames);
        // This set of code cycles through the list of names that reference the
        // individual PromptEntry objects.  As each name is accessed it can be used
        // to retrieve a specific instance of a PromptEntry object.  There is also a
        // method (ConnectPromptInfo::getListPromptEntry()) to retrieve the list of
        // PromptEntry objects directly, allowing the individual PromtpEntry object
        // to be accessed in a different manner if desired.
        //
        std::list<tstring> :: iterator name_iter;
        for (name_iter = promptNames.begin();
                         name_iter != promptNames.end(); ++name_iter)
        {
            // name_iter represents a single name from the promptNames list.
            //
            tstring promptName = *name_iter;
            PromptEntry *entry = ConnectPrompt.getPromptEntry(promptName);

            // For this demo program, we'll assume any combo box is for
            // group selection.
            //
            if (entry->getPromptType() == Prompt_Combo)
            {
                entry->setValue(ms_group);
            }
            tstring entryName = entry->getPromptName();

            // PromptEntry::Username and PromptEntry::Password are string currently
            // resolving to the wide char values "username" and "password".
            //
            if (entryName == PromptEntry::Username)
            {
                entry->setValue(ms_user);
            }
            else if (entryName == PromptEntry::Password)
            {
                entry->setValue(ms_pswd);
            }
        }
    }

void CLIClientImpl::StateCB | ( | const VPNState | state,
|  | const VPNSubState | subState,
|  | const tstring | stateString
| ) |  | `[protected, virtual]`

Callback used to deliver VPN state and state change string. The stateString delivered by this method is localized.

See the VPNState enum found in api.h for set of valid states.

Implements ClientIfcBase.

    {
    #ifdef UNICODE
       printf("Current State (%d): %S\n", state, stateString.c_str());
    #else
       printf("Current State (%d): %s\n", state, stateString.c_str());
    #endif

        switch(me_RequestType)
        {
            case REQ_STATE:
                mb_exit = true;
                break;
            case REQ_DISCONNECT:
                if (VPNState::DISCONNECTED == state)
                {
                    mb_exit = true;
                }
                break;
            case REQ_CONNECT:
                if (VPNState::CONNECTED == state)
                {
                    mb_exit = true;
                }

                // API may report the current state of VPN (ie., DISCONNECTED) when a connect request is received.
                // States reported after receiving CONNECTING state should be considered for the current connection
                // attempt. Exit the main processing loop for DISCONNECTED or CONNECTED states only after CONNECTING
                // state is received.
                //
                if (VPNState::CONNECTING == state)
                {
                    mb_ConnectingStateReceived = true;
                }

                if (mb_ConnectingStateReceived &&
                    ((VPNState::DISCONNECTED == state) || (VPNState::CONNECTED == state)))
                {
                    mb_exit = true;
                }
                break;
            default:
                break;
        }
    }

void CLIClientImpl::StatsCB | ( | VPNStats & | stats | ) | `[protected, virtual]`

Callback used to deliver new statistics related to the VPN connection.

When a connection is active, a new set of statistics is delivered each second.

See also:
  resetStats(), stopStats() and startStats()

Implements ClientIfcBase.

    {
        if (REQ_STATISTICS == me_RequestType)
        {
            tstring stats = SEP + VPNStats::getTranslatedLabel(VPNStats::State)
                                + rStats.getStatValue(VPNStats::State);
                stats += SEP + VPNStats::getTranslatedLabel(VPNStats::TunnelingMode)
                             + rStats.getStatValue(VPNStats::TunnelingMode);
                stats += SEP + VPNStats::getTranslatedLabel(VPNStats::TimeConnected)
                             + rStats.getStatValue(VPNStats::TimeConnected);
                stats += SEP + VPNStats::getTranslatedLabel(VPNStats::BytesSent)
                             + rStats.getStatValue(VPNStats::BytesSent);
                stats += SEP + VPNStats::getTranslatedLabel(VPNStats::BytesReceived)
                             + rStats.getStatValue(VPNStats::BytesReceived);

                // Now get the data for the active protocol.
                //
                // NOTE: There is also Secure and non-secure route information.  This
                //       data can be retrieved in a manner similar to protocolInfo
                //       using the methods getSecureRoutes() and getNonsecureRoutes()
                //
                std::list<ProtocolInfo *> protInfo = rStats.getProtocolInfo();
                for (std::list<ProtocolInfo *>::iterator iter = protInfo.begin();
                                                        iter != protInfo.end();
                                                        iter++)
                {
                    if ((*iter)->isActive())
                    {
                        stats += SEP + VPNStats::getTranslatedLabel(ProtocolInfo::Cipher)
                                    +(*iter)->getProtocolValue(ProtocolInfo::Cipher);
                        stats += SEP + VPNStats::getTranslatedLabel(ProtocolInfo::Protocol)
                                    +(*iter)->getProtocolValue(ProtocolInfo::Protocol);
                        stats += SEP + VPNStats::getTranslatedLabel(ProtocolInfo::Compression)
                                    +(*iter)->getProtocolValue(ProtocolInfo::Compression);
                    }
                }

    #ifdef UNICODE
                printf("VPN Stats:%S\n",stats.c_str());
    #else
                printf("VPN Stats:%s\n",stats.c_str());
    #endif
            mb_exit = true;
        }
    }

void CLIClientImpl::UserPromptCB | ( | ConnectPromptInfo & | ConnectPrompt | ) | `[protected, virtual]`

This method supports prompting for single or multiple values. All prompts are considered mandatory.

The ConnectPromptInfo object contains a list of PromptEntry instances. The labels and their default values (if any) can be found in these instances. After the data has been collected from the user it can be set into these same instances. When ready, the client application should call the method UserSubmit() to have the responses read by the API.

Implements ClientIfcBase.

    {
        if (me_RequestType == REQ_CONNECT)
        {
            // For example purposes, only allow one try at setting user data.
            //
            // Look for requested user input fields and fill in previously
            // stored values.
            //
            setUserData(ConnectPrompt);
            // Now that the user data has been entered, submit the response.
            //
            UserSubmit();
        }
        else if (me_RequestType == REQ_GROUPLIST)
        {
            printGroupList(ConnectPrompt);
            mb_exit = true;
        }
    }