#include "stdafx2.h" #include "MobileDialFSM.h" #include "MbnEventImpl.h" #include "WirelessAgentSafeClient.h" #define WIN32_LEAN_AND_MEAN #include #include #include #include #include #include #include #include using namespace std; using namespace MobileDial; #include "EventCode.h" #include "GetDevInfoHelper.h" #include "string_util.h" #include "MobileDlg.h" #define SUPPORT_DIAL_FROM_WEB 1 #pragma comment (lib, "Ws2_32.lib") const int DATA_BUFSIZE = 8192; const DWORD MOBILEDIAL_TIMER_ID = 1; const int CHECK_CONNECT_TIMER_ID = 2; const int CHECK_CONNECT_BACKUP_TIMER_ID = 5; const int CHECK_CONNECT_DIAL_TIMER_ID = 6; const int RAS_CONNECTION_NOTIFICATION_TIMER_ID = 7; const int CHECK_RASDEVICE_CHANGED_TIMER_ID = 8; const int CHECK_PRE_RASDEVICE_CHANGED_TIMER_ID = 9; const int CHECK_CONNECT_MBN_TIMER_ID = 10; const int FAILURE_WAIT_TIMER_ID = 3; const int CHECK_NETCARD_TIMER_ID = 4; const int TIMER_TRY_LINK_ID = 11; const int TIMER_CHECK_DEVICE_ID = 12; const int TIMER_CHECK_DEVICE_NOCHANGED_ID = 13; const int MAX_TRY_CONNECT_TIMES = 3; const int MAX_TRY_WLAN_CONNETC_TIMES = 6; const DWORD BATTERY_TIMER_INTERVAL = 3000; const DWORD DEV_CHANGED_TIMER_INTERVAL = 3500; const DWORD RASCONNECTION_TIMER_INTERVAL = 500; const int DEFAULT_FAIL_CONNECT_MAX = 3; const int DEFAULT_FAIL_CONNECT_LESS = 1; const DWORD MOBILEDIAL_HBEAT_INTERVAL = 10000; const DWORD MOBILEDIAL_LIB_INTERVAL = 9000; const DWORD MOBILEDIAL_FLB_INTERVAL = 5000; const DWORD MOBILEDIAL_QUICK_TIMER_INTERVAL = 800; const DWORD MOBILEDIAL_FASTER_INTERVAL = 1000; const DWORD MOBILEDIAL_QUICK_TIMER_PLUS_INTERVAL = 3000; const DWORD MOBILEDIAL_FASTER_PLUS_INTERVAL = 5000; const DWORD MOBILEDIAL_CHECKDONGLE_INTERVAL = 5000; const DWORD MOBILEDIAL_WAITDIALRT_INTERVAL = 10000; const DWORD MOBILEDIAL_FASTERDIALRT_INTERVAL = 6000; const DWORD MOBILEDIAL_WLAN_CONNECT_INTERVAL = 10000; const int PING_INTERVAL = (60 * 1000 / MOBILEDIAL_FASTER_INTERVAL) - 1;//1 min const int ATTEMPT_INTERVAL = (1 * 60 * 1000 / MOBILEDIAL_CHECKDONGLE_INTERVAL) - 1;//1 min HRASCONN g_hrasconn = NULL; DWORD g_dwRasError; BOOL g_bFirstConnect = TRUE; const int DEFAULT_TIMEOUT_SEC = 3; const char* interfaceList[] = { "PC UI Interface", "ZTE NMEA Device", "ZTE Modem Device", "Vodafone Mobile Broadband Secondary Port Modem (Huawei)" }; const int sizeInterfaceList = 4; // [Josephus in 14:50:28 2016/9/3] const char* modelList[] = { RASDT_Modem }; const int sizeModelList = 1; //0: Connected //1: Disconnected //2: Error //3: Connect event //4: Cancel event. const int RasEventCount = 5; HANDLE g_RasEvents[RasEventCount] = { NULL }; const int PROFILE_MAX_COUNT = 10; #define SYSVAR_NET_STATUS "NetState" //系统变量名称 const char* sysVarNetStatusEnum[] = {"N", "O", "D", "I", "C", "E"}; #define NET_STATUS_UNINIT 0 //初始状态 #define NET_STATUS_NO_DEVICE 1 //没有设备 #define NET_STATUS_DIAL_OFF 2 //设备没有拨号 #define NET_STATUS_DISCONNECT 3 //上网卡已经连接但是网络不通 #define NET_STATUS_CONNECTED 4 //网络已连接 #define NET_STATUS_ERROR 5 //异常 void WINAPI CustomRasDialFunc(UINT unMsg, RASCONNSTATE rasconnstate, DWORD dwError) { static DWORD dwWatiTime = 1500; if (dwError){ Sleep(dwWatiTime); g_dwRasError = dwError; Dbg ("RasDial -- Error receive..."); if(g_RasEvents[2] != NULL) SetEvent(g_RasEvents[2]); return; } bool fDoneState = !!(rasconnstate & RASCS_DONE); bool fPausedState = !!(rasconnstate & RASCS_PAUSED); bool fRunState = !(fDoneState || fPausedState); // Map each of the states of RasDial() and display on the screen // the next state that RasDial() is entering switch (rasconnstate) { // Running States case RASCS_OpenPort: Dbg ("RasDial -- Opening port..."); break; case RASCS_PortOpened: Dbg ("RasDial -- Port opened."); break; case RASCS_ConnectDevice: Dbg ("RasDial -- Connecting device..."); break; case RASCS_DeviceConnected: Dbg ("RasDial -- Device connected."); break; case RASCS_AllDevicesConnected: Dbg ("RasDial -- All devices connected."); break; case RASCS_Authenticate: Dbg ("RasDial -- Authenticating..."); break; case RASCS_AuthNotify: Dbg ("RasDial -- Authentication notify."); break; case RASCS_AuthRetry: Dbg ("RasDial -- Retrying authentication..."); break; case RASCS_AuthCallback: Dbg ("RasDial -- Authentication callback..."); break; case RASCS_AuthChangePassword: Dbg ("RasDial -- Change password..."); break; case RASCS_AuthProject: Dbg ("RasDial -- Projection phase started..."); break; case RASCS_AuthLinkSpeed: Dbg ("RasDial -- Negotiating speed..."); break; case RASCS_AuthAck: Dbg ("RasDial -- Authentication acknowledge..."); break; case RASCS_ReAuthenticate: Dbg ("RasDial -- Retrying Authentication..."); break; case RASCS_Authenticated: Dbg ("RasDial -- Authentication complete."); break; case RASCS_PrepareForCallback: Dbg ("RasDial -- Preparing for callback..."); break; case RASCS_WaitForModemReset: Dbg ("RasDial -- Waiting for modem reset..."); break; case RASCS_WaitForCallback: Dbg ("RasDial -- Waiting for callback..."); break; case RASCS_Projected: Dbg ("RasDial -- Projection completed."); break; #if (WINVER >= 0x400) case RASCS_StartAuthentication: Dbg ("RasDial -- Starting authentication..."); break; case RASCS_CallbackComplete: Dbg ("RasDial -- Callback complete."); break; case RASCS_LogonNetwork: Dbg ("RasDial -- Logon to the network."); break; #endif case RASCS_SubEntryConnected: Dbg ("RasDial -- Subentry connected."); break; case RASCS_SubEntryDisconnected: Dbg ("RasDial -- Subentry disconnected."); #if (WINVER >= 0x601) case RASCS_ApplySettings: Dbg ("RasDial -- Apply settings."); break; #endif // The RAS Paused States will not occur because // we did not use the RASDIALEXTENSIONS structure // to set the RDEOPT_PausedState option flag. // RASCS_RetryAuthentication: RasDial正在等待新的用户凭据 // RASCS_CallbackSetByCaller: RasDial正在等待客户机的回拨号码 // RASCS_PasswordExpired: RasDial希望用户提供一个新密码 // Terminal States case RASCS_Connected: Sleep(dwWatiTime); Dbg ("RasDial -- Connection completed."); if(g_RasEvents[0] != NULL) SetEvent(g_RasEvents[0]); break; case RASCS_Disconnected: Sleep(dwWatiTime); Dbg ("RasDial -- Disconnecting..."); if(g_RasEvents[1] != NULL) SetEvent(g_RasEvents[1]); break; default: Dbg ("RasDial -- Unknown Status = %d", rasconnstate); break; } } UINT WINAPI RasEventThreadFunc(PVOID param) { CMobileDialFSM* pFsm = (CMobileDialFSM*)param; if(pFsm == NULL) return -1; char szRasString[256]; BOOL fError = FALSE; do { DWORD dwRes = WaitForMultipleObjects(5, g_RasEvents, FALSE, INFINITE); switch(dwRes) { case WAIT_OBJECT_0 + 2: { memset((void*)szRasString, 0, sizeof(char)*256); RasGetErrorString((UINT)g_dwRasError, szRasString, 256); Dbg ("RasDial -- Error: %d - %s.", g_dwRasError, szRasString); pFsm->m_csErrMsg = CSimpleStringA::Format("%s : %d", szRasString, g_dwRasError); pFsm->TellDlgTheResult(Error_Unexpect, WM_DIAL_RESULT, ADVANCE_RAS); //pFsm->SetRasStatus(MBD_RASDIAL_FAILED); // bug which makes recent dial info cannot be cleared. [1/24/2019 17:33 @Gifur] //pFsm->RasHangUpSuffix(); FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CONNECT_COMPLETE); fsmEvent->param1 = -1; fsmEvent->param2 = ADVANCE_RAS; pFsm->PostEventLIFO(fsmEvent); } break; case WAIT_OBJECT_0: { Dbg ("RasDial Connected Event."); pFsm->TellDlgTheResult(Error_Succeed, WM_DIAL_RESULT, ADVANCE_RAS); //pFsm->SetRasStatus(MBD_ACTIVATION_CONNECTED); FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CONNECT_COMPLETE); fsmEvent->param1 = 1; fsmEvent->param2 = ADVANCE_RAS; pFsm->PostEventLIFO(fsmEvent); } break; case WAIT_OBJECT_0 + 1: { Dbg ("RasDial DisConnected Event."); pFsm->TellDlgTheResult(Error_Succeed, WM_DIAL_DISCONNECT, 1); pFsm->SetRasStatus(MBD_ACTIVATION_DISCONNECTED); FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DISCONNECT_COMPLETE); fsmEvent->param1 = 1; fsmEvent->param2 = ADVANCE_RAS; pFsm->PostEventLIFO(fsmEvent); } break; case WAIT_OBJECT_0 + 3: { //FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DEVICE_ARRIVAL); //fsmEvent->param1 = 1; //fsmEvent->param2 = 3; //pFsm->PostEventLIFO(fsmEvent); } break; case WAIT_OBJECT_0 + 4: { //FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DEVICE_LEAVE); //fsmEvent->param1 = 1; //fsmEvent->param2 = 3; //pFsm->PostEventLIFO(fsmEvent); } break; default: fError = TRUE; break; } } while (!fError); Dbg("Exit the RasEventThreadFunc thread"); return 0; } CSimpleStringA GuidToString(GUID guid, bool bCover) { char c[GUID_LEN] = {0}; if(bCover) { sprintf_s(c, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); } else { sprintf_s(c, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); } CSimpleStringA s(c); return s; } CSimpleStringA CreateGuidString(bool bCover) { GUID guid; CoCreateGuid(&guid); return GuidToString(guid, bCover); } template class TimerOutHelper : public ITimerListener { public: typedef void (T::*FuncTimer)(); TimerOutHelper(T *p, FuncTimer pTimerFunc, bool bDeleteSelf = false) : m_pObject(p), m_pTimer(pTimerFunc), m_bDeleteSelf(bDeleteSelf) {} virtual void OnTimeout(DWORD dwTimerID) { (m_pObject->*m_pTimer)(); if (m_bDeleteSelf) delete this; } private: T *m_pObject; FuncTimer m_pTimer; bool m_bDeleteSelf; }; CMobileDialFSM::CMobileDialFSM() :m_testResult(Error_Succeed),m_csMachineType(true),m_csSite(true),m_csPhoneNum(true),m_csEntryName(true) ,m_csUserName(true),m_csPassword(true),m_csVpnName(true) ,m_sock(INVALID_SOCKET),m_bConnected(false),m_dwCkFailCount(0) ,m_dwFailMax(DEFAULT_FAIL_CONNECT_MAX),m_batteryRemains(100),m_batteryRemainsF(100),m_bACPower(0), m_bACPowerF(0) ,m_n1G(0),m_n3G(0),m_n4G(0),m_bRCfgHaveDial(false), m_bPadAndFLB(false), m_bPadAndLIB(false) ,m_TimerInterval(MOBILEDIAL_FLB_INTERVAL),m_nRecoverMax(0) ,m_signalVal(0), m_dwLsErrCode(0), m_curState(MBD_NOT_INITIALIZED),m_3gState(MBD_NOT_INITIALIZED),m_HwState(MBD_NOT_INITIALIZED) ,m_34GReserved(0),m_34GDialSuc(0),m_bNotify(true),m_bBackupAvail(false) ,ping1(NULL), ping2(NULL),m_hMainWnd(NULL),m_bManageByUser(false),m_nAdvancedGen(0) ,m_hRasListenThread(NULL),m_csCurEntryGUID(true),m_SafeWirelessClient(NULL),m_WifiChangedEvt(NULL) ,m_strReservedPasword(true),m_HwDeviceMnt(NULL),m_strTerminalNo(true),m_ecSelfTest(Error_Succeed) ,m_fMBBDeviceMonitoring(FALSE),m_fMBBDeviceMonitorStop(FALSE),m_dwEntityID(0x212),m_mifiBattery(0) ,m_bManufactureSignal(FALSE),m_curMIFIDevName(true) { m_pMbn = new CMbnImplHelper(this); m_rasEntries.Clear(); memset(&m_recentInfo, 0, sizeof(RecentDialInfo)); InitializeCriticalSection(&m_cs4WirlessClient); m_HwDeviceMnt = new hw::hw_device_mnt(); mMBBParam.connectType = 0; }; CMobileDialFSM::~CMobileDialFSM() { LOG_FUNCTION(); if(m_pMbn) { if(m_bPadAndFLB && !isUsingNewVerAllInOne() ) { m_pMbn->UnAdviseCustomEvents(); } delete m_pMbn; m_pMbn = NULL; } if(m_bPadAndFLB && !isUsingNewVerAllInOne() ) { if(m_hRasListenThread != NULL) { TerminateThread(m_hRasListenThread, -1); CloseHandle(m_hRasListenThread); m_hRasListenThread = NULL; } for(int i=0; im_bRegistered) { spagent::spagent_assistor::unregister_notification_events(conn_tool_wifi, m_WifiChangedEvt); } delete m_WifiChangedEvt; m_WifiChangedEvt = NULL; } //if(m_fMBBDeviceMonitoring) { // do { // Dbg("wait monitor circle break!"); // Sleep(300); // } while (m_fMBBDeviceMonitoring); //} if(m_HwDeviceMnt) { auto temp = m_HwDeviceMnt; m_HwDeviceMnt = NULL; Dbg("destroy hw instance..."); delete temp; } } ErrorCodeEnum CMobileDialFSM::OnInit() { LOG_FUNCTION(); Dbg("Mod version: %s, Complied at: %s %s", MOD_VERSION, __DATE__, __TIME__); #ifdef TWINKLE_LOCAL_DEBUG if (AllocConsole()) { FILE* here = NULL; freopen_s(&here, "CONOUT$", "w", stdout); freopen_s(&here, "CONOUT$", "w", stderr); Dbg("Debug console created."); } #endif ErrorCodeEnum eErr; int netAccessFlag=99, iFailMax = 99; int value = 0; CSimpleStringA csValue; CSimpleStringA csEntityName = GetEntityBase()->GetEntityName(); CSmartPointer spConfig, spConfigCen, spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Software, spConfig); GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); m_dwFailMax = DEFAULT_FAIL_CONNECT_MAX; m_TimeoutSec = DEFAULT_TIMEOUT_SEC; m_csVpnName = ""; spConfigRun->ReadConfigValue("init", "param1", m_csPhoneNum); if (m_csPhoneNum.GetLength() < 1) { Dbg("There are no config at runtime, config it's the new terminal device."); m_bRCfgHaveDial = false; } else { Dbg("For param, to read run cfg."); m_bRCfgHaveDial = true; spConfigRun->ReadConfigValue("init", "param2", m_csEntryName); spConfigRun->ReadConfigValue("init", "param3", m_csUserName); spConfigRun->ReadConfigValue("init", "param4", m_csPassword); spConfigRun->ReadConfigValue("init", "param5", m_csVpnName); } if(!m_csVpnName.IsNullOrEmpty()) { Dbg("Vpn Name: %s", (LPCTSTR)m_csVpnName); } int nValue = 0; if(spConfigRun->ReadConfigValueInt("init", "ManualManage", nValue) == 0 && nValue > 0) { Dbg("Require manage by user!!"); m_bManageByUser = true; } if(spConfigRun->ReadConfigValueInt("init", "GenAdvanced", nValue) == 0 && nValue > 0) { Dbg("Advanced Gen choose: %d", nValue); if(nValue == ADVANCE_RAS || nValue == ADVANCE_MBN || nValue == ADVANCE_MBB) { CSimpleStringA csTip; if(nValue == ADVANCE_RAS) { csTip = "当前终端选择的上网类型: 3G-RAS"; } else if(nValue == ADVANCE_MBN) { csTip = "当前终端选择的上网类型: 4G-MBN"; } else { csTip = "当前终端选择的上网类型: HuaWei-MBB"; } LogEvent(Severity_High, 0, (LPCTSTR)csTip); m_nAdvancedGen = nValue; } } m_recentInfo.usDialType = CNT_INVALID; m_recentInfo.ulRequestID = 0; if(spConfigRun->ReadConfigValue("Recent", "Type", csValue) == Error_Succeed && csValue.GetLength() > 0) { if(!csValue.Compare("MBN") && m_nAdvancedGen != ADVANCE_RAS && m_nAdvancedGen != ADVANCE_MBB) { m_recentInfo.usDialType = CNT_MBN; } else if(!csValue.Compare("RAS") && m_nAdvancedGen != ADVANCE_MBN && m_nAdvancedGen != ADVANCE_MBB) { m_recentInfo.usDialType = CNT_RAS; } } if(m_recentInfo.usDialType != CNT_INVALID) { spConfigRun->ReadConfigValue("Recent", "Dongle", m_recentInfo.strDongle); spConfigRun->ReadConfigValue("Recent", "Profile", m_recentInfo.strProfile); spConfigRun->ReadConfigValueInt("Recent", "Manual", m_recentInfo.fByManual); Dbg("Advanced connect device: %s", (LPCTSTR)m_recentInfo.strDongle); } GetCurWindowsVersion(); GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spConfigCen); // Read from CenterSetting in correct format [Josephus in 12:15:21 2016/4/18] CSimpleStringA csServer(""), csServerBackup(""); bool bLoadInCentSet = false; spConfigCen->ReadConfigValue(csEntityName, "Server", csServer); spConfigCen->ReadConfigValue(csEntityName, "Server_Backup", csServerBackup); if(csServer.GetLength() >= 7){ CAutoArray servSplits = csServer.Split(' '); if(servSplits.GetCount() >= 2){ m_csIp = servSplits[0]; m_csPort = servSplits[1]; bLoadInCentSet = true; }else{ Dbg("The serverString loaded in CenterSetting has illegal format %s", (LPCTSTR)csServer); } } if(!bLoadInCentSet && csServerBackup.GetLength() >= 7) { Dbg("To use the ServerBackup string(%s)", (LPCTSTR)csServerBackup); CAutoArray servSplits = csServerBackup.Split(' '); if(servSplits.GetCount() >= 2){ m_csIp = servSplits[0]; m_csPort = servSplits[1]; bLoadInCentSet = true; }else{ Dbg("The serverBackupString loaded in CenterSetting has illegal format"); } } Dbg("DualActive mark."); m_csIpBackup = ""; m_csPortBackup = ""; if(!bLoadInCentSet) { Dbg("For IP and port, no center setting, use local cfg."); spConfig->ReadConfigValue("init", "ip", m_csIp); spConfig->ReadConfigValue("init", "port", m_csPort); } else { if(csServerBackup.GetLength() >= 7) { Dbg("Store ServerBackup string(%s) after DualActive", (LPCTSTR)csServerBackup); CAutoArray servSplits = csServerBackup.Split(' '); if(servSplits.GetCount() >= 2) { if(!!servSplits[0].Compare("99.1.100.215")) { m_csIpBackup = servSplits[0]; m_csPortBackup = servSplits[1]; } }else{ Dbg("The serverBackupString loaded in CenterSetting has illegal format after DualActive"); } } } if((m_csIp.GetLength() < 7 || m_csPort.GetLength() <= 0) && (m_csIpBackup.GetLength() < 7 || m_csPortBackup.GetLength() <= 0) ) { Dbg("Get ip and port failed [IP#%s][Port#%s].", (LPCTSTR)m_csIp, (LPCTSTR)m_csPort); Dbg("Get backup ip and port failed [IP#%s][Port#%s].", (LPCTSTR)m_csIpBackup, (LPCTSTR)m_csPortBackup); LogError(Severity_High, Error_Param, CombineErrorCode(MBD_CENTERSETTING_LACK), "未能从配置中读取用于检测网络连接的服务其地址或端口,请检查!"); ShowFatalError("请配置用于MobileDial模块检测网络的服务器IP和端口"); return Error_Param; } CSystemStaticInfo sysInfo; eErr = GetEntityBase()->GetFunction()->GetSystemStaticInfo(sysInfo); if (eErr != Error_Succeed) { Dbg("Get System Static info failed(%d).",eErr); return Error_Unexpect; } m_csMachineType = sysInfo.strMachineType; m_csSite = sysInfo.strSite; m_strTerminalNo = sysInfo.strTerminalID; //m_strTerminalNo = "12345"; if(m_strTerminalNo.GetLength() < 10) { const int suffixLen = 10 - m_strTerminalNo.GetLength(); CSimpleStringA strTempTerminal(true); strTempTerminal.Append("0000000000", suffixLen); strTempTerminal += m_strTerminalNo; m_strTerminalNo = strTempTerminal; } else if(m_strTerminalNo.GetLength() > 10) { m_strTerminalNo = m_strTerminalNo.SubString(0, 10); } //Dbg("new terminal no: %s", m_strTerminalNo.GetData()); //return Error_Bug; //m_bPadAndFLB = false; //for(int i=MBD_NOT_INITIALIZED; i<=MBD_INTERNAL_ERROR; ++i) { // DWORD dwUserCode = (DWORD)((m_dwEntityID << 16) + (DWORD)(i)); // CSimpleStringA str = ConvertStatusToString((MOBILEDIAL_CONNECTION_STATE)i); // if(str.IndexOf("MOBILEDIAL_UNEXPECT_STATE(") == -1) { // SetCurState((MOBILEDIAL_CONNECTION_STATE)i); // CSimpleStringA csData = GetFurtherDetail(); // Dbg("0x%X - %s", dwUserCode, str.GetData()); // Dbg("%s", csData.GetData()); // } //} //return Error_Cancel; Dbg("%s:%s,%s,%s", (LPCTSTR)m_csPhoneNum, (LPCTSTR)m_csEntryName,(LPCTSTR)m_csMachineType, (LPCTSTR)m_csSite); Dbg("%s::%s, %s::%s", (LPCTSTR)m_csIp, (LPCTSTR)m_csPort, (LPCTSTR)m_csIpBackup, (LPCTSTR)m_csPortBackup); m_bBackupAvail = (m_csIpBackup.GetLength() >= 7 && m_csPortBackup.GetLength() > 0); if(m_bBackupAvail) { if(m_csIpBackup.Compare((LPCTSTR)m_csIp) == 0 && m_csPortBackup.Compare((LPCTSTR)m_csPortBackup) == 0) { m_bBackupAvail = false; } } WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2,2), &wsaData); if (iResult != 0) { Dbg("WSAStartup failed with error %d", iResult); RecordLastErrorMsg(iResult); return Error_IO; } if (CreateCheckSocket() != 0) { Dbg("failed to create socket for connecting test at the begin"); WSACleanup(); return Error_IO; } closesocket(m_sock); m_sock = INVALID_SOCKET; //m_csSite = "cmb.yzx"; //int bPingDisable = 0; //spConfigCen->ReadConfigValueInt(csEntityName, "PingDisable", bPingDisable); //if(!bPingDisable) { // ping1 = new CTWPing(); // ping1->Initial(m_csIp); // if(m_bBackupAvail && m_csIp.Compare(m_csIpBackup)) { // ping2 = new CTWPing(); // ping2->Initial(m_csIpBackup); // } //} if(!m_csMachineType.Compare("RVC.Pad", true) && !m_csSite.Compare("cmb.FLB", true)) { Dbg("Detect MachineType: %s & SiteType: %s", (LPCTSTR)m_csMachineType, (LPCTSTR)m_csSite); // 行内PAD,删除旧的配置文件 if(m_bRCfgHaveDial && !m_csPhoneNum.Compare("#777") && !m_csEntryName.Compare("szbranch") && !m_csUserName.Compare("123@szchinacmb.vpdn.gd") && !m_csPassword.Compare("123")) { Dbg("delete the old test dial param: %d", RasDeleteEntryA(NULL, m_csEntryName)); spConfigRun->WriteConfigValue("init", "param1", ""); spConfigRun->WriteConfigValue("init", "param2", ""); spConfigRun->WriteConfigValue("init", "param3", ""); spConfigRun->WriteConfigValue("init", "param4", ""); spConfigRun->WriteConfigValue("init", "param5", ""); m_csEntryName = m_csPhoneNum = m_csUserName = m_csPassword = ""; } m_bPadAndFLB = true; if(isUsingNewVerAllInOne()) { Dbg("Detect new version all_in_one condition."); m_nAdvancedGen = 0; } else { if(m_nAdvancedGen != ADVANCE_MBB) { m_blackSheep.Init(MAX_BLACK_SHEEP_NUM); mBlackSheepCount = 0; if(m_nAdvancedGen != ADVANCE_RAS) { Init4GComponent(); } if(m_nAdvancedGen != ADVANCE_MBN) { Init3GComponent(); } } else { InitHuaweiComponent(); } Recognized3GOr4G(); this->GetEntityBase()->GetFunction()->PostThreadPoolTask(new MBBDevicMonitorTask(this)); } } else { if(!m_csMachineType.Compare("RVC.Pad", true) && !m_csSite.Compare("cmb.LIB", true)) { Dbg("Detect MachineType: %s & SiteType: %s", (LPCTSTR)m_csMachineType, (LPCTSTR)m_csSite); m_bPadAndLIB = true; } m_TimerInterval = MOBILEDIAL_LIB_INTERVAL; } //电池电源监听线程 ITimerListener *pListener = new TimerOutHelper(this, &CMobileDialFSM::BatteryNotifierTimeOut); GetEntityBase()->GetFunction()->SetTimer(MOBILEDIAL_TIMER_ID, pListener, BATTERY_TIMER_INTERVAL); return Error_Succeed; } int CMobileDialFSM::ReadRecentValiDongle() { CSimpleStringA csInterfaceID; CSmartPointer spConfigRun; int nType = 0; if(!m_pMbn->GetInterfaceID(csInterfaceID)) { Dbg("GetInterfaceID failed in ReadRecentValiDongle."); } else { Dbg("GetInterfaceID(%s) suc.", (LPCTSTR)csInterfaceID); if(GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun) == Error_Succeed) { spConfigRun->ReadConfigValueInt("Interfaces", (LPCTSTR)csInterfaceID, nType); } Dbg("Interface:%s: nType:%d.", (LPCTSTR)csInterfaceID, nType); } return nType; } void CMobileDialFSM::WriteCurValiDongle(const CSimpleStringA& csInterfaceID, const int nType) { CSmartPointer spConfigRun; if(GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun) == Error_Succeed) { spConfigRun->WriteConfigValueInt("Interfaces", (LPCTSTR)csInterfaceID, nType); } return; } void CMobileDialFSM::Recognized3GOr4G() { LOG_FUNCTION(); static bool s_old3G = false; static bool s_old4G = false; SetCurState(MBD_NOT_INITIALIZED); s_old4G = m_n4G > 0; s_old3G = m_n3G > 0; ResetDongleInfos(); m_n3G = m_n4G = 0; m_34GReserved = 0; m_34GDialSuc = 0; if(isUsingNewVerAllInOne()) { LogEvent(Severity_Middle,CombineErrorCode(MBD_HOLD_MOBILEDONGLE), "当前使用新版分体式多合一设备"); BOOL bActive = FALSE, bConnected = FALSE; ErrorCodeEnum ec = m_SafeWirelessClient->IsActive(bActive, bConnected); if(ec == Error_Succeed) { if(bConnected) { int nNum = 0; ec = m_SafeWirelessClient->GetAPNConfigs(-1, nNum); } } return; } if(m_nAdvancedGen != ADVANCE_MBB) { int nMBN = m_nAdvancedGen != ADVANCE_RAS ? m_pMbn->EnumerateInterfaces(TRUE) : 0; int nRAS = m_nAdvancedGen != ADVANCE_MBN ? EnumCurRasDevices(TRUE) : 0; if(nMBN == 0 && nRAS == 0) { SetCurState(MBD_NO_MOBILEDONGLE); } else { if(nRAS > 0) { m_n3G = nRAS; if(!s_old3G) LogEvent(Severity_Middle,CombineErrorCode(MBD_HOLD_MOBILEDONGLE),"检测到3G无线宽带上网卡"); } if(nMBN > 0) { m_n4G = nMBN; if(!s_old4G) LogEvent(Severity_Middle,CombineErrorCode(MBD_HOLD_MOBILEDONGLE),"检测到4G无线宽带上网卡"); } if((nMBN < 0 && nRAS < 0) || (m_nAdvancedGen == ADVANCE_RAS && nRAS < 0) || (m_nAdvancedGen == ADVANCE_MBN && nMBN < 0)) { SetCurState(MBD_INTERNAL_ERROR); } } } else { CheckHWDeviceStatus(); } return; } ErrorCodeEnum CMobileDialFSM::OnExit() { GetEntityBase()->GetFunction()->ResetTimer(0, 0); if(m_bPadAndFLB && !isUsingNewVerAllInOne() ) { DisConnect(); m_pMbn->UnAdviseCustomEvents(); for(int i=0; iparam1 = 3; fsmEvent->param2 = 1; PostEventFIFO(fsmEvent); return; } else if(status == MBD_ACTIVATION_CONNECTED) { LogEvent(Severity_Middle, CombineErrorCode(status), "无线宽带上网卡已连接"); if(g_bFirstConnect) { g_bFirstConnect = FALSE; } } } Dbg("Walk normal way in connect style."); m_TimeoutSec = DEFAULT_TIMEOUT_SEC; CheckConnectionTask* task = new CheckConnectionTask(this); GetEntityBase()->GetFunction()->PostThreadPoolTask(task); SetSysVal(NET_STATUS_UNINIT); } void CMobileDialFSM::s0_on_exit() { } unsigned int CMobileDialFSM::s0_on_event(FSMEvent* pEvt) { int nRes = pEvt->param1; Dbg("s0_on_event %d, %d %d.", pEvt->iEvt, nRes, pEvt->param2); switch(pEvt->iEvt) { case USER_EVT_CKECK_CONNECTION_FINISHED: pEvt->SetHandled(); { if(nRes != 3) { bool bShouldBackup = !!(pEvt->param2 & 0x4); bool bRealBackup = !!(pEvt->param2 & 0x2); CSimpleStringA csIpPrint = bRealBackup ? m_csIpBackup : m_csIp; CSimpleStringA csPortPrint = bRealBackup ? m_csPortBackup : m_csPort; if(nRes == 0) { CSimpleStringA csMsg; csMsg = CSimpleStringA::Format("s0(idle): Connect to server(%s:%s) failed(%d) FailCount(%d) FailMax(%d).", (LPCTSTR)csIpPrint, (LPCTSTR)csPortPrint, m_dwLsErrCode, ++m_dwCkFailCount, m_dwFailMax); LogEvent(Severity_Middle, CombineErrorCode(MBD_CHECK_NETWORK_CONNETCTED), (LPCTSTR)csMsg); const MOBILEDIAL_CONNECTION_STATE state = GetCurState(); Dbg("s0(idle): %s.", ConvertStatusToString(state)); // fix bug which lead netbroken show more easy and earlier --Josephus at 8:59:47 20161211 if(m_dwCkFailCount < m_dwFailMax) { m_TimeoutSec = DEFAULT_TIMEOUT_SEC + 2 * m_dwCkFailCount; if(bShouldBackup && !bRealBackup) { Dbg("backup ip and port maybe no exist."); break; } //未达到连续次数的网络断开情况,防止状态跳转 nRes = 4; if(state == MBD_NETWORK_TIMEOUT) { Sleep(MOBILEDIAL_QUICK_TIMER_INTERVAL); } else { Sleep( MOBILEDIAL_FASTER_INTERVAL); } CheckConnectionTask* task = new CheckConnectionTask(this); if(bRealBackup) { task->m_bUseBackup = true; } GetEntityBase()->GetFunction()->PostThreadPoolTask(task); } else if(!bShouldBackup && m_bBackupAvail) { m_dwCkFailCount = 0; m_TimeoutSec = DEFAULT_TIMEOUT_SEC; //未达到连续次数的网络断开情况,防止状态跳转 nRes = 4; if(state == MBD_NETWORK_TIMEOUT){ Sleep(MOBILEDIAL_QUICK_TIMER_INTERVAL); } else{ Sleep(MOBILEDIAL_FASTER_INTERVAL); } CheckConnectionTask* task = new CheckConnectionTask(this); task->m_bUseBackup = true; GetEntityBase()->GetFunction()->PostThreadPoolTask(task); } } else { Dbg("s0(idle): Connect to server(%s:%s) result(%d)(%d), pad&FLB(%d) %s", (LPCTSTR)csIpPrint, (LPCTSTR)csPortPrint, nRes, m_dwLsErrCode, m_bPadAndFLB, ConvertStatusToString(GetCurState())); } m_dwOldErrCode = m_dwLsErrCode; } else if(pEvt->param2 == 1) { Dbg("Received convenient way."); nRes = 0; } } break; default: break; } return nRes; } //Connected void CMobileDialFSM::s1_on_entry() { LOG_FUNCTION(); LogEvent(Severity_Middle, CombineErrorCode(MBD_VALID_CONNECTED), "网络已连接"); ShowFatalError("网络已连接", TRUE); m_bConnected = true; SetCurState(MBD_VALID_CONNECTED); SendNetStatusMsg(); SetSysVal(NET_STATUS_CONNECTED); ReportConnectType(); m_dwCkFailCount = 0; m_TimeoutSec = DEFAULT_TIMEOUT_SEC; ScheduleTimer(CHECK_CONNECT_TIMER_ID, m_TimerInterval); } void CMobileDialFSM::s1_on_exit() { CancelTimer(CHECK_CONNECT_TIMER_ID); CancelTimer(CHECK_CONNECT_BACKUP_TIMER_ID); if(m_nAdvancedGen == 2) { if(mMBBParam.connectType == MBB_CONNECT_WIRE) { if(CheckLANConnectStatus() == 0) { SetHWStatus(MBD_NO_MOBILEDONGLE); } else { SetHWStatus(MBD_ACTIVATION_CONNECTED); } } } } unsigned int CMobileDialFSM::s1_on_event(FSMEvent* pEvt) { int nRes = 0; Dbg("s1_on_event %d, %d, %d", pEvt->iEvt, pEvt->param1, pEvt->param2); switch(pEvt->iEvt) { case EVT_TIMER: { if(pEvt->param1 == CHECK_CONNECT_TIMER_ID || pEvt->param1 == CHECK_CONNECT_BACKUP_TIMER_ID) { pEvt->SetHandled(); if(IsConnectedFromHB()) { m_dwCkFailCount = 0; ScheduleTimer(CHECK_CONNECT_TIMER_ID, MOBILEDIAL_HBEAT_INTERVAL); } else { CheckConnectionTask* task = new CheckConnectionTask(this); if(pEvt->param1 == CHECK_CONNECT_BACKUP_TIMER_ID) task->m_bUseBackup = true; GetEntityBase()->GetFunction()->PostThreadPoolTask(task); } } } break; case USER_EVT_CKECK_CONNECTION_FINISHED: pEvt->SetHandled(); { nRes = pEvt->param1; bool bShouldBackup = !!(pEvt->param2 & 0x4); bool bRealBackup = !!(pEvt->param2 & 0x2); UINT uTimerID = bRealBackup ? CHECK_CONNECT_BACKUP_TIMER_ID : CHECK_CONNECT_TIMER_ID; if(nRes == 1) { m_dwCkFailCount = 0; ScheduleTimer(uTimerID, m_TimerInterval); } else if(nRes == 0) { CSimpleStringA csIpPrint = bRealBackup ? m_csIpBackup : m_csIp; CSimpleStringA csPortPrint = bRealBackup ? m_csPortBackup : m_csPort; CSimpleStringA csMsg; csMsg = CSimpleStringA::Format("s1(connected): Connect to server(%s:%s) failed(%d) FailCount(%d) FailMax(%d).", (LPCTSTR)csIpPrint, (LPCTSTR)csPortPrint, m_dwLsErrCode, ++m_dwCkFailCount, m_dwFailMax); LogEvent(Severity_Middle, CombineErrorCode(MBD_CHECK_NETWORK_CONNETCTED), (LPCTSTR)csMsg); const MOBILEDIAL_CONNECTION_STATE state = GetCurState(); Dbg("s1(connected): %s.", ConvertStatusToString(state)); if(m_dwCkFailCount < m_dwFailMax) { if(bShouldBackup && !bRealBackup) { break; } m_TimeoutSec = DEFAULT_TIMEOUT_SEC + 2 * m_dwCkFailCount; //未达到连续次数的网络断开情况,防止状态跳转,并将时间间隔改成1s聆询 nRes = 3; if(state == MBD_NETWORK_TIMEOUT) { ScheduleTimer(uTimerID, MOBILEDIAL_QUICK_TIMER_INTERVAL); } else { ScheduleTimer(uTimerID, MOBILEDIAL_FASTER_INTERVAL); } } else if(!bShouldBackup && m_bBackupAvail) { m_dwCkFailCount = 0; m_TimeoutSec = DEFAULT_TIMEOUT_SEC; //未达到连续次数的网络断开情况,防止状态跳转,并将时间间隔改成1s聆询 nRes = 3; if(state == MBD_NETWORK_TIMEOUT) { ScheduleTimer(CHECK_CONNECT_BACKUP_TIMER_ID, MOBILEDIAL_QUICK_TIMER_INTERVAL); } else { ScheduleTimer(CHECK_CONNECT_BACKUP_TIMER_ID, MOBILEDIAL_FASTER_INTERVAL); } } m_dwOldErrCode = m_dwLsErrCode; } } break; case USER_EVT_SIGNAL: pEvt->SetHandled(); { NetStatusVar evt; m_signalVal = pEvt->param1; Dbg("s1(connected): Send Signal %d !!", m_signalVal); evt.netstatus = m_signalVal; SpSendBroadcast(m_pEntity->GetFunction(),SP_MSG_OF(NetStatusVar),SP_MSG_SIG_OF(NetStatusVar),evt); } break; case USER_EVT_DEVICE_LEAVE: pEvt->SetHandled(); BroadcastCableChangedFSMEvent(pEvt); if(pEvt->param2 == 0) { nRes = 1; } else { nRes = 0; Recognized3GOr4G(); auto state = GetCurState(); if(state == MBD_NO_MOBILEDONGLE) { nRes = 1; } else if(state == MBD_INTERNAL_ERROR) { PostEventFIFO(new FSMEvent(USER_EVT_FAILURE)); } else if(state == MBD_ACTIVATION_DISCONNECTED) { FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DISCONNECT_COMPLETE); fsmEvent->param1 = 0; fsmEvent->param2 = 0; PostEventFIFO(fsmEvent); } else { nRes = 2; } } break; default: break; } return nRes; } //Disconnected void CMobileDialFSM::s2_on_entry() { LOG_FUNCTION(); m_bConnected = false; m_dwCkFailCount = 0; m_TimeoutSec = DEFAULT_TIMEOUT_SEC + 2 * m_dwFailMax; SendNetStatusMsg(); SetSysVal(NET_STATUS_DISCONNECT); MOBILEDIAL_CONNECTION_STATE status = GetCurState(); if(m_bPadAndFLB && !isUsingNewVerAllInOne() && status > MBD_NETWORK_SEPERATE) { LogEvent(Severity_Middle,CombineErrorCode(MBD_INVALID_CONNECTED), "网络已断开"); if(status == MBD_NO_MOBILEDONGLE){ FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DEVICE_LEAVE); fsmEvent->param1 = 0; fsmEvent->param2 = 0; PostEventFIFO(fsmEvent); } else if(status == MBD_ACTIVATION_DISCONNECTED){ FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DISCONNECT_COMPLETE); fsmEvent->param1 = 0; fsmEvent->param2 = 0; PostEventFIFO(fsmEvent); } else if(status == MBD_WLAN_DISCONNECTED) { FSMEvent* fsmEvent = new FSMEvent(EVT_USER_WLAN_CONNECT); fsmEvent->param1 = 0; fsmEvent->param2 = 0; PostEventFIFO(fsmEvent); } else { PostEventFIFO(new FSMEvent(USER_EVT_FAILURE)); } } else { CSimpleStringA csTemp; if(m_bPadAndLIB && CheckLANConnectStatus() == 0) { SetCurState(MBD_NO_FOUND_CABLE); ShowFatalError(GetFurtherDetail()); if(status == MBD_NETWORK_TIMEOUT){ ScheduleTimer(CHECK_CONNECT_TIMER_ID, MOBILEDIAL_QUICK_TIMER_INTERVAL); }else{ ScheduleTimer(CHECK_CONNECT_TIMER_ID, MOBILEDIAL_FASTER_INTERVAL); } } else{ ShowFatalError(GetFurtherDetail()); if(status == MBD_NETWORK_TIMEOUT) { ScheduleTimer(CHECK_CONNECT_TIMER_ID, MOBILEDIAL_QUICK_TIMER_PLUS_INTERVAL); }else{ ScheduleTimer(CHECK_CONNECT_TIMER_ID, MOBILEDIAL_FASTER_PLUS_INTERVAL); } } } } void CMobileDialFSM::s2_on_exit() { CancelTimer(CHECK_CONNECT_TIMER_ID); //SetSysVal(NET_STATUS_UNINIT); } unsigned int CMobileDialFSM::s2_on_event(FSMEvent* pEvt) { int nRes = 0; static int s_nTimes = -1; static bool bCheckSwitch = false; switch(pEvt->iEvt) { case EVT_TIMER: { if(pEvt->param1 != CHECK_CONNECT_TIMER_ID) break; pEvt->SetHandled(); if(IsConnectedFromHB()) { Dbg("(s2_event)Connected status from HB, change status."); LogEvent(Severity_High, CombineErrorCode(MBD_VALID_CONNECTED), "心跳正常,执行跳转"); // s_nTimes = 0; nRes = 1; } else { if(s_nTimes == 0) { PingTask* pingTask = new PingTask(this); GetEntityBase()->GetFunction()->PostEntityTaskFIFO(pingTask); s_nTimes++; } else if(s_nTimes != -1) { if(++s_nTimes > PING_INTERVAL) { s_nTimes = 0; } } if(m_bPadAndFLB && !isUsingNewVerAllInOne() && m_n3G > 0) { if(!bCheckSwitch) { if(EnumCurRasDevices() == 0) { FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DEVICE_LEAVE); fsmEvent->param1 = 0; fsmEvent->param2 = 3; PostEventFIFO(fsmEvent); } bCheckSwitch = true; } else { bCheckSwitch = false; } } ScheduleTimer(CHECK_CONNECT_TIMER_ID, MOBILEDIAL_FASTER_PLUS_INTERVAL); } } break; case USER_EVT_PING_RESULT: { pEvt->SetHandled(); const int nPingResult = pEvt->param1; if(nPingResult == 0) { LogWarn(Severity_Middle, Error_NetBroken, 0, "尝试Ping连接至分行服务失败!"); } else if(nPingResult > 0) { if(nPingResult == 3) { LogEvent(Severity_None, 0, "Attempt to ping to branch server both succ."); }else if(nPingResult == 2) { LogEvent(Severity_None, 0, CSimpleStringA::Format("Attempt to ping to branch server[%s] succ.", (LPCTSTR)m_csIpBackup)); }else if(nPingResult == 1) { LogEvent(Severity_None, 0, CSimpleStringA::Format( "Attempt to ping to branch server[%s] succ.", (LPCTSTR)m_csIp)); } } else { s_nTimes = -1; Dbg("CheckNetSituationWithPing returned %d, Set flag !", nPingResult); } } break; case USER_EVT_DEVICE_LEAVE: pEvt->SetHandled(); BroadcastCableChangedFSMEvent(pEvt); if(pEvt->param2 == 0) { nRes = 1; } else { nRes = 0; Recognized3GOr4G(); auto state = GetCurState(); if(state == MBD_NO_MOBILEDONGLE) { nRes = 1; } else if(state == MBD_INTERNAL_ERROR) { PostEventFIFO(new FSMEvent(USER_EVT_FAILURE)); } else if(state == MBD_ACTIVATION_DISCONNECTED) { FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DISCONNECT_COMPLETE); fsmEvent->param1 = 0; fsmEvent->param2 = 0; PostEventFIFO(fsmEvent); } else { nRes = 2; } } break; case USER_EVT_FAILURE: Dbg("s2(disconnected): goto failed status %s", ConvertStatusToString(GetCurState())); pEvt->SetHandled(); break; case EVT_USER_WLAN_CONNECT: pEvt->SetHandled(); break; case EVT_USER_WIRELESS_STATE: BroadcastCableChangedFSMEvent(pEvt); pEvt->SetHandled(); nRes = pEvt->param1; break; default: break; } return nRes; } //Failed void CMobileDialFSM::s3_on_entry() { LOG_FUNCTION(); const MOBILEDIAL_CONNECTION_STATE state = GetCurState(); CSimpleStringA csErrorString = GetFurtherDetail(); ShowFatalError(csErrorString); SetSysVal(NET_STATUS_ERROR); if(state == MBD_NETWORK_INVALID_SOCKET) {//hardly happen. if(WSACleanup() == SOCKET_ERROR) { Dbg("s3(failed): WSACleanup() failed"); RecordLastErrorMsg(WSAGetLastError()); return; } Sleep(300); WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2,2), &wsaData); if (iResult != 0) { Dbg("s3(failed): WSAStartup() failed"); RecordLastErrorMsg(iResult); return; } FSMEvent* fsmEvent = new FSMEvent(USER_EVT_RECOVER); PostEventLIFO(fsmEvent); } else { m_bConnected = false; m_dwCkFailCount = 0; SendNetStatusMsg(); int mustFlag = 0; if(state == MBD_NO_PROFILE) { mustFlag = 4; } else if(state == MBD_ACTIVATION_CONNECTING) { ScheduleTimer(FAILURE_WAIT_TIMER_ID, MOBILEDIAL_FASTER_INTERVAL); return; } m_nRecoverMax = 0; ScheduleTimer(FAILURE_WAIT_TIMER_ID, MOBILEDIAL_CHECKDONGLE_INTERVAL); } } void CMobileDialFSM::s3_on_exit() { CancelTimer(FAILURE_WAIT_TIMER_ID); //SetSysVal(NET_STATUS_UNINIT); } unsigned int CMobileDialFSM::s3_on_event(FSMEvent* pEvt) { int nRes = pEvt->param1; Dbg("s3_on_event(failed) %d, %d, %d", pEvt->iEvt, pEvt->param1, pEvt->param2); switch(pEvt->iEvt) { case USER_EVT_ATTEMPT: pEvt->SetHandled(); break; case USER_EVT_RECOVER: pEvt->SetHandled(); if(GetCurState() == MBD_ACTIVATION_DISCONNECTED) { // // 因没有处理 OnConnectionComplete: newInterface: requestID: 0 status 0} 事件 // 导致当前处于没连接状态,但是网络好的情况 [6/16/2020 17:47 @Gifur] // Recognized3GOr4G(); } break; //case USER_EVT_STATUSCHANGE: // pEvt->SetHandled(); // { // Dbg("s3(failed): StatusChanged[%s]", ConvertStatusToString((MOBILEDIAL_CONNECTION_STATE)nRes)); // Recognized3GOr4G(); // } // break; case EVT_TIMER: pEvt->SetHandled(); if(pEvt->param1 == FAILURE_WAIT_TIMER_ID) { if(IsConnectedFromHB()) { Dbg("s3(failed): EVT_TIMER Creates USER_EVT_RECOVER triggered by heartbeat !!"); PostEventLIFO(new FSMEvent(USER_EVT_RECOVER)); } else { if(m_bPadAndFLB && !isUsingNewVerAllInOne() ) { if(m_nAdvancedGen != 4 && m_nAdvancedGen != 2) { int nRAS = EnumCurRasDevices(); if(nRAS >= 0 && nRAS != m_n3G) { FSMEvent* fsmEvent = new FSMEvent(m_n3G > nRAS ? USER_EVT_DEVICE_LEAVE : USER_EVT_DEVICE_ARRIVAL); fsmEvent->param1 = 0; fsmEvent->param2 = 3; PostEventLIFO(fsmEvent); } } } if(!m_bManageByUser && ++m_nRecoverMax > ATTEMPT_INTERVAL) { Recognized3GOr4G(); PostEventLIFO(new FSMEvent(USER_EVT_ATTEMPT)); } else { ScheduleTimer(FAILURE_WAIT_TIMER_ID, MOBILEDIAL_CHECKDONGLE_INTERVAL); } } } break; case USER_EVT_DEVICE_LEAVE: pEvt->SetHandled(); BroadcastCableChangedFSMEvent(pEvt); if(pEvt->param2 == 0) { nRes = 1; } else { nRes = 0; Recognized3GOr4G(); auto state = GetCurState(); if(state == MBD_NO_MOBILEDONGLE) { nRes = 1; } else if(state == MBD_ACTIVATION_DISCONNECTED) { FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DISCONNECT_COMPLETE); fsmEvent->param1 = 0; fsmEvent->param2 = 0; PostEventFIFO(fsmEvent); } else { nRes = 2; } } break; case USER_EVT_DEVICE_ARRIVAL: pEvt->SetHandled(); { BroadcastCableChangedFSMEvent(pEvt); Recognized3GOr4G(); if(GetCurState() == MBD_ACTIVATION_DISCONNECTED){ PostEventFIFO(new FSMEvent(USER_EVT_DISCONNECT_COMPLETE)); nRes = 1; } else { PostEventFIFO(new FSMEvent(USER_EVT_RECOVER)); nRes = 0; } } break; case USER_EVT_CONNECT_COMPLETE: BroadcastCableChangedFSMEvent(pEvt); case USER_EVT_DISCONNECT_COMPLETE: { pEvt->SetHandled(); //如果窗口是打开的那就让拨号窗口去更新状态 if(!m_hMainWnd) { Recognized3GOr4G(); } //PostEventLIFO(new FSMEvent(USER_EVT_RECOVER)); } break; default: break; } return nRes; } //OffLine void CMobileDialFSM::s4_on_entry() { LOG_FUNCTION(); #if !SUPPORT_DIAL_FROM_WEB m_34GDialSuc = 0; ShowFatalError("未检测到无线宽带上网卡,请重连设备"); m_bConnected = false; m_dwCkFailCount = 0; SendNetStatusMsg(); SetSysVal(NET_STATUS_NO_DEVICE); ScheduleTimer(CHECK_NETCARD_TIMER_ID, MOBILEDIAL_CHECKDONGLE_INTERVAL); #else Dbg("Walk normal way in connect style."); m_TimeoutSec = DEFAULT_TIMEOUT_SEC; CheckConnectionTask* task = new CheckConnectionTask(this); GetEntityBase()->GetFunction()->PostThreadPoolTask(task); m_offDeviceFlag = 0; #endif } void CMobileDialFSM::s4_on_exit() { m_offDeviceFlag = 0; CancelTimer(CHECK_NETCARD_TIMER_ID); //SetSysVal(NET_STATUS_UNINIT); } unsigned int CMobileDialFSM::s4_on_event(FSMEvent* pEvt) { int nRes = pEvt->param1; Dbg("s4_on_event %d, %d, %d", pEvt->iEvt, pEvt->param1, pEvt->param2); switch(pEvt->iEvt) { #if SUPPORT_DIAL_FROM_WEB case USER_EVT_CKECK_CONNECTION_FINISHED: pEvt->SetHandled(); { bool bShouldBackup = !!(pEvt->param2 & 0x4); bool bRealBackup = !!(pEvt->param2 & 0x2); CSimpleStringA csIpPrint = bRealBackup ? m_csIpBackup : m_csIp; CSimpleStringA csPortPrint = bRealBackup ? m_csPortBackup : m_csPort; if(nRes == 0) { CSimpleStringA csMsg; csMsg = CSimpleStringA::Format("s4(no device): Connect to server(%s:%s) failed(%d) FailCount(%d) FailMax(%d).", (LPCTSTR)csIpPrint, (LPCTSTR)csPortPrint, m_dwLsErrCode, ++m_dwCkFailCount, m_dwFailMax); LogEvent(Severity_Middle, CombineErrorCode(MBD_CHECK_NETWORK_CONNETCTED), (LPCTSTR)csMsg); const MOBILEDIAL_CONNECTION_STATE state = GetCurState(); Dbg("s4(no device): %s.", ConvertStatusToString(state)); // fix bug which lead netbroken show more easy and earlier --Josephus at 8:59:47 20161211 if(m_dwCkFailCount < DEFAULT_FAIL_CONNECT_LESS) { m_TimeoutSec = DEFAULT_TIMEOUT_SEC + 2 * m_dwCkFailCount; if(bShouldBackup && !bRealBackup) { Dbg("backup ip and port maybe no exist."); break; } //未达到连续次数的网络断开情况,防止状态跳转 nRes = 4; if(state == MBD_NETWORK_TIMEOUT) { Sleep(MOBILEDIAL_QUICK_TIMER_INTERVAL); } else { Sleep( MOBILEDIAL_FASTER_INTERVAL); } CheckConnectionTask* task = new CheckConnectionTask(this); if(bRealBackup) { task->m_bUseBackup = true; } GetEntityBase()->GetFunction()->PostThreadPoolTask(task); } else if(!bShouldBackup && m_bBackupAvail) { m_dwCkFailCount = 0; m_TimeoutSec = DEFAULT_TIMEOUT_SEC; //未达到连续次数的网络断开情况,防止状态跳转 nRes = 4; if(state == MBD_NETWORK_TIMEOUT){ Sleep(MOBILEDIAL_QUICK_TIMER_INTERVAL); } else{ Sleep(MOBILEDIAL_FASTER_INTERVAL); } CheckConnectionTask* task = new CheckConnectionTask(this); task->m_bUseBackup = true; GetEntityBase()->GetFunction()->PostThreadPoolTask(task); } else { if(m_offDeviceFlag == 0) { m_34GDialSuc = 0; ShowFatalError("未检测到无线宽带上网卡,请重连设备"); m_bConnected = false; m_dwCkFailCount = 0; SendNetStatusMsg(); SetSysVal(NET_STATUS_NO_DEVICE); m_offDeviceFlag = 1; } ScheduleTimer(CHECK_NETCARD_TIMER_ID, MOBILEDIAL_CHECKDONGLE_INTERVAL); } } else { //没网卡也能连接上网,适用于分行使用网页拨号上网的情况 Dbg("s4(no device): Connect to server(%s:%s) result(%d)(%d), pad&FLB(%d) %s", (LPCTSTR)csIpPrint, (LPCTSTR)csPortPrint, nRes, m_dwLsErrCode, m_bPadAndFLB, ConvertStatusToString(GetCurState())); } m_dwOldErrCode = m_dwLsErrCode; } break; #endif case USER_EVT_DEVICE_ARRIVAL: pEvt->SetHandled(); { BroadcastCableChangedFSMEvent(pEvt); Recognized3GOr4G(); if(GetCurState() == MBD_ACTIVATION_DISCONNECTED){ nRes = 1; } else { nRes = 0; } } break; case EVT_TIMER: if(pEvt->param1 == CHECK_NETCARD_TIMER_ID) { pEvt->SetHandled(); if(m_nAdvancedGen != 4 && m_nAdvancedGen != 2) { if(EnumCurRasDevices() > 0) { FSMEvent* pEvt = new FSMEvent(USER_EVT_DEVICE_ARRIVAL); pEvt->param1 = 0; pEvt->param2 = 3; PostEventLIFO(pEvt); break; } else { #if !SUPPORT_DIAL_FROM_WEB ScheduleTimer(CHECK_NETCARD_TIMER_ID, MOBILEDIAL_CHECKDONGLE_INTERVAL); #endif } } else if(m_nAdvancedGen == 2) { LOG_ASSERT(mMBBParam.connectType == MBB_CONNECT_WIRE); if(CheckLANConnectStatus() == 0) { //SetHWStatus(MBD_NO_MOBILEDONGLE); } else { //SetHWStatus(MBD_ACTIVATION_CONNECTED); FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DEVICE_ARRIVAL); fsmEvent->param1 = 0; fsmEvent->param2 = 2; PostEventFIFO(fsmEvent); break; } } #if SUPPORT_DIAL_FROM_WEB m_TimeoutSec = DEFAULT_TIMEOUT_SEC; CheckConnectionTask* task = new CheckConnectionTask(this); GetEntityBase()->GetFunction()->PostThreadPoolTask(task); #endif } break; default: break; } return nRes; } //Deactivated void CMobileDialFSM::s5_on_entry() { LOG_FUNCTION(); LogEvent(Severity_High, CombineErrorCode(MBD_CABLE_DIALUP_DISCONNETED), "无线宽带上网卡未连接"); //BroadcastCableChangedEvent(MBD_CABLE_DIALUP_DISCONNETED); SendMsgToDialog("无线宽带上网卡未连接"); m_bConnected = false; m_34GDialSuc = 0; m_dwCkFailCount = 0; SendNetStatusMsg(); SetSysVal(NET_STATUS_DIAL_OFF); if(!m_bManageByUser || g_bFirstConnect) { if(g_bFirstConnect) { g_bFirstConnect = FALSE; Dbg("Execute First ConnectTask"); } // 处理3G网卡在连接的状态下直接拔掉的情形: // 先接收到断开连接的事件,后续才发现到设备拔离的事件,所以要做延迟拨号处理,但测试发现尽管延迟了3秒都没有起到真正的作用 if(m_n3G > 0) { ScheduleTimer(CHECK_PRE_RASDEVICE_CHANGED_TIMER_ID, MOBILEDIAL_FASTERDIALRT_INTERVAL); } else { ConnectTask* task = new ConnectTask(this); GetEntityBase()->GetFunction()->PostThreadPoolTask(task); } } else { Dbg("Detect ManageByUser mode !!!"); if(m_n3G > 0) { ScheduleTimer(CHECK_RASDEVICE_CHANGED_TIMER_ID, MOBILEDIAL_FASTERDIALRT_INTERVAL); } } } void CMobileDialFSM::s5_on_exit() { CancelTimer(CHECK_CONNECT_DIAL_TIMER_ID); CancelTimer(CHECK_CONNECT_TIMER_ID); CancelTimer(CHECK_RASDEVICE_CHANGED_TIMER_ID); //SetSysVal(NET_STATUS_UNINIT); } unsigned int CMobileDialFSM::s5_on_event(FSMEvent* pEvt) { int nRes = pEvt->param1; Dbg("s5_on_event %d, %d, %d", pEvt->iEvt, pEvt->param1, pEvt->param2); switch(pEvt->iEvt) { case USER_EVT_CONNECT_COMPLETE: pEvt->SetHandled(); { BroadcastCableChangedFSMEvent(pEvt); if(pEvt->param2 == ADVANCE_RAS) { if(pEvt->param1 == 1) { UpdateRasConnectState(true); nRes = 0; } else if(pEvt->param1 == -1) { _FormatRasError(g_dwRasError); if(m_34GReserved != ADVANCE_RAS) { Dbg("Manual dial from outside(%d) ?", m_34GReserved); m_34GReserved = ADVANCE_RAS; } else { EraseTheRecentInfo((ULONG)g_hrasconn); } // Move here [1/24/2019 17:34 @Gifur] RasHangUpSuffix(); SetRasStatus(MBD_RASDIAL_FAILED); m_34GDialSuc = 0; nRes = 1; } } else if(pEvt->param2 == ADVANCE_MBB) { LOG_ASSERT(g_DongleInfos.GetCount() > 0); _GetMBBDeviceInfo(g_DongleInfos[0]); } } break; case USER_EVT_CONNECT_FINISHED: pEvt->SetHandled(); { if(pEvt->param1 < 0) { nRes = 0; } else { SendNetStatusMsg(); if(pEvt->param1 == ADVANCE_RAS) { LogEvent(Severity_Middle,CombineErrorCode(MBD_RAS_DIALUP_CONNETED),"3G拨号成功,等待响应"); m_34GDialSuc = ADVANCE_RAS; ScheduleTimer(CHECK_CONNECT_DIAL_TIMER_ID, MOBILEDIAL_FASTERDIALRT_INTERVAL); } else if(pEvt->param1 == ADVANCE_MBN) { LogEvent(Severity_Middle,CombineErrorCode(MBD_MBN_DIALUP_CONNETED),"4G拨号成功,等待响应"); m_34GDialSuc = ADVANCE_MBN; ScheduleTimer(CHECK_CONNECT_MBN_TIMER_ID, MOBILEDIAL_WAITDIALRT_INTERVAL); } else if(pEvt->param1 == ADVANCE_MBB) { LogEvent(Severity_Middle,CombineErrorCode(MBD_MBB_DIALUP_CONNECTED),"MBB 拨号成功"); m_34GDialSuc = ADVANCE_MBB; FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CONNECT_COMPLETE); fsmEvent->param1 = 0; fsmEvent->param2 = ADVANCE_MBB; PostEventFIFO(fsmEvent); } } } break; case EVT_TIMER: { if(pEvt->param1 == CHECK_CONNECT_MBN_TIMER_ID) { pEvt->SetHandled(); Dbg("timeout after 4g dial suc, change status auto."); nRes = 0; if(m_pMbn->CheckAndRefleshCurInterface()) { const MOBILEDIAL_CONNECTION_STATE state = GetCurState(); if(state < MBD_NETWORK_SEPERATE) {//find connected. FSMEvent* pEvent = new FSMEvent(USER_EVT_CONNECT_COMPLETE); pEvent->param1 = 0; pEvent->param2 = 0; PostEventFIFO(pEvent); nRes = 1; //cancel event. LogEvent(Severity_Middle,CombineErrorCode(MBD_UNKNOWN),"响应超时,自动跳转"); } else if(state == MBD_ACTIVATION_CONNECTING) {//still connecting nRes = 1; //cancel event. ScheduleTimer(CHECK_CONNECT_MBN_TIMER_ID, MOBILEDIAL_FASTERDIALRT_INTERVAL); } else if(state == MBD_ACTIVATION_DISCONNECTED) {//hardly happen but still has chance. nRes = 1; //cancel event. if(!m_bManageByUser) { ConnectTask* task = new ConnectTask(this); GetEntityBase()->GetFunction()->PostThreadPoolTask(task); } else { Dbg("Detect ManageByUser mode !!!"); } } } } else if(pEvt->param1 == CHECK_CONNECT_DIAL_TIMER_ID) { pEvt->SetHandled(); Dbg("timeout after 3g dial suc, change status auto."); nRes = 0; MOBILEDIAL_CONNECTION_STATE state = GetRasStatus(); if(state == MBD_ACTIVATION_CONNECTED) { nRes = 1; //cancel event. FSMEvent* pEvent = new FSMEvent(USER_EVT_CONNECT_COMPLETE); pEvent->param1 = 0; pEvent->param2 = ADVANCE_RAS; PostEventFIFO(pEvent); LogEvent(Severity_Middle,CombineErrorCode(MBD_RAS_DIALUP_CONNETED),"3G拨号成功,超时跳转"); } else if(state == MBD_ACTIVATION_CONNECTING) { nRes = 1; //cancel event. if(MOBILEDIAL_WAITDIALRT_INTERVAL > MOBILEDIAL_FASTERDIALRT_INTERVAL) { ScheduleTimer(CHECK_CONNECT_DIAL_TIMER_ID, MOBILEDIAL_WAITDIALRT_INTERVAL - MOBILEDIAL_FASTERDIALRT_INTERVAL); } else { ScheduleTimer(CHECK_CONNECT_DIAL_TIMER_ID, MOBILEDIAL_WAITDIALRT_INTERVAL); } } } else if(pEvt->param1 == CHECK_RASDEVICE_CHANGED_TIMER_ID || pEvt->param1 == CHECK_PRE_RASDEVICE_CHANGED_TIMER_ID) { if(m_nAdvancedGen != 4 && m_nAdvancedGen != 2 && EnumCurRasDevices() == 0) { FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DEVICE_LEAVE); fsmEvent->param1 = 0; fsmEvent->param2 = 3; PostEventFIFO(fsmEvent); break; } else if(pEvt->param1 == CHECK_PRE_RASDEVICE_CHANGED_TIMER_ID) { ConnectTask* task = new ConnectTask(this); GetEntityBase()->GetFunction()->PostThreadPoolTask(task); } ScheduleTimer(CHECK_RASDEVICE_CHANGED_TIMER_ID, MOBILEDIAL_FASTERDIALRT_INTERVAL); } } break; case USER_EVT_DEVICE_LEAVE: pEvt->SetHandled(); BroadcastCableChangedFSMEvent(pEvt); if(pEvt->param2 == 0) { nRes = 1; } else { nRes = 0; Recognized3GOr4G(); auto state = GetCurState(); if(state == MBD_NO_MOBILEDONGLE) { nRes = 1; } else if(state == MBD_ACTIVATION_DISCONNECTED) { if(!m_bManageByUser) { ConnectTask* task = new ConnectTask(this); GetEntityBase()->GetFunction()->PostThreadPoolTask(task); } else { Dbg("Detect ManageByUser mode !!!"); } } else { nRes = 2; } } break; default: break; } return nRes; } void CMobileDialFSM::s6_on_entry() { LOG_FUNCTION(); if(m_nAdvancedGen != 4 && m_nAdvancedGen != 2 && !isUsingNewVerAllInOne()) { ScheduleTimer(CHECK_RASDEVICE_CHANGED_TIMER_ID, DEV_CHANGED_TIMER_INTERVAL); } return; } void CMobileDialFSM::s6_on_exit() { LOG_FUNCTION(); CancelTimer(CHECK_RASDEVICE_CHANGED_TIMER_ID); Recognized3GOr4G(); return; } unsigned int CMobileDialFSM::s6_on_event(FSMEvent* pEvt) { int nRes = pEvt->param1; Dbg("s6_on_event %d, %d, %d", pEvt->iEvt, pEvt->param1, pEvt->param2); switch(pEvt->iEvt) { case EVT_TIMER: if(pEvt->param1 == CHECK_RASDEVICE_CHANGED_TIMER_ID) { pEvt->SetHandled(); int nTimerInterval = DEV_CHANGED_TIMER_INTERVAL; int nRAS = EnumCurRasDevices(); if(nRAS != m_n3G) { TellDlgTheResult(Error_Succeed, WM_DONGLE_CHANGE, 0); } else { nTimerInterval = DEV_CHANGED_TIMER_INTERVAL * 3; } ScheduleTimer(CHECK_RASDEVICE_CHANGED_TIMER_ID, nTimerInterval); } break; default: break; } return 0; } /*Linking*/ void CMobileDialFSM::s7_on_entry() { LOG_FUNCTION(); if(mMBBParam.wlanConnectParam.strPassword.IsNullOrEmpty() || mMBBParam.wlanConnectParam.strUsername.IsNullOrEmpty()) { SetHWStatus(MBD_RUN_CONFIG_INCOMPLEMENT); PostEventFIFO(new FSMEvent(USER_EVT_FAILURE)); } else { m_dwWlanConnectTimes = 0; ScheduleTimer(TIMER_TRY_LINK_ID, MOBILEDIAL_QUICK_TIMER_INTERVAL); SetHWStatus(MBD_WLAN_DISCONNECTED); } m_bConnected = false; ShowFatalError(GetFurtherDetail()); SendNetStatusMsg(); } void CMobileDialFSM::s7_on_exit() { if(GetHWStatus() == MBD_WLAN_CONNECTED) { m_dwWlanConnectTimes = 0; ShowFatalError("WLAN 已连接", TRUE); Recognized3GOr4G(); } CancelTimer(TIMER_TRY_LINK_ID); } unsigned int CMobileDialFSM::s7_on_event(FSMEvent* evt) { unsigned int uRet = 0; Dbg("s7_on_event %d, %d, %d", evt->iEvt, evt->param1, evt->param2); switch(evt->iEvt) { case EVT_TIMER: { if(evt->param1 == TIMER_TRY_LINK_ID) { evt->SetHandled(); if(NeedToConnectWifi()) { SetHWStatus(MBD_WLAN_CONNECTING); WlanConnectTask* task = new WlanConnectTask(this); this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task); } else { PostEventFIFO(new FSMEvent(USER_EVT_ATTEMPT)); } ShowFatalError(GetFurtherDetail()); SendNetStatusMsg(); } } break; case EVT_USER_WLAN_CONNECT_FINISHED: { evt->SetHandled(); uRet = evt->param1; m_dwWlanConnectTimes++; if(evt->param1 == 0) { const ErrorCodeEnum ec = (ErrorCodeEnum)evt->param2; if(ec == Error_NotExist) { SetHWStatus(MBD_WLAN_ENTRY_NO_FOUND); } else { SetHWStatus(MBD_WLAN_CONNECT_FAILED); } ShowFatalError(GetFurtherDetail()); SendNetStatusMsg(); if(m_dwWlanConnectTimes >= MAX_TRY_WLAN_CONNETC_TIMES) { LogError(Severity_High, Error_TimeOut, CombineErrorCode(MBD_WLAN_CONNECT_FAILED), CSimpleStringA::Format("连续%d次连接WLAN失败,请检查MIFI设备是否正常运行!", m_dwWlanConnectTimes) ); ScheduleTimer(TIMER_TRY_LINK_ID, MOBILEDIAL_WLAN_CONNECT_INTERVAL * 2); } else { ScheduleTimer(TIMER_TRY_LINK_ID, MOBILEDIAL_WLAN_CONNECT_INTERVAL); } } else { SetHWStatus(MBD_WLAN_CONNECTED); } } break; case EVT_USER_WIRELESS_STATE: //BroadcastCableChangedFSMEvent(evt); evt->SetHandled(); uRet = evt->param1; if(evt->param1 == 1) { SetHWStatus(MBD_WLAN_CONNECTED); } else { SetHWStatus(MBD_WLAN_CONNECT_FAILED); ScheduleTimer(TIMER_TRY_LINK_ID, MOBILEDIAL_WLAN_CONNECT_INTERVAL); } break; case USER_EVT_FAILURE: evt->SetHandled(); break; default: break; } return uRet; } void CMobileDialFSM::s8_on_entry() { LOG_FUNCTION(); MBBConfigUpdateTask* task = new MBBConfigUpdateTask(this); GetEntityBase()->GetFunction()->PostThreadPoolTask(task); } void CMobileDialFSM::s8_on_exit() { Recognized3GOr4G(); } unsigned int CMobileDialFSM::s8_on_event(FSMEvent* evt) { unsigned int uRet = 0; Dbg("s8_on_event %d, %d, %d", evt->iEvt, evt->param1, evt->param2); if(evt->iEvt == USER_EVT_CONFIG_DETECT_FINISHED) { evt->SetHandled(); if(evt->param1 == 1) { if(m_nAdvancedGen != ADVANCE_MBB) { InitHuaweiComponent(); m_nAdvancedGen = ADVANCE_MBB; CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->WriteConfigValueInt("init", "GenAdvanced", m_nAdvancedGen); SetHWStatus(MBD_WLAN_CONFIG_REBOOT); ShowFatalError(GetFurtherDetail()); SendNetStatusMsg(); ScheduleTimer(TIMER_CHECK_DEVICE_ID, DEV_CHANGED_TIMER_INTERVAL); } else { SetHWStatus(MBD_WLAN_DEVICE_PLUG_OFF); ShowFatalError(GetFurtherDetail()); SendNetStatusMsg(); ScheduleTimer(TIMER_CHECK_DEVICE_NOCHANGED_ID, DEV_CHANGED_TIMER_INTERVAL); } uRet = 1; //stop from backing to s0. } } else if(evt->iEvt == EVT_TIMER) { if(evt->param1 == TIMER_CHECK_DEVICE_ID || evt->param1 == TIMER_CHECK_DEVICE_NOCHANGED_ID) { evt->SetHandled(); if(!m_HwDeviceMnt->detect_devices()) { if(evt->param1 == TIMER_CHECK_DEVICE_ID) { Dbg("wait the selfchecker entity to kill it or manully."); m_ecSelfTest = Error_InvalidState; SetHWStatus(MBD_WLAN_CONFIG_WAIT_REBOOT); ShowFatalError(GetFurtherDetail()); SendNetStatusMsg(); } else { uRet = 1; } } else { if(evt->param1 == TIMER_CHECK_DEVICE_ID) { SetHWStatus(MBD_WLAN_CONFIG_REBOOT); ShowFatalError(GetFurtherDetail()); SendNetStatusMsg(); ScheduleTimer(TIMER_CHECK_DEVICE_ID, DEV_CHANGED_TIMER_INTERVAL); } else { SetHWStatus(MBD_WLAN_DEVICE_PLUG_OFF); ShowFatalError(GetFurtherDetail()); SendNetStatusMsg(); ScheduleTimer(TIMER_CHECK_DEVICE_NOCHANGED_ID, DEV_CHANGED_TIMER_INTERVAL); } } } } return uRet; } int CMobileDialFSM::EnumPhoneEntry() { DWORD dwCb = 0; DWORD dwRet = ERROR_SUCCESS; DWORD dwEntries = 0; LPRASENTRYNAME lpRasEntryName = NULL; // Call RasEnumEntries with lpRasEntryName = NULL. dwCb is returned with the required buffer size and // a return code of ERROR_BUFFER_TOO_SMALL dwRet = RasEnumEntries(NULL, NULL, lpRasEntryName, &dwCb, &dwEntries); if (dwRet == ERROR_BUFFER_TOO_SMALL) { // Allocate the memory needed for the array of RAS entry names. lpRasEntryName = (LPRASENTRYNAME) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb); if (lpRasEntryName == NULL){ Dbg("HeapAlloc failed when RasEnumEntries"); return -1; } // The first RASENTRYNAME structure in the array must contain the structure size lpRasEntryName[0].dwSize = sizeof(RASENTRYNAME); // Call RasEnumEntries to enumerate all RAS entry names dwRet = RasEnumEntries(NULL, NULL, lpRasEntryName, &dwCb, &dwEntries); // If successful, print the RAS entry names if (ERROR_SUCCESS == dwRet) { Dbg("The following RAS entry names were found:"); for (DWORD i = 0; i < dwEntries; i++) { if (m_csEntryName.GetLength() != 0 && _strnicmp(lpRasEntryName[i].szEntryName,m_csEntryName,m_csEntryName.GetLength()) == 0) { Dbg("Find specified entry: %s",(LPCTSTR)m_csEntryName); LPRASENTRY lpRasentry = NULL; LPBYTE lpDevInfo = NULL; DWORD dwEntrySz = 0, dwDevInfoSz = 0; dwRet = RasGetEntryProperties(NULL, lpRasEntryName[i].szEntryName, NULL, &dwEntrySz, NULL, &dwDevInfoSz); if(dwRet == ERROR_BUFFER_TOO_SMALL) { if(dwEntrySz != 0) lpRasentry = (LPRASENTRY)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwEntrySz); if(dwDevInfoSz != 0) lpDevInfo = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwDevInfoSz); } if(lpRasentry != NULL) { lpRasentry->dwSize = sizeof(RASENTRY); dwRet = RasGetEntryProperties(NULL, lpRasEntryName[i].szEntryName, lpRasentry, &dwEntrySz, lpDevInfo, &dwDevInfoSz); if(dwRet != 0) { Dbg("RasGetEntryProperties twice failed: %d", dwRet); } else { Dbg("DeviceName: %s, DeviceType: %s", lpRasentry->szDeviceName, lpRasentry->szDeviceType); CSimpleStringA csEntryGUID = GuidToString(lpRasentry->guidId); if(!csEntryGUID.IsNullOrEmpty()) { CSmartPointer spConfigRun; CSimpleStringA csValue; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); if(Error_Succeed != spConfigRun->ReadConfigValue(csEntryGUID, "Status", csValue) || csValue.GetLength() <= 0) { Dbg("Cannot found entry(%s) info from runtime file: (%s), set temporary", (LPCTSTR)csEntryGUID, (LPCTSTR)csValue); spConfigRun->WriteConfigValue(csEntryGUID, "Type", "RAS"); spConfigRun->WriteConfigValue(csEntryGUID, "Status", "Invalid-Temporary"); spConfigRun->WriteConfigValue(csEntryGUID, "EntryName", m_csEntryName); spConfigRun->WriteConfigValue("RAS", "EntryGUID", csEntryGUID); } } } } if(lpRasentry) { HeapFree(GetProcessHeap(), 0, lpRasentry); lpRasentry = NULL; } if(lpDevInfo) { HeapFree(GetProcessHeap(), 0, lpDevInfo); lpDevInfo = NULL; } //Deallocate memory for the connection buffer HeapFree(GetProcessHeap(), 0, lpRasEntryName); lpRasEntryName = NULL; return 0; } else { Dbg("EntryName[%d]: %s", i, lpRasEntryName[i].szEntryName); } } } //Deallocate memory for the connection buffer HeapFree(GetProcessHeap(), 0, lpRasEntryName); lpRasEntryName = NULL; return -2; } // There was either a problem with RAS or there are RAS entry names to enumerate if(dwEntries >= 1) { Dbg("The operation failed to acquire the buffer size."); } else { Dbg("There were no RAS entry names found."); return -2; } return -3; } int CMobileDialFSM::UpdateRasConnectState(bool bUpdateCmd) { LOG_FUNCTION(); DWORD dwCb = 0; DWORD dwRet = ERROR_SUCCESS; DWORD dwConnections = 0; LPRASCONN lpRasConn = NULL; if(bUpdateCmd) { int cnt = g_DongleInfos.GetCount(); for(int i=0; i 0 && !strBackup.IsNullOrEmpty()) { MBNProfileList& profiles = g_DongleInfos[i].profileList; for(int j=0; j 0) { lpRasConn = (LPRASCONN) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb); if (lpRasConn == NULL) { SetRasStatus(MBD_INTERNAL_ERROR); Dbg("HeapAlloc failed when RasEnumConnections"); return -1; } lpRasConn[0].dwSize = sizeof(RASCONN); int nRes = dwConnections; dwRet = RasEnumConnections(lpRasConn, &dwCb, &dwConnections); if (ERROR_SUCCESS == dwRet) { Dbg("The following RAS connections are currently active:"); for (DWORD i = 0; i < dwConnections; i++) { RASCONNSTATUS rasStatus; rasStatus.dwSize = sizeof(RASCONNSTATUS); dwRet = RasGetConnectStatus(lpRasConn[i].hrasconn, &rasStatus); const RASCONNSTATE& cntState = rasStatus.rasconnstate; if(dwRet == ERROR_SUCCESS){ Dbg("%s - rasconnstate: %d", lpRasConn[i].szEntryName, rasStatus.rasconnstate); CSimpleStringA csEntryGUID = GuidToString(lpRasConn[i].guidEntry); SetGlobalConnectState(csEntryGUID, cntState); if(cntState == RASCS_Connected) { Dbg("Reset the ras handle to bcz it has connected"); g_hrasconn = lpRasConn[i].hrasconn; SetRasStatusWithConnStatus(cntState); //if(g_hrasconn != lpRasConn[i].hrasconn) if(m_csCurEntryGUID.Compare(csEntryGUID)) { m_csCurEntryGUID = CSimpleStringA((LPCTSTR)csEntryGUID); CSmartPointer spConfigRun; CSimpleStringA csValue; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); if(Error_Succeed != spConfigRun->ReadConfigValue(csEntryGUID, "Status", csValue) || csValue.GetLength() <= 0 || csValue.IsStartWith("Invalid")) { Dbg("Cannot found entry info from runtime file or invalid: %s", (LPCTSTR)csValue); } else { Dbg("Read %s from run-config", (LPCTSTR)csEntryGUID); CSimpleStringA csTest; spConfigRun->ReadConfigValue("RAS", "EntryGUID", csTest); Dbg("test: %s", (LPCTSTR)csTest); spConfigRun->ReadConfigValue(csEntryGUID, "PhoneNum", m_csPhoneNum); spConfigRun->ReadConfigValue(csEntryGUID, "EntryName", m_csEntryName); spConfigRun->ReadConfigValue(csEntryGUID, "UserName", m_csUserName); #ifdef USING_ENCRYPT spConfigRun->ReadConfigValue(csEntryGUID, "Password", csValue); m_csPassword = DecryptString(csValue); #else spConfigRun->ReadConfigValue(csEntryGUID, "Password", m_csPassword); #endif spConfigRun->ReadConfigValue(csEntryGUID, "APN", m_csVpnName); } } } else if(g_hrasconn == lpRasConn[i].hrasconn) { SetRasStatusWithConnStatus(cntState); } }else{ Dbg("%s - RasGetConnectStatus failed: %u", lpRasConn[i].szEntryName, dwRet); } } } else { Dbg("RasEnumConnections twice failed %u", dwRet); SetRasStatus(MBD_INTERNAL_ERROR); nRes = -1; } //Deallocate memory for the connection buffer HeapFree(GetProcessHeap(), 0, lpRasConn); lpRasConn = NULL; return nRes; } // There was either a problem with RAS or there are no connections to enumerate if(dwConnections >= 1) { Dbg("The operation failed to acquire the buffer size."); SetRasStatus(MBD_INTERNAL_ERROR); return -1; } Dbg("There are no active RAS connections."); SetRasStatus(MBD_ACTIVATION_DISCONNECTED); return 0; } int CMobileDialFSM::DealConnctionActivity(LPCTSTR lpcszEntryName) { LOG_FUNCTION(); DWORD dwCb = 0; DWORD dwRet = ERROR_SUCCESS; DWORD dwConnections = 0; LPRASCONN lpRasConn = NULL; dwRet = RasEnumConnections(lpRasConn, &dwCb, &dwConnections); if (dwRet == ERROR_BUFFER_TOO_SMALL && dwConnections > 0) { lpRasConn = (LPRASCONN) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb); if (lpRasConn == NULL) { Dbg("HeapAlloc failed when RasEnumConnections"); return -1; } lpRasConn[0].dwSize = sizeof(RASCONN); int nRes = 0; dwRet = RasEnumConnections(lpRasConn, &dwCb, &dwConnections); if (ERROR_SUCCESS == dwRet) { Dbg("The following RAS connections are currently active: %d", dwConnections); for (DWORD i = 0; i < dwConnections; i++) { RASCONNSTATUS rasStatus; rasStatus.dwSize = sizeof(RASCONNSTATUS); dwRet = RasGetConnectStatus(lpRasConn[i].hrasconn, &rasStatus); const RASCONNSTATE& cntState = rasStatus.rasconnstate; if(dwRet == ERROR_SUCCESS){ Dbg("%s - rasconnstate: %d", lpRasConn[i].szEntryName, rasStatus.rasconnstate); if(lpcszEntryName != NULL && strlen(lpcszEntryName) > 0 && !strcmp(lpRasConn[i].szEntryName, lpcszEntryName)) { CSimpleStringA csEntryGUID = GuidToString(lpRasConn[i].guidEntry); /*if(cntState != RASCS_Connected)*/ { Dbg("Close the ras handle"); DWORD dwRet = 0; dwRet = RasHangUp(lpRasConn[i].hrasconn); Dbg("RasHangUp returned %d", dwRet); if(dwRet == ERROR_SUCCESS) { RASCONNSTATUS connStatus; connStatus.dwSize = sizeof(RASCONNSTATUS); Dbg("TickCount allocated 3 seconds after RasHangUp..."); //Reduce timeout tick in case occuring //UnLoading-Entity -Josephus@2017627 16:54:10 DWORD tcLast = GetTickCount() + 3 * 1100; while((( dwRet = RasGetConnectStatus(lpRasConn[i].hrasconn, &connStatus)) != ERROR_INVALID_HANDLE) && (tcLast > GetTickCount())) { Sleep(0); } bool fResult = (dwRet == ERROR_INVALID_HANDLE); Dbg("Cycle is done %snormally", fResult ? "" : "ab"); } } nRes = 1; break; } }else{ Dbg("%s - RasGetConnectStatus failed: %u", lpRasConn[i].szEntryName, dwRet); } } } else { Dbg("RasEnumConnections twice failed %u", dwRet); nRes = -1; } //Deallocate memory for the connection buffer HeapFree(GetProcessHeap(), 0, lpRasConn); lpRasConn = NULL; return nRes; } // There was either a problem with RAS or there are no connections to enumerate if(dwConnections >= 1) { Dbg("The operation failed to acquire the buffer size."); return -1; } Dbg("There are no active RAS connections."); return 0; } int CMobileDialFSM::CreatePhoneEntry() { return CreatePhoneEntryEx("", NULL, FALSE); } int CMobileDialFSM::CreatePhoneEntryEx(LPCTSTR lpcszDevName, const AccessKeyInfo * pNewInfo, bool fApplyNow) { DWORD dwCb = 0; DWORD dwRet = ERROR_SUCCESS; DWORD dwDevices = 0; BOOL bOrigin = FALSE; LPRASDEVINFO lpRasDevInfo = NULL; RASDEVINFO specialRasDevInfo = {0}; if(strlen(lpcszDevName) == 0 && pNewInfo == NULL) { bOrigin = TRUE; } specialRasDevInfo.dwSize = 0; strcpy_s(specialRasDevInfo.szDeviceName, lpcszDevName); strcpy_s(specialRasDevInfo.szDeviceType, RASDT_Modem); LPRASENTRY lpRasExistedEntry = NULL; LPBYTE lpRasExistedDevInfo = NULL; // Call RasEnumDevices with lpRasDevInfo = NULL. dwCb is returned with the required buffer size and // a return code of ERROR_BUFFER_TOO_SMALL dwRet = RasEnumDevices(lpRasDevInfo, &dwCb, &dwDevices); if (dwRet == ERROR_BUFFER_TOO_SMALL) { // Allocate the memory needed for the array of RAS structure(s). lpRasDevInfo = (LPRASDEVINFO) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb); if (lpRasDevInfo == NULL) { Dbg("HeapAlloc for RasEnumDevices failed"); if(!bOrigin) m_csErrMsg = "程序异常-申请内存失败!"; return -1; } else { // The first RASDEVINFO structure in the array must contain the structure size lpRasDevInfo[0].dwSize = sizeof(RASDEVINFO); // Call RasEnumDevices to enumerate RAS devices dwRet = RasEnumDevices(lpRasDevInfo, &dwCb, &dwDevices); int bFound = FALSE; // If successful, print the names of the RAS devices if (ERROR_SUCCESS == dwRet) { Dbg("The following RAS devices were found:"); for (DWORD i = 0; i < dwDevices; i++) { Dbg("%s <%s>",lpRasDevInfo[i].szDeviceName,lpRasDevInfo[i].szDeviceType); if(specialRasDevInfo.dwSize == 0) { if(!bOrigin) { if(!_strnicmp(lpRasDevInfo[i].szDeviceName, lpcszDevName, strlen(lpcszDevName))) { specialRasDevInfo.dwSize = strlen(lpcszDevName) + strlen(lpRasDevInfo[i].szDeviceType); strcpy_s(specialRasDevInfo.szDeviceName, lpRasDevInfo[i].szDeviceName); strcpy_s(specialRasDevInfo.szDeviceType, lpRasDevInfo[i].szDeviceType); Dbg("found it 1: %s::%s", specialRasDevInfo.szDeviceName, specialRasDevInfo.szDeviceType); bFound = TRUE; break; } } else { for(int j=0; jdwSize = sizeof(RASENTRY); if((dwRet = RasGetEntryProperties(NULL, "", lpDefaultRasEntry, &dwDefaultEntrySize, lpDefaultDeviceInfo, &dwDefaultInforSize)) != 0) { Dbg("RasGetEntryProperties twice failed"); if(lpDefaultRasEntry) { HeapFree(GetProcessHeap(), 0, lpDefaultRasEntry); lpDefaultRasEntry = NULL; } if(lpDefaultDeviceInfo) { HeapFree(GetProcessHeap(), 0, lpDefaultDeviceInfo); lpDefaultDeviceInfo = NULL; } if(!bOrigin) m_csErrMsg = "RasGetEntryProperties error"; return -1; } } else { Dbg("RasGetEntryProperties failed : %d", dwRet); if(!bOrigin) m_csErrMsg = "RasGetEntryProperties error"; return -1; } } else { Dbg("RasGetEntryProperties improper : %d", dwRet); if(!bOrigin) m_csErrMsg = "RasGetEntryProperties improper"; return -1; } } RASENTRY rasEntry; ZeroMemory(&rasEntry, sizeof(RASENTRY)); /* rasEntry.dwSize = sizeof(RASENTRY); rasEntry.dwCountryCode = 86; rasEntry.dwCountryID = 86; rasEntry.dwDialExtraPercent = 75; rasEntry.dwDialExtraSampleSeconds = 120; rasEntry.dwDialMode = RASEDM_DialAll; rasEntry.dwEncryptionType = 3; rasEntry.dwfNetProtocols = RASNP_Ip; rasEntry.dwfOptions = RASEO_RequirePAP | RASEO_RequireMsCHAP2; if((RASEO_RequireMsCHAP2 | RASEO_RequireMsCHAP | RASEO_RequireCHAP | RASEO_PreviewDomain | RASEO_PreviewUserPw | RASEO2_DisableClassBasedStaticRoute | RASEO2_IPv6ExplicitMetric | RASEO2_IPv4ExplicitMetric | RASEO2_SharePhoneNumbers | RASEO2_ReconnectIfDropped | RASEO2_UsePreSharedKey) == 1024262928) { Dbg("the same options mask."); } rasEntry.dwfOptions2 = 367; rasEntry.dwFramingProtocol = RASFP_Ppp; rasEntry.dwHangUpExtraPercent = 10; rasEntry.dwHangUpExtraSampleSeconds = 120; rasEntry.dwRedialCount = 3; rasEntry.dwRedialPause = 60; rasEntry.dwType = RASET_Phone; //指定电话薄条目类型,这里指明是电话线 rasEntry.dwVpnStrategy = VS_Default; */ assert(lpDefaultRasEntry != NULL); memcpy_s(&rasEntry, sizeof(RASENTRY), lpDefaultRasEntry, sizeof(RASENTRY)); rasEntry.dwSize = sizeof(RASENTRY); DWORD dwTempMask = ~(RASEO_RequireCHAP | RASEO_RequireMsCHAP2 | RASEO_RequirePAP); Dbg("test: 0x%08X, 0x%08X", rasEntry.dwfOptions, dwTempMask); if(bOrigin) { rasEntry.dwfOptions &= (~RASEO_RequireCHAP); } else { rasEntry.dwfOptions &= dwTempMask; if((pNewInfo->usAPType & AUPR_PAP) == AUPR_PAP) { rasEntry.dwfOptions |= RASEO_RequirePAP; } if((pNewInfo->usAPType & AUPR_CHAP) == AUPR_CHAP) { rasEntry.dwfOptions |= RASEO_RequireCHAP; } if((pNewInfo->usAPType & AUPR_MSV2) == AUPR_MSV2) { rasEntry.dwfOptions |= RASEO_RequireMsCHAP2; } } Dbg("Use default entry !!! 0X%08X", rasEntry.dwfOptions); strcpy_s(rasEntry.szDeviceName, specialRasDevInfo.szDeviceName); strcpy_s(rasEntry.szDeviceType, specialRasDevInfo.szDeviceType); if(bOrigin) { strcpy_s(rasEntry.szLocalPhoneNumber, (LPCTSTR)m_csPhoneNum); } else { strcpy_s(rasEntry.szLocalPhoneNumber, (LPCTSTR)pNewInfo->strPhoneNum); } if(lpDefaultRasEntry) { HeapFree(GetProcessHeap(), 0, lpDefaultRasEntry); lpDefaultRasEntry = NULL; } if(lpDefaultDeviceInfo) { HeapFree(GetProcessHeap(), 0, lpDefaultDeviceInfo); lpDefaultDeviceInfo = NULL; } DWORD dwValid = 0; if(bOrigin) { dwValid = RasValidateEntryName(NULL, m_csEntryName); if(dwValid != ERROR_SUCCESS && dwValid != ERROR_ALREADY_EXISTS){ if(dwValid == ERROR_INVALID_NAME){ Dbg("EntryName(%s) is invalid format", (LPCTSTR)m_csEntryName); }else{ Dbg("validate entry name (%s) failed: %d", (LPCTSTR)m_csEntryName, dwValid); } return -1; } } else { dwValid = RasValidateEntryName(NULL, pNewInfo->strProfileDesc); if(dwValid != ERROR_SUCCESS && dwValid != ERROR_ALREADY_EXISTS){ if(dwValid == ERROR_INVALID_NAME){ Dbg("EntryName(%s) is invalid format", (LPCTSTR)pNewInfo->strProfileDesc); }else{ Dbg("validate entry name (%s) failed: %d", (LPCTSTR)pNewInfo->strProfileDesc, dwValid); } m_csErrMsg = CSimpleStringA::Format("连接名称[%s]校验无效:0x%X", (LPCTSTR)pNewInfo->strProfileDesc, dwValid); return -1; } } if(dwValid == ERROR_ALREADY_EXISTS) { if(!bOrigin) { m_csErrMsg = CSimpleStringA::Format("该连接名称[%s]已存在!", (LPCTSTR)pNewInfo->strProfileDesc); return -1; } Dbg("EntryName(%s) is already existed", (LPCTSTR)m_csEntryName); } DWORD dwSetEntry = ERROR_SUCCESS; LPCTSTR lpcszTmpVpn = NULL; if(bOrigin) { lpcszTmpVpn = (LPCTSTR)m_csVpnName; } else { lpcszTmpVpn = (LPCTSTR)pNewInfo->strAccessString; } //TODO APN if(lpcszTmpVpn != NULL && strlen(lpcszTmpVpn) > 0) { BYTE lpb[436]; size_t szLen = strlen(lpcszTmpVpn); CSimpleStringW lpwczTmpVpn = CSimpleStringA2W(CSimpleStringA(lpcszTmpVpn)); int szWlen = wcslen((LPCWSTR)lpwczTmpVpn); DWORD dwSizeOflpb = sizeof(lpb); memset(lpb, 0, dwSizeOflpb); lpb[0]=180, lpb[1]=1, lpb[4]=180,lpb[5]=1; lpb[8]=180, lpb[9]=1, lpb[12]=1, lpb[16]=15; lpb[20]=1, lpb[24]=2, lpb[76]=1, lpb[80]=2, lpb[84]=2; for(int i=0,stip=0; istrProfileDesc, &rasEntry, sizeof(rasEntry) , lpb, dwSizeOflpb); if (dwSetEntry == ERROR_SUCCESS){ Dbg("set entry(%s) with lpb successfully.", (LPCTSTR)(bOrigin ? m_csEntryName : pNewInfo->strProfileDesc)); } else { Dbg("set entry(%s) with lpb(%s) failed: %d", (LPCTSTR)(bOrigin ? m_csEntryName : pNewInfo->strProfileDesc), lpcszTmpVpn, dwSetEntry); } } else { //lpbDeviceInfo 参数是一个指向缓冲区的指针,该缓冲区中包含TAPI设备的配置信息。 //在Windows 2000和Windows NT平台上,没有使用这个参数,因此,应该设为NULL。 dwSetEntry = RasSetEntryProperties(NULL, bOrigin ? m_csEntryName : pNewInfo->strProfileDesc, &rasEntry, sizeof(rasEntry), NULL, 0); if(dwSetEntry == ERROR_SUCCESS) { Dbg("set entry(%s) successfully.", (LPCTSTR)(bOrigin ? m_csEntryName : pNewInfo->strProfileDesc)); } else { Dbg("set entry(%s) failed: %d", (LPCTSTR)(bOrigin ? m_csEntryName : pNewInfo->strProfileDesc), dwSetEntry); } } if (dwSetEntry == ERROR_SUCCESS){ do { if((dwRet = RasGetEntryProperties(NULL, bOrigin ? m_csEntryName : pNewInfo->strProfileDesc, NULL, &dwDefaultEntrySize, NULL, &dwDefaultInforSize)) != 0) { if(dwRet == ERROR_BUFFER_TOO_SMALL) { lpDefaultRasEntry = (LPRASENTRY) HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, dwDefaultEntrySize); if(dwDefaultInforSize != 0) { lpDefaultDeviceInfo = (LPBYTE) HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, dwDefaultInforSize); Dbg("dwDefaultInforSize2: %u", dwDefaultInforSize); } lpDefaultRasEntry->dwSize = sizeof(RASENTRY); if((dwRet = RasGetEntryProperties(NULL, bOrigin ? m_csEntryName : pNewInfo->strProfileDesc, lpDefaultRasEntry, &dwDefaultEntrySize, lpDefaultDeviceInfo, &dwDefaultInforSize)) != 0) { Dbg("RasGetEntryProperties2 twice failed"); break; } CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); CSimpleStringA csEntryGUID = GuidToString(lpDefaultRasEntry->guidId); spConfigRun->WriteConfigValue(csEntryGUID, "Type", "RAS"); spConfigRun->WriteConfigValue(csEntryGUID, "Status", "Create"); if(!bOrigin) { spConfigRun->WriteConfigValue(csEntryGUID, "EntryName", pNewInfo->strProfileDesc); spConfigRun->WriteConfigValue(csEntryGUID, "PhoneNum", pNewInfo->strPhoneNum); spConfigRun->WriteConfigValue(csEntryGUID, "UserName", pNewInfo->strUserName); #ifdef USING_ENCRYPT CSimpleStringA csEValue = EncryptString(pNewInfo->strPassword); spConfigRun->WriteConfigValue(csEntryGUID, "Password", csEValue); #else spConfigRun->WriteConfigValue(csEntryGUID, "Password", pNewInfo->strPassword); #endif spConfigRun->WriteConfigValue(csEntryGUID, "APN", pNewInfo->strAccessString); } else { spConfigRun->WriteConfigValue(csEntryGUID, "EntryName", m_csEntryName); spConfigRun->WriteConfigValue(csEntryGUID, "PhoneNum", m_csPhoneNum); spConfigRun->WriteConfigValue(csEntryGUID, "UserName", m_csUserName); #ifdef USING_ENCRYPT CSimpleStringA csEValue = EncryptString(m_csPassword); spConfigRun->WriteConfigValue(csEntryGUID, "Password", csEValue); #else spConfigRun->WriteConfigValue(csEntryGUID, "Password", m_csPassword); #endif spConfigRun->WriteConfigValue(csEntryGUID, "APN", m_csVpnName); } } else { Dbg("RasGetEntryProperties2 failed : %d", dwRet); break; } } else { Dbg("RasGetEntryProperties2 improper : %d", dwRet); break; } } while (FALSE); if(lpDefaultRasEntry) { HeapFree(GetProcessHeap(), 0, lpDefaultRasEntry); lpDefaultRasEntry = NULL; } if(lpDefaultDeviceInfo) { HeapFree(GetProcessHeap(), 0, lpDefaultDeviceInfo); lpDefaultDeviceInfo = NULL; } return 0; } return -1; } ErrorCodeEnum CMobileDialFSM::UpdateEntryInfo(LPCTSTR lpcszEntryGUID, const AccessKeyInfo& newInfo, bool fApplyNow) { ErrorCodeEnum rc = Error_Unexpect; CSmartPointer spConfigRun; rc = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); CSimpleStringA csValue; CSimpleStringA csEntryName(true); bool fRuncfgMark = true; bool fReCreate = false; if(Error_Succeed != spConfigRun->ReadConfigValue(lpcszEntryGUID, "Status", csValue) || csValue.GetLength() <= 0 || csValue.IsStartWith("Invalid")) { int cnt = m_rasEntries.GetCount(); for(int i=0; iReadConfigValue(lpcszEntryGUID, "EntryName", csEntryName); } Dbg("UpdateEntryInfo(%s),mark(%d)", lpcszEntryGUID, fRuncfgMark); if(csEntryName.GetLength() <= 0) { m_csErrMsg = "获取电话簿名称失败"; return Error_NotExist; } DWORD dwValide = RasValidateEntryName(NULL, csEntryName); if(dwValide == ERROR_ALREADY_EXISTS) { Dbg("The entry is comfirmed exist, so it seems normal ??"); Dbg("DealConnctionActivity returned: %d", DealConnctionActivity(csEntryName)); dwValide = RasDeleteEntry(NULL, csEntryName); if(dwValide == ERROR_SUCCESS) { Dbg("Delete the previous one succ."); fReCreate = true; } else { Dbg("Delete entry(%s) failed: %d", (LPCTSTR)csEntryName, dwValide); m_csErrMsg = CSimpleStringA::Format("更新前清理电话簿失败 : %d", dwValide); return Error_Unexpect; ERROR_INVALID_NAME; } } else { Dbg("Valid entry name return: %d", dwValide); m_csErrMsg = "校验电话簿名称失败"; return Error_Unexpect; } Dbg("Update EntryName: %s", (LPCTSTR)csEntryName); LPRASENTRY lpRasentry = NULL; LPBYTE lpDevInfo = NULL; DWORD dwEntrySz = 0, dwDevInfoSz = 0; DWORD dwRet = RasGetEntryProperties(NULL, /*(LPCTSTR)csEntryName*/"", NULL, &dwEntrySz, NULL, &dwDevInfoSz); if(dwRet == ERROR_BUFFER_TOO_SMALL) { if(dwEntrySz != 0) { lpRasentry = (LPRASENTRY)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwEntrySz); if(dwDevInfoSz != 0) lpDevInfo = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwDevInfoSz); } if(lpRasentry == NULL) { m_csErrMsg = "分配内存失败"; return Error_Resource; } lpRasentry->dwSize = sizeof(RASENTRY); dwRet = RasGetEntryProperties(NULL, /*(LPCTSTR)csEntryName*/"", lpRasentry, &dwEntrySz, lpDevInfo, &dwDevInfoSz); if(dwRet != ERROR_SUCCESS) { if(lpRasentry) { HeapFree(GetProcessHeap(), 0, lpRasentry); lpRasentry = NULL; } if(lpDevInfo) { HeapFree(GetProcessHeap(), 0, lpDevInfo); lpDevInfo = NULL; } m_csErrMsg = CSimpleStringA::Format("RasGetEntryProperties failed: %d", dwRet); return Error_Unexpect; } RASENTRY rasEntry; ZeroMemory(&rasEntry, sizeof(RASENTRY)); memcpy_s(&rasEntry, sizeof(RASENTRY), lpRasentry, sizeof(RASENTRY)); rasEntry.dwSize = sizeof(RASENTRY); DWORD dwTempMask = ~(RASEO_RequireCHAP | RASEO_RequireMsCHAP2 | RASEO_RequirePAP); rasEntry.dwfOptions &= dwTempMask; if((newInfo.usAPType & AUPR_PAP) == AUPR_PAP) { rasEntry.dwfOptions |= RASEO_RequirePAP; Dbg("Add: AUPR_PAP"); } if((newInfo.usAPType & AUPR_CHAP) == AUPR_CHAP) { rasEntry.dwfOptions |= RASEO_RequireCHAP; Dbg("Add: AUPR_CHAP"); } if((newInfo.usAPType & AUPR_MSV2) == AUPR_MSV2) { rasEntry.dwfOptions |= RASEO_RequireMsCHAP2; Dbg("Add: AUPR_MSV2"); } strcpy_s(rasEntry.szLocalPhoneNumber, (LPCTSTR)newInfo.strPhoneNum); if(lpRasentry) { HeapFree(GetProcessHeap(), 0, lpRasentry); lpRasentry = NULL; } if(lpDevInfo) { HeapFree(GetProcessHeap(), 0, lpDevInfo); lpDevInfo = NULL; } //TODO: AccessString BYTE lpb[436]; DWORD dwSizeOflpb = 0; bool fHaveApn = false; if(!newInfo.strAccessString.IsNullOrEmpty()) { fHaveApn = true; size_t szLen = strlen(newInfo.strAccessString); CSimpleStringW lpwczTmpVpn = CSimpleStringA2W(newInfo.strAccessString); int szWlen = wcslen((LPCWSTR)lpwczTmpVpn); dwSizeOflpb = sizeof(lpb); memset(lpb, 0, dwSizeOflpb); lpb[0]=180, lpb[1]=1, lpb[4]=180,lpb[5]=1; lpb[8]=180, lpb[9]=1, lpb[12]=1, lpb[16]=15; lpb[20]=1, lpb[24]=2, lpb[76]=1, lpb[80]=2, lpb[84]=2; for(int i=0,stip=0; idwSize = sizeof(RASENTRY); if((dwRet = RasGetEntryProperties(NULL, (LPCTSTR)csEntryName, lpRasentry, &dwEntrySz, lpDevInfo, &dwDevInfoSz)) != 0) { Dbg("RasGetEntryProperties twice failed"); break; } csUpdatedGUID = GuidToString(lpRasentry->guidId); if(!csUpdatedGUID.IsNullOrEmpty()) { fAborted = false; } } else { Dbg("RasGetEntryProperties3 failed : %d", dwRet); break; } } else { Dbg("RasGetEntryProperties3 improper : %d", dwRet); break; } } while (FALSE); } else { csUpdatedGUID = lpcszEntryGUID; } if(!fAborted) { CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->WriteConfigValue(csUpdatedGUID, "Status", "Update"); if(!fRuncfgMark || fReCreate) { spConfigRun->WriteConfigValue(csUpdatedGUID, "Type", "RAS"); spConfigRun->WriteConfigValue(csUpdatedGUID, "EntryName", newInfo.strProfileDesc); if(fReCreate) { spConfigRun->WriteConfigValue(lpcszEntryGUID, "Status", "Invalid-Update-Delete"); spConfigRun->WriteConfigValue(lpcszEntryGUID, "EntryName", ""); spConfigRun->WriteConfigValue(lpcszEntryGUID, "PhoneNum", ""); spConfigRun->WriteConfigValue(lpcszEntryGUID, "UserName", ""); spConfigRun->WriteConfigValue(lpcszEntryGUID, "Password", ""); spConfigRun->WriteConfigValue(lpcszEntryGUID, "APN", ""); Sleep(800); } } spConfigRun->WriteConfigValue(csUpdatedGUID, "PhoneNum", newInfo.strPhoneNum); spConfigRun->WriteConfigValue(csUpdatedGUID, "UserName", newInfo.strUserName); #ifdef USING_ENCRYPT CSimpleStringA csEValue = EncryptString(newInfo.strPassword); spConfigRun->WriteConfigValue(csUpdatedGUID, "Password", csEValue); #else spConfigRun->WriteConfigValue(csUpdatedGUID, "Password", newInfo.strPassword); #endif spConfigRun->WriteConfigValue(csUpdatedGUID, "APN", newInfo.strAccessString); } if(lpRasentry) { HeapFree(GetProcessHeap(), 0, lpRasentry); lpRasentry = NULL; } if(lpDevInfo) { HeapFree(GetProcessHeap(), 0, lpDevInfo); lpDevInfo = NULL; } m_csErrMsg = ""; return fAborted ? Error_Unexpect : Error_Succeed; }else { m_csErrMsg = CSimpleStringA::Format("RasGetEntryProperties failed: %d", dwRet); return Error_Unexpect; } } BOOL CMobileDialFSM::SetGlobalConnectState(LPCTSTR lpcszEntryGUID, const RASCONNSTATE state) { int cnt = g_DongleInfos.GetCount(); int aim = -1; for(int i=0; i 0) { MBNProfileList& profiles = g_DongleInfos[i].profileList; for(int j=0; j 0) { if(!g_DongleInfos[aim].subInfo.strProfileName.Compare(lpcszEntryGUID)) { //TODO: more various situation? g_DongleInfos[aim].subInfo.mbnCntState = MBN_ACTIVATION_STATE_DEACTIVATED; g_DongleInfos[aim].subInfo.strProfileName = ""; g_DongleInfos[aim].state = MBD_ACTIVATION_DISCONNECTED; } } } return TRUE; } int CMobileDialFSM::Dial3GConnect() { LOG_FUNCTION(); m_34GReserved = 3; if(m_34GDialSuc == 3) { m_34GDialSuc = 0; } if (EnumPhoneEntry() != 0) { Dbg("no sepecified entry(%s), begin to create it...", (LPCTSTR)m_csEntryName); if(CreatePhoneEntry() != 0) { Dbg("Create phone entry failed."); SetRasStatus(MBD_CREATE_ENTRY_FAILED); return 0; }else{ Dbg("Create phone entry suc."); } } RASDIALPARAMS Rasparam; Rasparam.dwSize=sizeof(RASDIALPARAMS); strcpy_s(Rasparam.szPhoneNumber,m_csPhoneNum); strcpy_s(Rasparam.szEntryName,m_csEntryName); strcpy_s(Rasparam.szUserName,m_csUserName); strcpy_s(Rasparam.szPassword,m_csPassword); strcpy_s(Rasparam.szDomain, ""); if(g_hrasconn != NULL) { Dbg("g_hrasconn has value !"); RasHangUpSuffix(); } DWORD dwDial = RasDial(NULL, NULL, &Rasparam, 0, /*&CustomRasDialFunc*/NULL, &g_hrasconn); if (dwDial == ERROR_SUCCESS) { Dbg("3g condition, ras dial successfully "); SetRasStatus(MBD_ACTIVATION_CONNECTING); { CSmartPointer spConfigRun; CSimpleStringA csValue; CSimpleStringA csEntryGUID; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); if(Error_Succeed == spConfigRun->ReadConfigValue("RAS", "EntryGUID", csEntryGUID) && !csEntryGUID.IsNullOrEmpty()) { Dbg("Update original dial param."); if(Error_Succeed == spConfigRun->ReadConfigValue(csEntryGUID, "Status", csValue) && !csValue.Compare("Invalid-Temporary")) { spConfigRun->WriteConfigValue(csEntryGUID, "Type", "RAS"); spConfigRun->WriteConfigValue(csEntryGUID, "EntryName", m_csEntryName); spConfigRun->WriteConfigValue(csEntryGUID, "PhoneNum", m_csPhoneNum); spConfigRun->WriteConfigValue(csEntryGUID, "UserName", m_csUserName); #ifdef USING_ENCRYPT CSimpleStringA csEValue = EncryptString(m_csPassword); spConfigRun->WriteConfigValue(csEntryGUID, "Password", csEValue); #else spConfigRun->WriteConfigValue(csEntryGUID, "Password", m_csPassword); #endif spConfigRun->WriteConfigValue(csEntryGUID, "APN", m_csVpnName); spConfigRun->WriteConfigValue(csEntryGUID, "Status", "Init"); spConfigRun->WriteConfigValue("RAS", "EntryGUID", ""); } } } m_34GDialSuc = 3; return 1; } //hardly useful. //Condition1: replaced by disconnect from mbn. //Condition2: repalced by error_socket or timeout even invalid connect from fsm. SetCurState(MBD_CONNECTION_FAILURE); _FormatRasError(dwDial); if(g_hrasconn != NULL) { RasHangUpSuffix(); } SetRasStatus(MBD_CONNECTION_FAILURE); return 0; } int CMobileDialFSM::Dial3GConnectEx(LPCTSTR lpcszDevName, LPCTSTR lpcszEntryGUID) { LOG_FUNCTION(); if(GetCurState() == MBD_ACTIVATION_CONNECTED) { assert(FALSE && "不应该处于已连接的状态"); SetRasStatus(MBD_UNKNOWN); return 0; } m_34GReserved = 3; if(m_34GDialSuc == 3) { m_34GDialSuc = 0; } CSmartPointer spConfigRun; ErrorCodeEnum rc = Error_NoDefine; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); CSimpleStringA csValue; CSimpleStringA csPhoneNum; CSimpleStringA csEntryName; CSimpleStringA csUserName; CSimpleStringA csPassword; CSimpleStringA csVpn; if(Error_Succeed == spConfigRun->ReadConfigValue(lpcszEntryGUID, "Status", csValue) && csValue.GetLength() > 0) { if(csValue.IsStartWith("Invalid")) { Dbg("the runcfg record for %s is invalid : %s", lpcszEntryGUID, (LPCTSTR)csValue); m_csErrMsg = CSimpleStringA::Format("运行时配置信息无效:%s", (LPCTSTR)csValue); return -1; } spConfigRun->ReadConfigValue(lpcszEntryGUID, "EntryName", csEntryName); spConfigRun->ReadConfigValue(lpcszEntryGUID, "PhoneNum", csPhoneNum); spConfigRun->ReadConfigValue(lpcszEntryGUID, "UserName", csUserName); #ifdef USING_ENCRYPT spConfigRun->ReadConfigValue(lpcszEntryGUID, "Password", csValue); csPassword = DecryptString(csValue); #else spConfigRun->ReadConfigValue(lpcszEntryGUID, "Password", csPassword); #endif spConfigRun->ReadConfigValue(lpcszEntryGUID, "APN", csVpn); }else { Dbg("runcfg is not exist ras record for %s", lpcszEntryGUID); m_csErrMsg = "在运行时配置信息中未找到拨号参数"; SetRasStatus(MBD_RUN_ENTRY_NOTFOUND); return -1; } RASDIALPARAMS Rasparam; memset(&Rasparam, 0, sizeof(RASDIALPARAMS)); Rasparam.dwSize=sizeof(RASDIALPARAMS); strcpy_s(Rasparam.szPhoneNumber, csPhoneNum); strcpy_s(Rasparam.szEntryName, csEntryName); strcpy_s(Rasparam.szUserName, csUserName); strcpy_s(Rasparam.szPassword, csPassword); strcpy_s(Rasparam.szDomain, ""); if(g_hrasconn != NULL) { RasHangUpSuffix(); } bool bAsyn = !!(m_hRasListenThread != NULL); if(bAsyn) { // LogEvent(Severity_Low, Error_NoDefine, "Cancel the Ras asy dial!"); // bAsyn = false; } DWORD dwDial = RasDial(NULL, NULL, &Rasparam, 0, bAsyn ? &CustomRasDialFunc : NULL, &g_hrasconn); if (dwDial == ERROR_SUCCESS) { Dbg("3g condition, ras dial successfully bAsyn:%d", bAsyn); if(m_recentInfo.usDialType == CNT_INVALID || (m_recentInfo.strDongle.Compare(lpcszDevName) || m_recentInfo.strProfile.Compare(lpcszEntryGUID) )) { Dbg("Store the new dial param."); m_34GDialSuc = 3; m_recentInfo.usDialType = CNT_RAS; m_recentInfo.strDongle = lpcszDevName; m_recentInfo.strProfile = lpcszEntryGUID; CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->WriteConfigValue("Recent", "Type", "RAS"); spConfigRun->WriteConfigValue("Recent", "Dongle", m_recentInfo.strDongle); spConfigRun->WriteConfigValue("Recent", "Profile", m_recentInfo.strProfile); spConfigRun->WriteConfigValueInt("Recent", "Manual", 0); spConfigRun->WriteConfigValueHexInt("Recent", "RequestID", (ULONG)g_hrasconn); } else if(m_recentInfo.usDialType == CNT_RAS) { m_recentInfo.ulRequestID = (ULONG)g_hrasconn; CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->WriteConfigValueHexInt("Recent", "RequestID", (ULONG)g_hrasconn); } SetRasStatus(MBD_ACTIVATION_CONNECTING); m_34GDialSuc = 3; return 1; } _FormatRasError(dwDial); if(g_hrasconn != NULL) { RasHangUpSuffix(); } SetRasStatus(MBD_CONNECTION_FAILURE); return 0; } int CMobileDialFSM::Dial4GConnect() { m_34GReserved = 4; if(m_pMbn->Connect()) { Dbg("4g condition, mbn connect successfully"); m_34GDialSuc = 4; return 1; } Dbg("4g condition, mbn connect failed."); return 0; } int CMobileDialFSM::Dial4GConnectEx(LPCTSTR lpcszInterface, LPCTSTR lpcszProfileName) { m_34GReserved = 4; if(m_34GDialSuc == 4) { m_34GDialSuc = 0; } ULONG ulResult = m_pMbn->ConnectEx2(lpcszInterface, lpcszProfileName); if(ulResult != (ULONG)-1) { Dbg("4g Dial4GConnectEx successfully"); if(m_recentInfo.usDialType == CNT_INVALID || (m_recentInfo.strDongle.Compare(lpcszInterface) || m_recentInfo.strProfile.Compare(lpcszProfileName) )) { Dbg("Store the new dial param."); m_34GDialSuc = 4; m_recentInfo.usDialType = CNT_MBN; m_recentInfo.strDongle = lpcszInterface; m_recentInfo.strProfile = lpcszProfileName; m_recentInfo.ulRequestID = ulResult; CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->WriteConfigValue("Recent", "Type", "MBN"); spConfigRun->WriteConfigValue("Recent", "Dongle", m_recentInfo.strDongle); spConfigRun->WriteConfigValue("Recent", "Profile", m_recentInfo.strProfile); spConfigRun->WriteConfigValueInt("Recent", "Manual", 0); spConfigRun->WriteConfigValueHexInt("Recent", "RequestID", ulResult); } else if(m_recentInfo.usDialType == CNT_MBN) { m_recentInfo.ulRequestID = ulResult; CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->WriteConfigValueHexInt("Recent", "RequestID", ulResult); } return 1; } if(m_34GDialSuc == 4) { m_34GDialSuc = 0; } Dbg("Dial4GConnectEx failed."); return 0; } int CMobileDialFSM::DialConnect() { static int s_x[MAX_BLACK_SHEEP_NUM]; static int s_y[MAX_BLACK_SHEEP_NUM]; static int s_z[MAX_BLACK_SHEEP_NUM]; static int s_pt; LOG_FUNCTION(); s_pt = 0; Dbg("---------- The first step arrived."); SetCurState(MBD_ACTIVATION_CONNECTING); auto state3G = GetRasStatus(); auto state4G = m_pMbn->GetCurState(); auto stateMBB = GetHWStatus(); Dbg("[MBN#%s][RAS#%s][MBB#%s]", ConvertStatusToString(state4G), ConvertStatusToString(state3G), ConvertStatusToString(stateMBB)); m_34GReserved = 0; if(m_nAdvancedGen == ADVANCE_MBB) { if(SwithMBBConnectStatus(TRUE)) { return ADVANCE_MBB; } return -1; } if(m_recentInfo.usDialType != CNT_INVALID) { if((m_recentInfo.usDialType == CNT_RAS && m_n3G > 0) || (m_recentInfo.usDialType == CNT_MBN && m_n4G > 0)) { Dbg("[%s]: Start to find the specified dial param.", m_recentInfo.usDialType == CNT_MBN ? "4G" : "3G"); const int cnt = g_DongleInfos.GetCount(); int aim = -1; Dbg("dongles'count: %d", cnt); for(int i=0; i 0) { return 3; } else if(g_DongleInfos[aim].state == MBD_ACTIVATION_DISCONNECTED) { SetCurState(MBD_CONNECTION_FAILURE); return -1; } } else { if(Dial4GConnectEx(m_recentInfo.strDongle, m_recentInfo.strProfile) > 0) { return 4; } else if(g_DongleInfos[aim].state == MBD_ACTIVATION_DISCONNECTED) { SetCurState(MBD_CONNECTION_FAILURE); return -1; } } Dbg("Nonono, give you one more chance"); } else { Dbg("[%s]: not found yet", m_recentInfo.usDialType == CNT_MBN ? "4G" : "3G"); } } } Dbg("---------- The second step arrived."); int cnt = g_DongleInfos.GetCount(); int aim = -1; bool fp3G = false, fp4G = false; for(int i=0; i 0) { if(g_DongleInfos[i].usDeviceType == DEVTYPE_MODEM && !fp3G) { fp3G = true;} else if(g_DongleInfos[i].usDeviceType == DEVTYPE_INTER && !fp4G) { fp4G = true; } } if(g_DongleInfos[i].state != MBD_ACTIVATION_DISCONNECTED) { Dbg("Ignore it bcz Dongle[%d]'s state: %s", i, ConvertStatusToString(g_DongleInfos[i].state)); continue; } if(cnt2 > 0) { for(int j=0; j 0) { aim = 4; Dbg("[MBN](%s)(%s) connect succ.", (LPCTSTR)g_DongleInfos[i].csInterfaceId, (LPCTSTR)g_DongleInfos[i].profileList[j].AccessInfo.strProfileDesc); break; } } else if(g_DongleInfos[i].profileList[j].AccessInfo.usCntType == CNT_RAS) { if(Dial3GConnectEx(g_DongleInfos[i].csInterfaceId, g_DongleInfos[i].profileList[j].strProfileName) > 0) { aim = 3; Dbg("[RAS](%s)(%s) connect succ.", (LPCTSTR)g_DongleInfos[i].csInterfaceId, (LPCTSTR)g_DongleInfos[i].profileList[j].AccessInfo.strProfileDesc); break; } } } } if(aim != -1) { return aim; } } if(s_pt > 0) { Dbg("---------- The third step arrived."); bool loop = true; int times = 0; do { DWORD dwMinError = (DWORD)-1; int aim3 = -1, k = -1; for(int i=0; i m_blackSheep[s_z[i]].dwErrCount) { aim3 = s_z[i]; k = i; dwMinError = m_blackSheep[s_z[i]].dwErrCount; } } if(aim3 >= 0) { int i = s_x[k]; int j = s_y[k]; if(g_DongleInfos[i].profileList[j].AccessInfo.usCntType == CNT_MBN) { if(Dial4GConnectEx(g_DongleInfos[i].csInterfaceId, g_DongleInfos[i].profileList[j].strProfileName) > 0) { aim = 4; Dbg("BlackSheep#[MBN](%s)(%s) connect succ.", (LPCTSTR)g_DongleInfos[i].csInterfaceId, (LPCTSTR)g_DongleInfos[i].profileList[j].AccessInfo.strProfileDesc); } } else if(g_DongleInfos[i].profileList[j].AccessInfo.usCntType == CNT_RAS) { if(Dial3GConnectEx(g_DongleInfos[i].csInterfaceId, g_DongleInfos[i].profileList[j].strProfileName) > 0) { aim = 3; Dbg("BlackSheep#[RAS](%s)(%s) connect succ.", (LPCTSTR)g_DongleInfos[i].csInterfaceId, (LPCTSTR)g_DongleInfos[i].profileList[j].AccessInfo.strProfileDesc); } } if(aim != -1) { return aim; } else { times++; Dbg("Black sheep cannot connect(%d/%d) ?", times, s_pt); m_blackSheep[aim3].dwErrCount += 2; if(times >= s_pt) { break; } Sleep(1000); } } else { loop = false; } } while (loop); } Dbg("---------- The fourth step arrived."); if(m_n3G > 0) { if(!m_csEntryName.IsNullOrEmpty() && Dial3GConnect()) { return 3; } } SetCurState(MBD_CONNECTION_FAILURE); return -1; } int CMobileDialFSM::DisConnect(BOOL bManual) { LOG_FUNCTION(); if(m_pMbn->GetCurState() == MBD_ACTIVATION_CONNECTED) { /*if(m_n4G > 0)*/if(m_pMbn->m_ulRequestID != ULONG(-1)) { BOOL bRet = m_pMbn->DisConnect(); // Description update... [Josephus in 14:37:06 2016/7/12] Dbg("4g Mbn disconnect return %d. requestID(%d)", bRet, m_pMbn->m_ulRequestID); } /*else if(m_n3G > 0)*/ if(g_hrasconn != NULL) { DWORD dwRet = RasHangUp(g_hrasconn); Dbg("RasHangUp in Disconnect function returned %d", dwRet); if(dwRet == ERROR_SUCCESS) { RASCONNSTATUS connStatus; connStatus.dwSize = sizeof(RASCONNSTATUS); Dbg("TickCount after RasHangUp..."); DWORD tcLast = GetTickCount() + 10000; while((RasGetConnectStatus(g_hrasconn, &connStatus) != ERROR_INVALID_HANDLE) && (tcLast > GetTickCount())) { Sleep(50); } Dbg("TickCount is done."); } } } RasHangUpSuffix(); return 0; } BOOL CMobileDialFSM::Dis4GConnect(LPCTSTR lpcszInterface) { assert(m_pMbn->GetCurState() == MBD_ACTIVATION_CONNECTED); BOOL bRet = m_pMbn->DisConnect(); return bRet; } int CMobileDialFSM::CreateCheckSocket() { int iResult = 0; if(m_sock != INVALID_SOCKET) { closesocket(m_sock); m_sock = INVALID_SOCKET; } m_sock = socket(AF_INET, SOCK_STREAM, 0); if (m_sock == INVALID_SOCKET) { m_dwLsErrCode = WSAGetLastError(); Dbg("create socket failed with error: %d", m_dwLsErrCode); SetCurState(MBD_NETWORK_INVALID_SOCKET); return -1; } // Set socket into nonblocking mode to prevent its connection action from delaying too much //[Josephus in 17:17:48 2016/3/31] ULONG ul = 1; iResult = ioctlsocket(m_sock, FIONBIO, (unsigned long*)&ul); if(iResult == SOCKET_ERROR) { m_dwLsErrCode = WSAGetLastError(); Dbg("Set socket into nonblocking mode failed %d", m_dwLsErrCode); SetCurState(MBD_NETWORK_INVALID_SOCKET); closesocket(m_sock); m_sock = INVALID_SOCKET; return -1; } return 0; } void CMobileDialFSM::BatteryNotifierTimeOut() { SYSTEM_POWER_STATUS sys_power_status; BOOL bRet = GetSystemPowerStatus(&sys_power_status); if (bRet != 0) { if (sys_power_status.ACLineStatus == 255) { Dbg("unknown AC power status."); m_bACPower = 2; } else m_bACPower = sys_power_status.ACLineStatus; if (sys_power_status.BatteryLifePercent == 255) { #ifndef TWINKLE_LOCAL_DEBUG Dbg("unknown battery power"); #endif } else { m_batteryRemains = sys_power_status.BatteryLifePercent; } //Dbg("oiltest %d",m_batteryRemains); if (m_batteryRemains != m_batteryRemainsF || m_bACPower != m_bACPowerF) { m_batteryRemainsF = m_batteryRemains; m_bACPowerF = m_bACPower; BatteryVar evt; evt.battery = (m_batteryRemains<<16)+m_bACPower; SpSendBroadcast(m_pEntity->GetFunction(),SP_MSG_OF(BatteryVar),SP_MSG_SIG_OF(BatteryVar),evt); Dbg("oiltest power left %d(%x)",sys_power_status.BatteryLifePercent,evt.battery); } } GetEntityBase()->GetFunction()->ResetTimer(MOBILEDIAL_TIMER_ID, BATTERY_TIMER_INTERVAL); return; } int CMobileDialFSM::CheckConnenction(bool bUseBackup, int& nRetType) { static int iResult = 0; int nRes = 0; nRetType = 0; iResult = CreateCheckSocket(); if(iResult < 0) { Dbg("Create sockect for connect operation failed %d", WSAGetLastError()); nRes = 2; } else { // Connect to server. SOCKADDR_IN addrSrv; addrSrv.sin_family = AF_INET; if(bUseBackup && m_bBackupAvail) { addrSrv.sin_addr.S_un.S_addr = inet_addr(m_csIpBackup); addrSrv.sin_port = htons(atoi(m_csPortBackup)); nRetType = 2; } else { addrSrv.sin_addr.S_un.S_addr = inet_addr(m_csIp); addrSrv.sin_port = htons(atoi(m_csPort)); nRetType = 1; } //Dbg("prepared for connecting"); timeval tm; FD_SET set; FD_SET exceptSet; iResult = connect(m_sock, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)); m_dwLsErrCode = WSAGetLastError(); if(iResult == SOCKET_ERROR && m_dwLsErrCode == WSAEWOULDBLOCK) { //Dbg("start to select"); // Set config value [Josephus in 9:54:07 2016/4/6] tm.tv_sec = m_TimeoutSec; tm.tv_usec = 0; FD_ZERO(&set); FD_SET(m_sock, &set); FD_ZERO(&exceptSet); FD_SET(m_sock, &exceptSet); iResult = select(m_sock+1, NULL, &set, &exceptSet, &tm); if(iResult == 0) { Dbg("timeout(%d)...", tm.tv_sec); //timeout iResult = SOCKET_ERROR; SetCurState(MBD_NETWORK_TIMEOUT); } else if(iResult > 0) { if(FD_ISSET(m_sock, &set)) { iResult = 0; SetCurState(MBD_VALID_CONNECTED); } else if(FD_ISSET(m_sock, &exceptSet)) { DWORD optVal; int optLen = sizeof(DWORD); if(getsockopt(m_sock, SOL_SOCKET, SO_ERROR, (char*)&optVal, &optLen) != SOCKET_ERROR) { Dbg("find it in exceptSet(socket#%d) %d", m_sock, optVal); m_dwLsErrCode = optVal; } else { Dbg("find it in exceptSet(socket#%d) but getOpt failed", m_sock); } iResult = SOCKET_ERROR; SetCurState(MBD_NETWORK_NOTFOUND_SOCKET); } else { Dbg("didn't find it in writeset(socket#%d)", m_sock); iResult = SOCKET_ERROR; SetCurState(MBD_NETWORK_NOTFOUND_SOCKET); } } else { // [Josephus in 14:42:30 2016/7/12] Dbg("socket(%d), iResult(%d)...", m_sock, iResult); SetCurState(MBD_NETWORK_ERROR_SOCKET); m_dwLsErrCode = WSAGetLastError(); } } if (iResult == SOCKET_ERROR) { Dbg("Set disconnect flag."); nRes = 0; } else { Dbg("Set connected flag."); nRes = 1; Sleep(2000); } // cleanup closesocket(m_sock); m_sock = INVALID_SOCKET; } return nRes; } void CMobileDialFSM::SendNetStatusMsg() { NetStatusVar evt; if(m_bPadAndFLB && isUsingNewVerAllInOne()) { if(m_signalVal == 0) { Dbg("Connected condition prior to check NetCard Set Signal default 4!!"); m_signalVal = 4; } Dbg("FLB type pad so Send real signal value! %d ", m_signalVal); evt.netstatus = m_signalVal; SpSendBroadcast(m_pEntity->GetFunction(),SP_MSG_OF(NetStatusVar),SP_MSG_SIG_OF(NetStatusVar),evt); return; } if(!m_bConnected) { Dbg("Send Signal 0 !!"); evt.netstatus = 0; m_signalVal = 0; SpSendBroadcast(m_pEntity->GetFunction(),SP_MSG_OF(NetStatusVar),SP_MSG_SIG_OF(NetStatusVar),evt); } else if(!m_bPadAndFLB) { Dbg("not pad or FLB so Send Signal default 4!!"); evt.netstatus = 4; m_signalVal = 4; SpSendBroadcast(m_pEntity->GetFunction(),SP_MSG_OF(NetStatusVar),SP_MSG_SIG_OF(NetStatusVar),evt); } else { m_signalVal = m_pMbn->m_nSignalVal; if(m_signalVal == 0) { Dbg("Connected condition prior to check NetCard Set Signal default 4!!"); m_signalVal = 4; } Dbg("Send Signal %d !!", m_signalVal); evt.netstatus = m_signalVal; SpSendBroadcast(m_pEntity->GetFunction(),SP_MSG_OF(NetStatusVar),SP_MSG_SIG_OF(NetStatusVar),evt); } } int CMobileDialFSM::SearchForCOMPorts() { int nCnt = 0; m_mapPort.clear(); GUID guid = GUID_CLASS_COMPORT; HDEVINFO hDevInfo = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if(hDevInfo == INVALID_HANDLE_VALUE) { Dbg("SetupDiGetClassDevs failed with error %d", GetLastError()); return -1; } SP_DEVINFO_DATA devInfoData; ZeroMemory(&devInfoData, sizeof(devInfoData)); devInfoData.cbSize = sizeof(SP_DEVINFO_DATA); int nIndex = 0; while(SetupDiEnumDeviceInfo(hDevInfo, nIndex++, &devInfoData)) { HKEY hKey = SetupDiOpenDevRegKey(hDevInfo, &devInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE); if(hKey){ DWORD dwDataType = 0; char szPort[256] = {0}; DWORD dwSize = sizeof(szPort); if(RegQueryValueEx(hKey, "PortName", NULL, &dwDataType, (LPBYTE)szPort, &dwSize) == ERROR_SUCCESS) { if(dwDataType == REG_SZ) { char szPortName[256] = {0}; DWORD dwSizeName = sizeof(szPortName); pair pairPort; pairPort.second = szPort; if(SetupDiGetDeviceRegistryProperty(hDevInfo, &devInfoData, SPDRP_DEVICEDESC, NULL, (PBYTE)szPortName, dwSizeName, &dwSizeName)) { pairPort.first = szPortName; }else { pairPort.first = ""; } m_mapPort.insert(pairPort); nCnt++; } } RegCloseKey(hKey); } } SetupDiDestroyDeviceInfoList(hDevInfo); return nCnt; } void CMobileDialFSM::_EntriesToDongle(const RasEntryWithDevice& entry, ptMbnProfileInfo info) { InitAccessKeyInfo(&info->AccessInfo); info->bUserDefined = true; info->AccessInfo.usCntType = CNT_RAS; info->AccessInfo.strProfileDesc = entry.szEntryName; info->AccessInfo.strPhoneNum = entry.szPhoneNumber; info->strProfileName = entry.szGUID; info->AccessInfo.IsDefault = TRUE; Dbg("ADD: %s", (LPCTSTR)info->strProfileName); if((entry.dwfOptions & RASEO_RequirePAP) == RASEO_RequirePAP) { info->AccessInfo.usAPType |= AUPR_PAP; } if((entry.dwfOptions & RASEO_RequireCHAP) == RASEO_RequireCHAP) { info->AccessInfo.usAPType |= AUPR_CHAP; } if((entry.dwfOptions & RASEO_RequireMsCHAP2) == RASEO_RequireMsCHAP2) { info->AccessInfo.usAPType |= AUPR_MSV2; } { CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); CSimpleStringA csEntryGUID = info->strProfileName; CSimpleStringA csValue; if(Error_Succeed == spConfigRun->ReadConfigValue(csEntryGUID, "Status", csValue) && csValue.GetLength() > 0) { if(csValue.IsStartWith("Invalid")) { Dbg("the runcfg record for %s is invalid : %s", (LPCTSTR)csEntryGUID, (LPCTSTR)csValue); } else { spConfigRun->ReadConfigValue(csEntryGUID, "PhoneNum", info->AccessInfo.strPhoneNum); spConfigRun->ReadConfigValue(csEntryGUID, "UserName", info->AccessInfo.strUserName); #ifdef USING_ENCRYPT spConfigRun->ReadConfigValue(csEntryGUID, "Password", csValue); info->AccessInfo.strPassword = DecryptString(csValue); #else spConfigRun->ReadConfigValue(csEntryGUID, "Password", info->AccessInfo.strPassword); #endif spConfigRun->ReadConfigValue(csEntryGUID, "APN", info->AccessInfo.strAccessString); } }else { Dbg("runcfg is not exist ras record for %s", (LPCTSTR)csEntryGUID); } } } //int CMobileDialFSM::WriteBackDirCfgToRunCfg() //{ // LOG_FUNCTION(); // CSmartPointer spConfigRun; // GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); // spConfigRun->WriteConfigValue("init", "param1", m_csPhoneNum); // spConfigRun->WriteConfigValue("init", "param2", m_csEntryName); // spConfigRun->WriteConfigValue("init", "param3", m_csUserName); // spConfigRun->WriteConfigValue("init", "param4", m_csPassword); // m_bRCfgHaveDial = true; // return 0; //} void CMobileDialFSM::RecordLastErrorMsg(int nLastError) { switch(nLastError) { case WSASYSNOTREADY: Dbg("ErrorCode(%d), Text[%s]", nLastError, "The underlying network subsystem is not ready for network communication."); break; case WSAVERNOTSUPPORTED: Dbg("ErrorCode(%d), Text[%s]", nLastError, "The version of Windows Sockets support requested is not provided by this particular Windows Sockets implementation"); break; case WSAEINPROGRESS : Dbg("ErrorCode(%d), Text[%s]", nLastError, "A blocking Windows Sockets 1.1 operation is in progress."); break; case WSAEPROCLIM: Dbg("ErrorCode(%d), Text[%s]", nLastError, "A limit on the number of tasks supported by the Windows Sockets implementation has been reached."); break; case WSAEFAULT: Dbg("ErrorCode(%d), Text[%s]", nLastError, "The lpWSAData parameter is not a valid pointer."); break; //Above for WSAStartup case WSANOTINITIALISED: Dbg("ErrorCode(%d), Text[%s]", nLastError, "A successful WSAStartup call must occur before using this function."); break; case WSAENETDOWN: Dbg("ErrorCode(%d), Text[%s]", nLastError, "The network subsystem has failed."); break; //Above for WSACleanup default: Dbg("ErrorCode(%d), josephtest can not explain the text current."); break; } } void CMobileDialFSM::SelfTest(EntityTestEnum eTestType,CSmartPointer pTransactionContext) { pTransactionContext->SendAnswer(m_ecSelfTest); } MOBILEDIAL_CONNECTION_STATE CMobileDialFSM::GetCurState() { if(m_bPadAndFLB && !isUsingNewVerAllInOne()) { const MOBILEDIAL_CONNECTION_STATE st3G = GetRasStatus(); const MOBILEDIAL_CONNECTION_STATE st4G = m_pMbn->GetCurState(); const MOBILEDIAL_CONNECTION_STATE stHW = GetHWStatus(); if(m_nAdvancedGen != 0) { if(m_nAdvancedGen == ADVANCE_RAS && st3G != MBD_ACTIVATION_CONNECTED) { return st3G; } if(m_nAdvancedGen == ADVANCE_MBN && st4G != MBD_ACTIVATION_CONNECTED) { return st4G; } if(m_nAdvancedGen == ADVANCE_MBB && stHW != MBD_ACTIVATION_CONNECTED && stHW != MBD_WLAN_CONNECTED) { return stHW; } } else { if(m_n3G > 0 || m_n4G > 0) { if(st3G == MBD_ACTIVATION_CONNECTED || st4G == MBD_ACTIVATION_CONNECTED) { if(m_34GReserved != 0){ m_34GReserved = 0; } } else { if(m_n3G > 0 && m_n4G > 0) { if(m_34GReserved == ADVANCE_RAS) { Dbg("Ras status handled.1"); return st3G; } else if(m_34GReserved == ADVANCE_MBN) { Dbg("Mbn status handled.1"); return st4G; } if(st3G == MBD_ACTIVATION_DISCONNECTED || st4G == MBD_ACTIVATION_DISCONNECTED) { return MBD_ACTIVATION_DISCONNECTED; } Dbg("[MBN#%s][RAS#%s]", ConvertStatusToString(st4G), ConvertStatusToString(st3G)); if(m_pMbn->HasAnyProfile()) { Dbg("Mbn status handled.3"); return st4G; } if(st4G == MBD_NO_PROFILE && st3G == MBD_NO_ENTRY) { return MBD_NO_PROFILE; } return MBD_INVALID_BOTH_DONGLE; } else if(m_n3G > 0) { Dbg("Ras status handled.2"); return st3G; } else { Dbg("Mbn status handled.2"); return st4G; } } } else if(m_curState != MBD_VALID_CONNECTED) { if(MBD_MIFI_START < stHW && stHW < MBD_MIFI_END) { Dbg("hw handle."); return stHW; } Dbg("no any dongle ..."); SetCurState(MBD_NO_MOBILEDONGLE); } } } Dbg("Main status handled."); return m_curState; } void CMobileDialFSM::OnStateTrans(int iSrcState, int iDstState) { //if(iSrcState == FSM_STATE_INIT) if(s1 == iSrcState && (iDstState == s4 || iDstState == s5)) m_bNotify = TRUE; } BOOL CMobileDialFSM::FormatLastError(DWORD dwCode, CSimpleStringA& csOut) { LPVOID lpMsgBuf; if(!FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_MAX_WIDTH_MASK, NULL, dwCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL )) { return FALSE; } csOut = (LPCTSTR)lpMsgBuf; LocalFree(lpMsgBuf); return TRUE; } CSimpleStringA CMobileDialFSM::GetFurtherDetail(BOOL slvNeed) { const MOBILEDIAL_CONNECTION_STATE state = GetCurState(); CSimpleStringA csTemp; CSimpleStringA csDetail; DWORD nSuffixCode = 0; BOOL fReportOrNot = TRUE; if(m_bConnected) { fReportOrNot = FALSE; } LOG_TRACE("[MBN#%s][RAS#%s][HW#%s][FSM#%s]", ConvertStatusToString(m_pMbn->GetCurState()), ConvertStatusToString(m_3gState), ConvertStatusToString(m_HwState), ConvertStatusToString(state)); if(m_bPadAndFLB) { nSuffixCode = 0x01000000; nSuffixCode |= (m_nAdvancedGen << 20); if(m_n3G > 0) nSuffixCode |= (m_n3G << 18); if(m_n4G > 0) nSuffixCode |= (m_n4G << 16); } nSuffixCode |= state; //Dbg("nSuffixCode : %d(0x%08x).", nSuffixCode, nSuffixCode); if(state < MBD_NETWORK_SEPERATE) { if(state == MBD_NETWORK_TIMEOUT) { if(m_bPadAndFLB) { if(!isUsingNewVerAllInOne()) { if(m_nAdvancedGen == 2 && mMBBParam.connectType == MBB_CONNECT_WIFI) { csTemp = "WLAN已连接,但网络请求超时"; } else { csTemp = "上网卡已连接,但网络请求超时"; } } } /*else { csTemp = "网线已连接,但网络请求超时"; }*/ if(csTemp.IsNullOrEmpty()) { csTemp = "网络请求超时"; } } // error!!! should be fixed in 1.9.0 [Josephus in 8:59:23 2016/9/22] else if(state == MBD_NETWORK_ERROR_SOCKET || state == MBD_NETWORK_NOTFOUND_SOCKET) { // [Josephus in 13:36:22 2016/9/6] CSimpleStringA csCode; if(m_bPadAndFLB) { if(FormatLastError(m_dwLsErrCode, csCode)) { CSimpleStringA csTest; if(!isUsingNewVerAllInOne()) { if(m_nAdvancedGen == 2 && mMBBParam.connectType == MBB_CONNECT_WIFI) { csTest = CSimpleStringA::Format("WLAN已连接,但网络出现错误:%s", (LPCTSTR)csCode); } else { csTest = CSimpleStringA::Format("上网卡已连接,但网络出现错误:%s", (LPCTSTR)csCode); } } else { csTest = CSimpleStringA::Format("网络出现错误:%s", (LPCTSTR)csCode); } LogEvent(Severity_Middle,CombineErrorCode(state), (LPCTSTR)csTest); } if(m_dwLsErrCode == 0) { if(!isUsingNewVerAllInOne()) { if(m_nAdvancedGen == 2 && mMBBParam.connectType == MBB_CONNECT_WIFI) { csTemp = "WLAN已连接,但网络出现错误"; } else { csTemp = "上网卡已连接,但网络出现错误"; } } else { csTemp = "网络出现错误"; } } else{ char cdString[128] = {0}; sprintf_s(cdString, 128, "GLE=%08X", m_dwLsErrCode); csTemp = CSimpleStringA::Format("网络出现错误[%s]", cdString); } } } else if(state == MBD_NETWORK_INVALID_SOCKET) { csTemp = "创建套接字失败"; } else if(state == MBD_NO_FOUND_CABLE){ csTemp = "网线未连接,请重新连接网线或设备"; } else { char cdString[128] = {0}; sprintf_s(cdString, 128, "%08x", nSuffixCode); csTemp = CSimpleStringA::Format("连接上网错误[%s]", cdString); } } else { if(state == MBD_READY_SIM_NO_INSERT) { csTemp = "SIM卡未插入卡托,请检查无线宽带上网卡"; } else if(state > MBD_READY_BAD_SIM_START && state < MBD_READY_BAD_SIM_END) { char cdString[128] = {0}; sprintf_s(cdString, 128, "%08x", nSuffixCode); csTemp = CSimpleStringA::Format("SIM卡出现异常[%s],请尝试重连设备", cdString); } else if(state == MBD_READY_NO_SERVICE) { csTemp = "无线宽带上网卡无服务,请检查卡托或咨询相关运营商"; } else if(state == MBD_CONNECTION_INVALID_ACCESS) { csTemp = "连接准入字符串设置错误,请检查配置后再重连设备"; } else if(state == MBD_CONNECTION_INVALID_NAMEORPASSWORD) { csTemp = "拨号所使用的用户名或密码错误"; } else if(state == MBD_UNKNOWN) { csTemp = "无线宽带上网卡状态不可用,请等候一段时间或重连设备"; } else if(state == MBD_NO_PROFILE) { csTemp = "找不到拨号参数,请先对4G上网卡进行配置"; } else if(state == MBD_NO_ENTRY){ csTemp = "找不到拨号参数,请先对上网卡进行配置"; } else if(state == MBD_RUN_ENTRY_NOTFOUND) {//仅3G拨号时出现的错误 csTemp = "运行时找不到3G拨号所需数据,请更新数据"; } else if(state == MBD_CREATE_ENTRY_FAILED) { csTemp = "创建拨号所需的电话簿失败"; } else if(state == MBD_NO_MOBILEDONGLE) { csTemp = "未检测到无线宽带上网卡,请重连设备"; } else if(state == MBD_CONNECTION_FAILURE || state == MBD_RASDIAL_FAILED) {//34G轮询拨号或仅4G拨号可能出现的错误 if(!_IsMBBProfileConfiged()) { csTemp = "尝试拨号上网失败,请检查配置后再重连设备"; } else { csTemp = "尝试拨号上网失败,请检查配置并确认是否在可用时间段"; } } else if(state == MBD_ACTIVATION_CONNECTING) { csTemp = "无线宽带上网卡正在进行拨号"; fReportOrNot = FALSE; } else if(state == MBD_ACTIVATION_DISCONNECTING) { csTemp = "无线宽带上网卡正在断开连接"; fReportOrNot = FALSE; } else if(state == MBD_ACTIVATION_DISCONNECTED) { csTemp = "无线宽带上网卡未连接"; fReportOrNot = FALSE; } else if(state == MBD_INVALID_BOTH_DONGLE) { csTemp = "上网卡出现异常,请检查配置或重连设备"; } else if(state == MBD_WLAN_INVALID_NAMEORPASSWORD) { csTemp = "无效的 WLAN 连接参数"; } else if(state == MBD_WLAN_OFF) { csTemp = "WLAN 被禁用"; } else if(state == MBD_WLAN_DISCONNECTED) { csTemp = "WLAN 未连接"; } else if(state == MBD_WLAN_CONNECTED) { csTemp = "WLAN 已连接"; fReportOrNot = FALSE; } else if(state == MBD_WLAN_CONNECTING) { csTemp = "正在连接 WLAN..."; fReportOrNot = FALSE; } else if(state == MBD_WLAN_ENTRY_NO_FOUND) { csTemp = "找不到指定的 SSID 名称"; fReportOrNot = FALSE; } else if(state == MBD_WLAN_CONNECT_FAILED) { csTemp = "尝试连接 WLAN 失败"; fReportOrNot = FALSE; } else if(state == MBD_WLAN_CONFIG_CHANGED) { csTemp = "WLAN 配置已更新"; fReportOrNot = FALSE; } else if(state == MBD_NO_FOUND_CABLE) { csTemp = "网线未连接,请重新连接网线或设备"; } else if(state == MBD_WLAN_CONFIG_REBOOT) { csTemp = "上网模式已同步更新为WLAN连接,请拔离MIFI设备并重启终端应用"; fReportOrNot = FALSE; } else if(state == MBD_WLAN_DEVICE_PLUG_OFF) { csTemp = "上网模式已同步更新,请拔离MIFI设备,或者你可以更改为有线连接方式"; fReportOrNot = FALSE; } else if(state == MBD_WLAN_CONFIG_WAIT_REBOOT) { csTemp = "上网模式同步更新完成,请重启终端应用或等候拨号模块自动重启"; fReportOrNot = FALSE; } else if(state == MBD_MIFI_LOGIN_INVALID_NAMEORPASSWORD) { csTemp = "登录到MIFI设备失败,无效的用户名或密码"; } else if(state == MBD_INTERNAL_ERROR) { csTemp = CSimpleStringA::Format("拨号程序执行异常[0x%08x],请尝试重连设备", m_pMbn->GetMBNCode()); } else { char cdString[128] = {0}; sprintf_s(cdString, 128, "%08x", nSuffixCode); csTemp = CSimpleStringA::Format("连接上网错误[%s]", cdString); } } if(slvNeed) { csDetail = CSimpleStringA::Format("%s#0x%08x", (LPCTSTR)csTemp, nSuffixCode); } else { csDetail = CSimpleStringA((LPCTSTR)csTemp.GetData()); } if(fReportOrNot && !slvNeed) { LogError(Severity_High, Error_InvalidState, CombineErrorCode(state), csDetail.GetData()); } return csDetail; } int CMobileDialFSM::CheckLANConnectStatus() { DWORD dwFlag; BOOL bRet = InternetGetConnectedState(&dwFlag, 0); Dbg("Return Status: %d, GetLastError: %d", bRet, GetLastError()); if((dwFlag & INTERNET_CONNECTION_CONFIGURED) == INTERNET_CONNECTION_CONFIGURED) { Dbg("Local system has a valid connection to the Internet, but it might or might not be currently connected."); } if((dwFlag & INTERNET_CONNECTION_LAN) == INTERNET_CONNECTION_LAN) { Dbg("Local system uses a local area network to connect to the Internet."); } if((dwFlag & INTERNET_CONNECTION_MODEM) == INTERNET_CONNECTION_MODEM) { Dbg("Local system uses a modem to connect to the Internet."); } if((dwFlag & INTERNET_CONNECTION_MODEM_BUSY) == INTERNET_CONNECTION_MODEM_BUSY) { Dbg("No longer used: INTERNET_CONNECTION_MODEM_BUSY"); } if((dwFlag & INTERNET_CONNECTION_OFFLINE) == INTERNET_CONNECTION_OFFLINE) { Dbg("Local system is in offline mode."); } if((dwFlag & INTERNET_CONNECTION_PROXY) == INTERNET_CONNECTION_PROXY) { Dbg("Local system uses a proxy server to connect to the Internet."); } if((dwFlag & INTERNET_RAS_INSTALLED) == INTERNET_RAS_INSTALLED) { Dbg("Local system has RAS installed."); } if(bRet) return 1; return 0; } void CMobileDialFSM::SendMsgToDialog(LPCTSTR errMsg, BOOL bSolvedInfor) { static char szMessage[256]; if(errMsg != NULL) { memset(szMessage, 0, sizeof(szMessage)); szMessage[0] = '\n'; if(!bSolvedInfor) { strcpy_s(szMessage, errMsg); } TellDlgTheResult(bSolvedInfor ? Error_Succeed : Error_Bug , WM_FATALMESSAGE_CHANGE, (LPARAM)szMessage); } } void CMobileDialFSM::ShowFatalError(LPCTSTR errMsg, BOOL bSolvedInfor) { static int nFatalTimes = 0; CSimpleStringA uiState = ""; bool bDisplay = true; auto err = this->GetEntityBase()->GetFunction()->GetSysVar("UIState",uiState); if(err == Error_Succeed && uiState.GetLength() > 0 && uiState[0] != 'X'){ bDisplay = false; } if(errMsg != NULL) { if(!bSolvedInfor) { nFatalTimes++; if(bDisplay) GetEntityBase()->GetFunction()->ShowFatalError(errMsg); else Dbg("ShowFatalError:%s", errMsg); } else if(nFatalTimes != 0) { nFatalTimes = 0; if(bDisplay) GetEntityBase()->GetFunction()->ShowFatalError(errMsg); else Dbg("ShowFatalSucceed:%s", errMsg); } SendMsgToDialog(errMsg, bSolvedInfor); } } void CMobileDialFSM::TryOpenWwanSvc() { ServiceStatus status = SERVICE_STATUS_UNKNOWN; BOOLEAN bRet = CSvcManager::GetInstance()->QueryServiceStatus(SERVICE_WWAN_AutoConfig, status); Dbg("The %s service query result: %d, status: %d.", SERVICE_WWAN_AutoConfig, bRet, status); if(bRet) { if(status == SERVICE_STATUS_STOPPED) { bRet = CSvcManager::GetInstance()->StartServiceWith(SERVICE_WWAN_AutoConfig); Dbg("CustomStartService %s returned %d.", SERVICE_WWAN_AutoConfig, bRet); if(!bRet) { LastErrorInfo infor; CSvcManager::GetInstance()->GetLastErrMsg(infor); Dbg("GetLastErr: %s.", infor.szErrMsg); } } else if(status == SERVICE_STATUS_PASUSED) { bRet = CSvcManager::GetInstance()->StopService(SERVICE_WWAN_AutoConfig); Dbg("StopService %s returned %d.", SERVICE_WWAN_AutoConfig, bRet); if(!bRet) { LastErrorInfo infor; CSvcManager::GetInstance()->GetLastErrMsg(infor); Dbg("GetLastErr: %s.", infor.szErrMsg); } } } } int CMobileDialFSM::RefreshRasEntry() { LOG_FUNCTION(); DWORD dwCb = 0; DWORD dwRet = ERROR_SUCCESS; DWORD dwEntries = 0; LPRASENTRYNAME lpRasEntryName = NULL; m_rasEntries.Clear(); dwRet = RasEnumEntries(NULL, NULL, lpRasEntryName, &dwCb, &dwEntries); if (dwRet == ERROR_BUFFER_TOO_SMALL && dwEntries > 0) { lpRasEntryName = (LPRASENTRYNAME) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb); if (lpRasEntryName == NULL){ Dbg("HeapAlloc failed when RasEnumEntries"); SetRasStatus(MBD_INTERNAL_ERROR); return -1; } lpRasEntryName[0].dwSize = sizeof(RASENTRYNAME); dwRet = RasEnumEntries(NULL, NULL, lpRasEntryName, &dwCb, &dwEntries); if (ERROR_SUCCESS == dwRet) { Dbg("The following RAS entry names were found:"); m_rasEntries.Init(dwEntries); for (DWORD i = 0; i < dwEntries; i++) { strcpy_s(m_rasEntries[i].szEntryName, lpRasEntryName[i].szEntryName); m_rasEntries[i].szDeviceType[0] = '\0'; m_rasEntries[i].szDeviceName[0] = '\0'; m_rasEntries[i].szPhoneNumber[0] = '\0'; m_rasEntries[i].dwfOptions = 0; Dbg("Refresh EntryName: %s", m_rasEntries[i].szEntryName); LPRASENTRY lpRasentry = NULL; LPBYTE lpDevInfo = NULL; DWORD dwEntrySz = 0, dwDevInfoSz = 0; dwRet = RasGetEntryProperties(NULL, lpRasEntryName[i].szEntryName, NULL, &dwEntrySz, NULL, &dwDevInfoSz); if(dwRet == ERROR_BUFFER_TOO_SMALL) { if(dwEntrySz != 0) lpRasentry = (LPRASENTRY)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwEntrySz); if(dwDevInfoSz != 0) lpDevInfo = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwDevInfoSz); } if(lpRasentry != NULL) { lpRasentry->dwSize = sizeof(RASENTRY); dwRet = RasGetEntryProperties(NULL, lpRasEntryName[i].szEntryName, lpRasentry, &dwEntrySz, lpDevInfo, &dwDevInfoSz); if(dwRet != 0) { Dbg("RasGetEntryProperties twice failed: %d", dwRet); } else { Dbg("DeviceName: %s, DeviceType: %s", lpRasentry->szDeviceName, lpRasentry->szDeviceType); strcpy_s(m_rasEntries[i].szDeviceName, lpRasentry->szDeviceName); strcpy_s(m_rasEntries[i].szDeviceType, lpRasentry->szDeviceType); strcpy_s(m_rasEntries[i].szPhoneNumber, lpRasentry->szLocalPhoneNumber); strcpy_s(m_rasEntries[i].szGUID, (LPCTSTR)GuidToString(lpRasentry->guidId)); Dbg("EntryGUID: %s", m_rasEntries[i].szGUID); m_rasEntries[i].dwfOptions = lpRasentry->dwfOptions; } } if(lpRasentry) { HeapFree(GetProcessHeap(), 0, lpRasentry); lpRasentry = NULL; } if(lpDevInfo) { HeapFree(GetProcessHeap(), 0, lpDevInfo); lpDevInfo = NULL; } } } else { HeapFree(GetProcessHeap(), 0, lpRasEntryName); lpRasEntryName = NULL; SetRasStatus(MBD_INTERNAL_ERROR); return -2; } HeapFree(GetProcessHeap(), 0, lpRasEntryName); lpRasEntryName = NULL; return dwEntries; } // There was either a problem with RAS or there are RAS entry names to enumerate if(dwEntries >= 1) { Dbg("The operation failed to acquire the buffer size."); SetRasStatus(MBD_INTERNAL_ERROR); return -3; } Dbg("There were no RAS entry names found."); SetRasStatus(MBD_NO_ENTRY); return 0; } ErrorCodeEnum CMobileDialFSM::AddNewProfile( const CSimpleStringA csInterfaceID, const AccessKeyInfo& newInfo, bool fApplyNow) { LOG_FUNCTION(); ErrorCodeEnum rc = Error_NoDefine; // if(newInfo.usCntType == CNT_MBN) { rc = m_pMbn->AddProfile(csInterfaceID, newInfo, fApplyNow); if(rc == Error_Succeed) { } }else if(newInfo.usCntType == CNT_RAS) { rc = CreatePhoneEntryEx(csInterfaceID, &newInfo, fApplyNow) < 0 ? Error_Unexpect : Error_Succeed; if(rc == Error_Succeed) { } } else if(newInfo.usCntType == CNT_ANDROID) { int slotID = strnicmp(csInterfaceID, "MAIN", strlen("MAIN")) == 0 ? 0 : 1; rc = m_SafeWirelessClient->UpdateOrInsertAPN(slotID, newInfo, fApplyNow); } else if(newInfo.usCntType == CNT_MBB) { hw::apn_config_t config; _ConvertToMBBApnStruct(newInfo, config); int res = m_HwDeviceMnt->add_profile(config, fApplyNow); if(res == 0) { _StoreMBBPassword(newInfo.strProfileDesc, newInfo.strPassword); rc = Error_Succeed; } else { const auto tmp = MBBResult2Status(res); //SetHWStatus(tmp); m_csErrMsg = CSimpleStringA::Format("添加配置到MIFI设备失败(%s)!", ConvertStatusToString(tmp)); rc = Error_Unexpect; } } else { m_csErrMsg = "不支持的连接配置方式!"; } return rc; } ErrorCodeEnum CMobileDialFSM::UpdateProfile( const CSimpleStringA csInterfaceID, LPCTSTR lpszProfileName, const AccessKeyInfo& newInfo, bool fApplyNow) { LOG_FUNCTION(); if(newInfo.usCntType == CNT_MBN) { return m_pMbn->UpdateProfile(csInterfaceID, lpszProfileName, newInfo, fApplyNow); } else if(newInfo.usCntType == CNT_RAS) { return UpdateEntryInfo(lpszProfileName, newInfo, fApplyNow); } else if(newInfo.usCntType == CNT_ANDROID) { int profileID = 0; if(lpszProfileName == NULL || strlen(lpszProfileName) == 0) { m_csErrMsg = "无效配置标识"; return Error_Param; } else { profileID = atoi(lpszProfileName); } int slotID = strnicmp(csInterfaceID, "MAIN", strlen("MAIN")) == 0 ? 0 : 1; return m_SafeWirelessClient->UpdateOrInsertAPN(slotID, newInfo, fApplyNow, profileID); } else if(newInfo.usCntType == CNT_MBB) { hw::connect_profile_t config; _ConvertToMBBApnStruct(newInfo, config.apn_config); int profileID = atoi(lpszProfileName); config.index = profileID; config.is_default = fApplyNow; int res = m_HwDeviceMnt->update_profile(config); Dbg("update profile with id: %d returned %d", profileID, res); if(res == 0) { _StoreMBBPassword(newInfo.strProfileDesc, newInfo.strPassword); return Error_Succeed; } else { const auto tmp = MBBResult2Status(res); //SetHWStatus(tmp); m_csErrMsg = CSimpleStringA::Format("更新配置到MIFI设备失败 (%s)!", ConvertStatusToString(tmp)); return Error_Unexpect; } } else { m_csErrMsg = "不支持的连接配置方式!"; return Error_NotMeetCondition; } } ErrorCodeEnum CMobileDialFSM::DeleteProfile(int nDongleIdx, int nProfileIdx) { LOG_FUNCTION(); if(g_DongleInfos[nDongleIdx].usDeviceType == DEVTYPE_INTER) { return m_pMbn->DeleteProfile(g_DongleInfos[nDongleIdx].csInterfaceId, g_DongleInfos[nDongleIdx].profileList[nProfileIdx].strProfileName); } else if(g_DongleInfos[nDongleIdx].usDeviceType == DEVTYPE_MODEM) { Dbg("DealConnctionActivity returned: %d", DealConnctionActivity(g_DongleInfos[nDongleIdx].profileList[nProfileIdx].AccessInfo.strProfileDesc)); DWORD dwRet = RasDeleteEntry(NULL, g_DongleInfos[nDongleIdx].profileList[nProfileIdx].AccessInfo.strProfileDesc); if(dwRet == 0) { return Error_Succeed; } else { m_csErrMsg = CSimpleStringA::Format("RasDeleteEntry failed: %d", dwRet); Dbg("Delete entry(%s) failed : %d", (LPCTSTR)g_DongleInfos[nDongleIdx].profileList[nProfileIdx].AccessInfo.strProfileDesc, dwRet); return Error_Unexpect; } } else if((g_DongleInfos[nDongleIdx].usDeviceType & DEVTYPE_ANDROID_UKNOWN ) || (g_DongleInfos[nDongleIdx].usDeviceType & DEVTYPE_MBB)) { int profileID = 0; if(!g_DongleInfos[nDongleIdx].profileList[nProfileIdx].strProfileName.IsNullOrEmpty()) { profileID = atoi(g_DongleInfos[nDongleIdx].profileList[nProfileIdx].strProfileName); } if(profileID == 0) { Dbg("invalid profile id! profileName:%s", g_DongleInfos[nDongleIdx].profileList[nProfileIdx].strProfileName.GetData()); m_csErrMsg = "无效配置序号"; return Error_Param; } if(g_DongleInfos[nDongleIdx].usDeviceType & DEVTYPE_ANDROID_UKNOWN) { return m_SafeWirelessClient->DeleteProfile(profileID); } else { int res = m_HwDeviceMnt->delete_profile_by(profileID); if(res == 0) { Dbg("delete profile succ."); _StoreMBBPassword(g_DongleInfos[nDongleIdx].profileList[nProfileIdx].AccessInfo.strProfileDesc, ""); return Error_Succeed; } else { const auto tmp = MBBResult2Status(res); //SetHWStatus(tmp); m_csErrMsg = CSimpleStringA::Format("删除配置失败(%s)!", ConvertStatusToString(tmp)); return Error_Unexpect; } } } m_csErrMsg = "不支持的连接配置文件类型"; return Error_NoDefine; } ErrorCodeEnum CMobileDialFSM::ConnectWithDefault() { if(m_SafeWirelessClient) { m_csErrMsg = ""; return m_SafeWirelessClient->ConnectWithDefault(); } return Error_NotInit; } int CMobileDialFSM::RetrieveDongleInfo() { ResetDongleInfos(); if(isUsingNewVerAllInOne()) { BOOL bActive = FALSE, bConnected = FALSE; ErrorCodeEnum ec = m_SafeWirelessClient->IsActive(bActive, bConnected); if(ec == Error_Succeed) { if(!bConnected) { SendMsgToDialog("当前未连接到多合一,请稍后再试!"); return -2; } int nNum = 0; ec = m_SafeWirelessClient->GetAPNConfigs(-1, nNum); return nNum; } else { SendMsgToDialog(CSimpleStringA::Format("连接多合一管控实体失败(0x%X)", ec)); return -1; } } if(m_nAdvancedGen == ADVANCE_MBB) { const auto hwStatus = GetHWStatus(); //if(hwStatus == MBD_WLAN_CONNECTED) { // int nNum3 = RetriveMifiInfo(); // if(nNum3 > 0) { // return nNum3; // } //} else { // m_csErrMsg = GetFurtherDetail(); //} if(hwStatus == MBD_NO_MOBILEDONGLE || hwStatus == MBD_WLAN_DISCONNECTED || hwStatus == MBD_WLAN_CONNECTING || hwStatus == MBD_WLAN_CONNECT_FAILED) { m_csErrMsg = GetFurtherDetail(); } else { int nNum3 = RetriveMifiInfo(); if(nNum3 > 0) { return nNum3; } } return -500; } int nNum = m_nAdvancedGen != 3 ? m_pMbn->EnumerateInterfaces(TRUE) : 0; int nNum2 = m_nAdvancedGen !=4 ? EnumCurRasDevices(TRUE) : 0; m_n3G = nNum2; m_n4G = nNum; if(nNum >= 0 || nNum2 >= 0) { if(nNum2 >= 0 && nNum >= 0) { return nNum + nNum2; } else if(nNum >= 0) return nNum; else return nNum2; } return (nNum < 0 ? nNum : nNum2); } void CMobileDialFSM::TellDlgTheResult(ErrorCodeEnum ec, UINT uMsg, LPARAM lparam) { if(m_hMainWnd) { PostMessage(m_hMainWnd, uMsg, ec, (LPARAM)lparam); } } BOOL CMobileDialFSM::UpdateProfileInfo(int nCurSel) { LOG_FUNCTION(); LOG_ASSERT(nCurSel >= 0); BOOL bRes = FALSE; if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_INTER) { bRes = m_pMbn->SearchForProfileName(&g_DongleInfos[nCurSel]); if(!bRes && m_pMbn->m_tmpState == MBD_NO_PROFILE) { Dbg("Because there are no profile..."); return TRUE; } } else if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_MODEM) { int nEntryNum = RefreshRasEntry(); if(nEntryNum < 0) { return FALSE; } int nGongleCnt = g_DongleInfos.GetCount(); for(int i=0; i 0) { g_DongleInfos[i].profileList.Init(cnt); for(int j=0, z=0; jIsActive(bActive, bConnected); if(ec == Error_Succeed) { if(!bConnected) { m_csErrMsg = "当前未连接到多合一,请稍后再试!"; return FALSE; } int nNum = 0; ec = m_SafeWirelessClient->GetAPNConfigsPure(nCurSel, nNum); if(ec == Error_Succeed) { return TRUE; } m_csErrMsg = CSimpleStringA::Format("调用接口 GetAPNConfigsPure 失败:%d", ec); return FALSE; } else { m_csErrMsg = CSimpleStringA::Format("连接多合一管控实体失败(0x%X)", ec); return FALSE; } } else { m_csErrMsg = CSimpleStringA::Format("未知连接类型:%d", g_DongleInfos[nCurSel].usDeviceType); } return bRes; } BOOL CMobileDialFSM::UpdateSubInfo(int nCurSel) { LOG_FUNCTION(); LOG_ASSERT(nCurSel >= 0); if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_INTER) { return m_pMbn->GetInterfaceInfo(g_DongleInfos[nCurSel].csInterfaceId, &g_DongleInfos[nCurSel].subInfo); } else if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_MODEM) { return UpdateRasConnectState(true) >= 0 ? TRUE : FALSE; } else if(g_DongleInfos[nCurSel].usDeviceType & DEVTYPE_ANDROID_UKNOWN) { int slotNum = 1; if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_ANDROID_MAIN) { slotNum = 1; // sim_slot_main } else if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_ANDROID_VICE) { slotNum = 2; // sim_slot_vice } else { m_csErrMsg = CSimpleStringA::Format("无效卡槽序号:%d", g_DongleInfos[nCurSel].usDeviceType); return FALSE; } int nNum = 0; ErrorCodeEnum ec = m_SafeWirelessClient->GetAPNConfigs(-1, nNum, true, false); if(ec == Error_Succeed) { return TRUE; } m_csErrMsg = CSimpleStringA::Format("调用接口 GetAPNConfigs 失败:%d", ec); return FALSE; } else if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_MBB) { if(_GetMBBDeviceInfo(g_DongleInfos[nCurSel]) == 0){ return TRUE; } return FALSE; } return FALSE; } void CMobileDialFSM::StorePersistentRequetsId(ULONG ulRequestID) { CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->WriteConfigValueHexInt("MBN", "RequestID", ulRequestID); //Dbg("Store RequestID: %d", ulRequestID); } BOOL CMobileDialFSM::GetPersistentRequestId(ULONG& ulRequestID) { UINT64 data; CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); if(spConfigRun->ReadConfigValueHexInt("MBN", "RequestID", data) == Error_Succeed) { ulRequestID = (ULONG)data; return TRUE; } Dbg("Read run config value for RequestID failed"); return FALSE; } void CMobileDialFSM::EraseTheRecentInfo(const ULONG ulRequestID) { LOG_FUNCTION(); Dbg("the coming id: %d", ulRequestID); Dbg("recent type: %d", m_recentInfo.usDialType); Dbg("recent request id: %d", m_recentInfo.ulRequestID); if(ulRequestID == 0) { return; } if(m_recentInfo.usDialType == CNT_MBN && m_recentInfo.ulRequestID == ulRequestID || (m_recentInfo.usDialType == CNT_RAS && m_recentInfo.ulRequestID == ulRequestID)) { Dbg("Start to remove recent infor : %d", m_recentInfo.usDialType == CNT_RAS); { int aim = -1; for(int i=0; i spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->WriteConfigValue("Recent", "Type", "Invalid"); spConfigRun->WriteConfigValue("Recent", "Dongle", ""); spConfigRun->WriteConfigValue("Recent", "Profile", ""); spConfigRun->WriteConfigValueInt("Recent", "Manual", 0); spConfigRun->WriteConfigValueHexInt("Recent", "RequestID", 0); } else { Dbg("try to erase the recent dial info failed!"); } } void CMobileDialFSM::SetAutoManage(bool bAuto /*= true*/) { CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->WriteConfigValueInt("init", "ManualManage", bAuto ? 0 : 1); if(m_bManageByUser == bAuto) { m_bManageByUser = !bAuto; if(!m_bManageByUser && GetCurrState()->id == s5) { Dbg("Recover and should to run...s5 entry"); ConnectTask* task = new ConnectTask(this); GetEntityBase()->GetFunction()->PostThreadPoolTask(task); } } } void CMobileDialFSM::SetAdvancedGen(int newValue) { if(newValue == 1) { newValue = ADVANCE_RAS; } else if(newValue == 2) { newValue = ADVANCE_MBN; } else if(newValue == 3) { newValue = 0; } else if(newValue == 4) { newValue = ADVANCE_MBB; } else { return; } CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->WriteConfigValueInt("init", "GenAdvanced", newValue); //m_nAdvancedGen = newValue; } // 映射到窗体的Radio控件的顺序 int CMobileDialFSM::GetAdvancedGen(bool fRead5RunCfg /*= false*/) { int ret = 0; if(!fRead5RunCfg) { ret = m_nAdvancedGen; } else { CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->ReadConfigValueInt("init", "GenAdvanced", ret); if(ret != ADVANCE_MBB && ret != ADVANCE_MBN && ret != ADVANCE_RAS) { ret = 0; } } if(ret == ADVANCE_RAS) { return 1; } else if(ret == ADVANCE_MBN) { return 2; } else if(ret == ADVANCE_MBB) { return 4; } return 3; } BOOL CMobileDialFSM::isUsingNewVerAllInOne() { #if HAS_NEW_ALL_IN_ONE static int status = -1; if(status == -1) { if(m_SafeWirelessClient == NULL) { EnterCriticalSection(&m_cs4WirlessClient); if(m_SafeWirelessClient == NULL) { m_SafeWirelessClient = new MySpace::WirelessAgentSafeClient(this); } LeaveCriticalSection(&m_cs4WirlessClient); } BOOL isActive = FALSE, isConnected = FALSE; ErrorCodeEnum ec = m_SafeWirelessClient->IsActive(isActive, isConnected); if(ec == Error_Succeed) { if(isActive) { status = 1; } else { status = 0; } } } if(status == -1) { BOOL active = FALSE; CSimpleStringA strDevName; ErrorCodeEnum ec = SpDetectWirelessConfig(GetEntityBase(), active, strDevName); if(active) { status = 1; } else if(ec == 0) { status = 0; } } if(status == 1) { return TRUE; } #endif return FALSE; } ErrorCodeEnum CMobileDialFSM::SwitchDefaultSlot(int slotIdx) { return m_SafeWirelessClient->SetDefaultSlot(slotIdx); } void CMobileDialFSM::SaveMBBConfig(const MBBParams* param, BOOL autoSave) { CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); spConfigRun->WriteConfigValue("MBB", "Username", param->loginParam.strUsername); CSimpleStringA csEValue = EncryptString(param->loginParam.strPassword); spConfigRun->WriteConfigValue("MBB", "Password", csEValue); spConfigRun->WriteConfigValueInt("MBB", "ConnectType", param->connectType); spConfigRun->WriteConfigValue("MBB", "SSID", param->wlanConnectParam.strUsername); csEValue = EncryptString(param->wlanConnectParam.strPassword); spConfigRun->WriteConfigValue("MBB", "SharedKey", csEValue); spConfigRun->WriteConfigValueInt("MBB", "Hidden", param->wlanConnectParam.Flag); spConfigRun->WriteConfigValueInt("MBB", "Customized", autoSave ? FALSE : TRUE); if(!autoSave) { Dbg("Update MBB param from outside."); } } bool CMobileDialFSM::GetMBBConfig(MBBParams* param, BOOL fSetDefaultIfEmpty) { if(param == NULL) { return false; } CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); param->connectType = MBB_CONNECT_UNKONWN; spConfigRun->ReadConfigValueInt("MBB", "ConnectType", param->connectType); param->loginParam.strUsername.Clear(); spConfigRun->ReadConfigValue("MBB", "Username", param->loginParam.strUsername); CSimpleStringA csEValue; spConfigRun->ReadConfigValue("MBB", "Password", csEValue); param->loginParam.strPassword.Clear(); param->loginParam.strPassword = DecryptString(csEValue); param->loginParam.Flag = FALSE; param->wlanConnectParam.strUsername.Clear(); spConfigRun->ReadConfigValue("MBB", "SSID", param->wlanConnectParam.strUsername); csEValue.Clear(); spConfigRun->ReadConfigValue("MBB", "SharedKey", csEValue); param->wlanConnectParam.strPassword.Clear(); param->wlanConnectParam.strPassword = DecryptString(csEValue); param->wlanConnectParam.Flag = FALSE; spConfigRun->ReadConfigValueInt("MBB", "Hidden", param->wlanConnectParam.Flag); param->customSet = FALSE; spConfigRun->ReadConfigValueInt("MBB", "Customized", param->customSet); BOOL fResetFlag = FALSE; if(fSetDefaultIfEmpty) { if(param->connectType == MBB_CONNECT_UNKONWN) { param->connectType = MBB_CONNECT_WIFI; fResetFlag = TRUE; } if(param->loginParam.strUsername.IsNullOrEmpty() || param->loginParam.strPassword.IsNullOrEmpty()) { param->loginParam.strUsername = DEFAULT_MIFI_LOGIN_USERNAME; param->loginParam.strPassword = DEFAULT_PASSWORD_PREFIX; param->loginParam.strPassword += m_strTerminalNo.SubString(0, 6); param->loginParam.Flag = FALSE; fResetFlag = TRUE; } if(param->wlanConnectParam.strUsername.IsNullOrEmpty() || param->wlanConnectParam.strPassword.IsNullOrEmpty()) { CSimpleStringA strNewSSID(m_strTerminalNo.GetData()); strNewSSID += "-MIFI"; CSimpleStringA strNewPassword(DEFAULT_PASSWORD_PREFIX); strNewPassword += m_strTerminalNo.SubString(6, m_strTerminalNo.GetLength() - 6); param->wlanConnectParam.strUsername = strNewSSID; param->wlanConnectParam.strPassword = strNewPassword; param->wlanConnectParam.Flag = TRUE; param->customSet = FALSE; fResetFlag = TRUE; } } if(param != &mMBBParam && !fResetFlag) { mMBBParam.connectType = param->connectType; mMBBParam.loginParam.strUsername = (LPCTSTR)param->loginParam.strUsername; mMBBParam.loginParam.strPassword = (LPCTSTR)param->loginParam.strPassword; mMBBParam.loginParam.Flag = param->loginParam.Flag; mMBBParam.wlanConnectParam.strUsername = (LPCTSTR)param->wlanConnectParam.strUsername; mMBBParam.wlanConnectParam.strPassword = (LPCTSTR)param->wlanConnectParam.strPassword; mMBBParam.wlanConnectParam.Flag = param->wlanConnectParam.Flag; mMBBParam.customSet = param->customSet; } else { csEValue.Clear(); spConfigRun->ReadConfigValue("MBB", "StoredSharedKey", csEValue); m_strReservedPasword = DecryptString(csEValue); /*暂时没有用*/ } return true; } ErrorCodeEnum CMobileDialFSM::ConnectWlan() { connect_param conn_param_; memset(&conn_param_, 0, sizeof(conn_param_)); conn_param_.temporary_mode = true; //if(m_strReservedPasword.IsNullOrEmpty() // || 0 != mMBBParam.wlanConnectParam.strPassword.Compare(m_strReservedPasword.GetData())) { // LogEvent(Severity_Middle, 0, "Need to update password!"); // conn_param_.rewrite_password = true; // strcpy_s(conn_param_.new_password, mMBBParam.wlanConnectParam.strPassword.GetData()); //} conn_param_.hidden_mode = !!mMBBParam.wlanConnectParam.Flag; strcpy_s(conn_param_.friendly_name, mMBBParam.wlanConnectParam.strUsername.GetData()); strcpy_s(conn_param_.password, mMBBParam.wlanConnectParam.strPassword.GetData()); Dbg("Start to connect wifi %s", conn_param_.friendly_name); Dbg("hidden or not? %s", conn_param_.hidden_mode ? "true" : "false"); if(m_dwWlanConnectTimes % 3 == 0 && !conn_param_.hidden_mode) { LogWarn(Severity_Low, Error_DataCheck, CombineErrorCode(MBD_WLAN_SSID_VISIBLE), "安全起见,请勿将 WLAN 设为广播模式!!"); } int rc = spagent::spagent_assistor::connect_wifi_with_param(&conn_param_); Dbg("connect to wifi(%s) returned: %d", conn_param_.friendly_name, rc); if(rc != 0) { LogWarn(Severity_Low, Error_NetBroken, 0, (LPCTSTR)CSimpleStringA::Format("connect to %s failed, hidden mode(%s): %d", conn_param_.friendly_name, (conn_param_.hidden_mode ? "true" : "false"), rc)); } return (ErrorCodeEnum)rc; } BOOL CMobileDialFSM::NeedToConnectWifi() { LOG_ASSERT(!mMBBParam.wlanConnectParam.strUsername.IsNullOrEmpty()); std::string ssid; //Dbg("start to find out whether is connected or not.."); int rc = spagent::spagent_assistor::is_connected(conn_tool_wifi, ssid); if(rc == 0) { Dbg("wifi is not connect !"); } else if(rc > 0) { Dbg("wifi is connected and connected ssid is: %s", ssid.c_str()); if(mMBBParam.wlanConnectParam.strUsername.Compare(ssid.c_str())) { //Dbg("force reconnect wifi bcz the ssid is not: %s", (LPCTSTR)mMBBParam.wlanConnectParam.strUsername); LogWarn(Severity_High, Error_Unexpect, CombineErrorCode(MBD_WLAN_CONNECTED_WITH_ILLEGAL_SSID), CSimpleStringA::Format("Unexpected wifi %s is connected, force to reconnect to %s immediately!", ssid.c_str(), mMBBParam.wlanConnectParam.strUsername.GetData())); rc = 0; } } return (rc == 0); } void CMobileDialFSM::UpdateWifiPassword(const CSimpleStringA& password) { CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); CSimpleStringA csEValue = EncryptString(password); spConfigRun->WriteConfigValue("MBB", "StoredSharedKey", csEValue); m_strReservedPasword = (LPCTSTR)password; } int CMobileDialFSM::RetriveMifiInfo() { if(m_HwDeviceMnt->detect_devices()) { int res = _LoginMBBDevice(mMBBParam); if(res != 0) { return res; } g_DongleInfos.Init(1); MbnDongleInfo& dongle = g_DongleInfos[0]; dongle.profileList.Clear(); res = _GetMBBDeviceInfo(dongle); if(res < 0) { return res; } _GetMBBProfiles(dongle); return 1; } else { SendMsgToDialog("未找到MIFI设备!"); return 0; } } BOOL CMobileDialFSM::SwithMBBConnectStatus(BOOL toConnect) { if(!toConnect) { int res = m_HwDeviceMnt->disconnect(); if(res == 0) { Dbg("disconnect mifi network succ."); return TRUE; } else { const auto tmp = MBBResult2Status(res); //SetHWStatus(tmp); m_csErrMsg = CSimpleStringA::Format("MIFI断开上网连接失败!(%s)", ConvertStatusToString(tmp)); return FALSE; } } else { int res = m_HwDeviceMnt->connect(); if(res == 0) { Dbg("connect mifi network succ."); return TRUE; } else { const auto tmp = MBBResult2Status(res); //SetHWStatus(tmp); m_csErrMsg = CSimpleStringA::Format("MIFI拨号上网连接失败!(%s)", ConvertStatusToString(tmp)); return FALSE; } } } void CMobileDialFSM::CheckHWDeviceStatus() { BOOL fToExtend = FALSE; if(m_nAdvancedGen == ADVANCE_MBB) { if(mMBBParam.connectType == MBB_CONNECT_WIRE) { if(CheckLANConnectStatus() == 0) { SetHWStatus(MBD_NO_MOBILEDONGLE); } else { SetHWStatus(MBD_ACTIVATION_CONNECTED); fToExtend = TRUE; } } else if(mMBBParam.connectType == MBB_CONNECT_WIFI) { if(NeedToConnectWifi()) { SetHWStatus(MBD_WLAN_DISCONNECTED); } else { SetHWStatus(MBD_WLAN_CONNECTED); fToExtend = TRUE; } } else { SetHWStatus(MBD_RUN_CONFIG_INCOMPLEMENT); } Dbg("Huawei status: %s", ConvertStatusToString(GetHWStatus())); if(fToExtend) { const int res = RetriveMifiInfo(); } } } void CMobileDialFSM::_ConvertToMBBApnStruct(const AccessKeyInfo& newInfo, hw::apn_config_t& config) { memset(&config, 0, sizeof(hw::apn_config_t)); wcscpy_s(config.profile_name, spagent::util::string_util::s2w(newInfo.strProfileDesc.GetData()).c_str()); wcscpy_s(config.apn_name, spagent::util::string_util::s2w(newInfo.strAccessString.GetData()).c_str()); wcscpy_s(config.username, spagent::util::string_util::s2w(newInfo.strUserName.GetData()).c_str()); wcscpy_s(config.password, spagent::util::string_util::s2w(newInfo.strPassword.GetData()).c_str()); if(newInfo.usAPType == AUPR_PAP) { config.auth_mode = hw::auth_pap; } else if(newInfo.usAPType == AUPR_CHAP) { config.auth_mode = hw::auth_chap; } else if(newInfo.usAPType == AUPR_PAPORCHAP) { config.auth_mode = hw::auth_none; } else { config.auth_mode = hw::auth_auto; } if(newInfo.strIPType.Compare("IPv4") == 0) { config.ip_type = hw::ipv4; } else if(newInfo.strIPType.Compare("IPv6") == 0) { config.ip_type = hw::ipv6; } else /*if(newInfo.strIPType.Compare("IPv4v6") == 0)*/ { config.ip_type = hw::ipv46; } } int CMobileDialFSM::_GetMBBDeviceInfo(MbnDongleInfo& dongle) { InitMbnDongleSubInfo(&dongle.subInfo); dongle.state = MBD_ACTIVATION_DISCONNECTED; dongle.usDeviceType = DEVTYPE_MBB; hw::dev_info_t dev_info; Dbg("start to get dev info..."); int res = m_HwDeviceMnt->get_dev_info(dev_info); if(res == 0) { dongle.subInfo.strProviderName = spagent::util::string_util::w2s(dev_info.dev_name).c_str(); dongle.subInfo.strDeviceID = spagent::util::string_util::w2s(dev_info.imsi).c_str(); dongle.subInfo.strManufacturer = spagent::util::string_util::w2s(dev_info.sn).c_str(); dongle.subInfo.strCellularClass = spagent::util::string_util::w2s(dev_info.work_mode).c_str(); dongle.subInfo.strFirmware = spagent::util::string_util::w2s(dev_info.hardware_version).c_str(); dongle.subInfo.strSimIccID = spagent::util::string_util::w2s(dev_info.iccid).c_str(); dongle.subInfo.strMode = spagent::util::string_util::w2s(dev_info.provider_name).c_str(); dongle.csInterfaceId = spagent::util::string_util::w2s(dev_info.dev_name).c_str(); dongle.subInfo.ulSingnal = dev_info.network_status.signal_strength; dongle.subInfo.mbnCntState = MBN_ACTIVATION_STATE_NONE; Dbg("connect status: %d", (int)dev_info.network_status.connect_status); if(dev_info.network_status.connect_status == hw::connected) { dongle.subInfo.mbnCntState = MBN_ACTIVATION_STATE_ACTIVATED; } else if(dev_info.network_status.connect_status == hw::connecting) { dongle.subInfo.mbnCntState = MBN_ACTIVATION_STATE_ACTIVATING; } else if(dev_info.network_status.connect_status == hw::disconnecting) { dongle.subInfo.mbnCntState = MBN_ACTIVATION_STATE_DEACTIVATING; } else if(dev_info.network_status.connect_status == hw::disconnected) { dongle.subInfo.mbnCntState = MBN_ACTIVATION_STATE_DEACTIVATED; } dongle.state = GetMBBConnectState(dev_info.network_status); SetHWStatus(dongle.state); Dbg("dongle connect status: %d", (int)dongle.subInfo.mbnCntState); } else { Dbg("get the mifi dev information failed: %d", res); const auto tmp = MBBResult2Status(res); //SetHWStatus(tmp); SendMsgToDialog(CSimpleStringA::Format("获取MIFI设备信息失败 (%s)", ConvertStatusToString(tmp))); res = -1; } return res; } int CMobileDialFSM::_GetMBBProfiles(MbnDongleInfo& dongle) { std::vector profiles; Dbg("start to get connect profile..."); hw::connect_profile_t* profile = new hw::connect_profile_t[PROFILE_MAX_COUNT]; memset(profile, 0, sizeof(hw::connect_profile_t)*PROFILE_MAX_COUNT); int profileNum = PROFILE_MAX_COUNT; //int nNum = m_HwDeviceMnt->get_connect_profiles(profiles); int nNum = m_HwDeviceMnt->get_profiles(profile, profileNum); Dbg("get_connect_profiles returned %d", nNum); if(nNum > 0) { dongle.profileList.Init(nNum); int idx = 0; //while(it != nullptr) { for(int i=0; iapn_config.profile_name).c_str(); profile.strProfileName = CSimpleStringA::Format("%d", it->index); profile.AccessInfo.IsDefault = it->is_default; if(it->is_default) { dongle.subInfo.strProfileName = profile.strProfileName.GetData(); } profile.AccessInfo.strAccessString = spagent::util::string_util::w2s(it->apn_config.apn_name).c_str(); profile.AccessInfo.strUserName = spagent::util::string_util::w2s(it->apn_config.username).c_str(); profile.AccessInfo.strPassword = spagent::util::string_util::w2s(it->apn_config.password).c_str(); //TODO: 新版的MIFI有给定特殊的********号字符,需要做处理,后续验证 if(profile.AccessInfo.strPassword.IsNullOrEmpty()) { _RetrieveMBBPassword(profile.AccessInfo.strProfileDesc, profile.AccessInfo.strPassword); } if(it->apn_config.auth_mode == hw::auth_auto) { profile.AccessInfo.usAPType = AUPR_AUTO; } else if(it->apn_config.auth_mode == hw::auth_pap) { profile.AccessInfo.usAPType = AUPR_PAP; } else if(it->apn_config.auth_mode == hw::auth_chap) { profile.AccessInfo.usAPType = AUPR_CHAP; } else if(it->apn_config.auth_mode == hw::auth_none) { profile.AccessInfo.usAPType = AUPR_PAPORCHAP; } if(it->apn_config.ip_type == hw::ipv4) { profile.AccessInfo.strIPType = "IPv4"; } else if(it->apn_config.ip_type == hw::ipv6) { profile.AccessInfo.strIPType = "IPv6"; } else { profile.AccessInfo.strIPType = "IPv4v6"; } idx++; } } else { const auto tmp = MBBResult2Status(nNum); } delete [] profile; return nNum; } void CMobileDialFSM::_StoreMBBPassword(const CSimpleStringA& profileName, const CSimpleStringA& password) { CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); CSimpleStringA csEValue = EncryptString(password); spConfigRun->WriteConfigValue(profileName, "Password", csEValue); } void CMobileDialFSM::_RetrieveMBBPassword(const CSimpleStringA& profileName, CSimpleStringA& password) { CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); CSimpleStringA csValue; spConfigRun->ReadConfigValue(profileName, "Password", csValue); password = DecryptString(csValue); } int CMobileDialFSM::_LoginMBBDevice(const MBBParams& newParam) { int res = 0; bool firstLogin = false; if(!m_HwDeviceMnt->has_login(firstLogin)) { std::wstring username = spagent::util::string_util::s2w(newParam.loginParam.strUsername.GetData()); std::wstring password = spagent::util::string_util::s2w(newParam.loginParam.strPassword.GetData()); //Dbg("start to login: %s, %s", (LPCTSTR)newParam.loginParam.strUsername, (LPCTSTR)newParam.loginParam.strPassword); Dbg("start to login: %s %d", (LPCTSTR)newParam.loginParam.strUsername, newParam.loginParam.strPassword.GetLength()); res = m_HwDeviceMnt->login(username, password); const auto tmp = MBBResult2Status(res); if(res == -3) { Dbg("login failed: incorrect usrname or password!"); SendMsgToDialog("登录密码不正确!"); } else if(res != 0) { Dbg("login returned %s", ConvertStatusToString(tmp)); //SetHWStatus(tmp); m_csErrMsg = CSimpleStringA::Format("登录到MIFI设备失败(%s)!", ConvertStatusToString(tmp)); SendMsgToDialog(m_csErrMsg); } } return res; } int CMobileDialFSM::_UpdateMBBDualParam(int configMask, MBBParams& newParam) { /*对于MIFI3,需要先改密码然后再更新WIFI信息,否则后面的MAC过滤地址会报9003的错误*/ if(!!(configMask & 4)) { std::wstring username = CSimpleStringA2W(newParam.loginParam.strUsername).GetData(); std::wstring password = CSimpleStringA2W(newParam.loginParam.strPassword).GetData(); const CSimpleStringA oldPassword = newParam.loginParam.strPassword; newParam.loginParam.strPassword = DEFAULT_PASSWORD_PREFIX; newParam.loginParam.strPassword += m_strTerminalNo.SubString(0, 6); std::wstring newPassword = CSimpleStringA2W(newParam.loginParam.strPassword).GetData(); int res = m_HwDeviceMnt->change_password(username, password, newPassword); Dbg("update login password returned: %d",res); if(res != 0) { newParam.loginParam.strPassword = oldPassword; configMask &= (int(~4)); const auto tmp = MBBResult2Status(res); Dbg("change_password failed: %s", ConvertStatusToString(tmp)); return -1; } } if(!!(configMask & 1)) { hw::wlan_config_t new_wlan_config; memset(&new_wlan_config, 0, sizeof(hw::wlan_config_t)); CSimpleStringW strUsernameW = CSimpleStringA2W(newParam.wlanConnectParam.strUsername); CSimpleStringW strPasswordW = CSimpleStringA2W(newParam.wlanConnectParam.strPassword); wcscpy_s(new_wlan_config.ssid, strUsernameW.GetData()); wcscpy_s(new_wlan_config.password, strPasswordW.GetData()); new_wlan_config.hidden = !!newParam.wlanConnectParam.Flag; int save_res = m_HwDeviceMnt->set_wlan_config(new_wlan_config, true); Dbg("update wlan config returned: %d", save_res); if(save_res != 0) { const auto tmp = MBBResult2Status(save_res); Dbg("set wlan config failed: %s", ConvertStatusToString(tmp)); return -1; } } if(!!(configMask & 2) || !!(configMask & 4)) { Dbg("Write to the run config"); LOG_ASSERT(!newParam.loginParam.strUsername.IsNullOrEmpty()); LOG_ASSERT(!newParam.loginParam.strPassword.IsNullOrEmpty()); LOG_ASSERT(!newParam.wlanConnectParam.strUsername.IsNullOrEmpty()); LOG_ASSERT(!newParam.wlanConnectParam.strPassword.IsNullOrEmpty()); SaveMBBConfig(&newParam); } return 0; } MOBILEDIAL_CONNECTION_STATE CMobileDialFSM::GetMBBConnectState(const hw::network_info_t& info) { if(info.sim_locked) { return MBD_READY_DEVICE_LOCKED; } else if(info.sim_status == hw::sim_not_found) { return MBD_READY_SIM_NO_INSERT; } else if(info.sim_status == hw::invalid_sim) { return MBD_READY_BAD_SIM; } if(info.connect_status == hw::connected) { return MBD_ACTIVATION_CONNECTED; } else if(info.connect_status == hw::connecting) { return MBD_ACTIVATION_CONNECTING; } else if(info.connect_status == hw::disconnecting) { return MBD_ACTIVATION_DISCONNECTING; } else if(info.connect_status == hw::disconnected) { return MBD_ACTIVATION_DISCONNECTED; } else if(info.connect_status == hw::connect_failed || info.connect_status == hw::connect_failed_with_poor) { return MBD_CONNECTION_FAILURE; } else if(info.connect_status == hw::no_service) { return MBD_READY_NO_SERVICE; } else if(info.connect_status == hw::connect_dial_up_param_failed) { return MBD_CONNECTION_FAILURE; } else { return MBD_ACTIVATION_NONE; } } ErrorCodeEnum CMobileDialFSM::_InsertLocal2MacFilter() { ErrorCodeEnum ec = Error_Succeed; if(mMBBParam.connectType == MBB_CONNECT_WIRE) { return ec; } std::vector wlanKeys; wlanKeys.push_back("wlan"); CSmartPointer spConfigRun; GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun); CSimpleStringA csWlanName; BOOL fNeedEnum = TRUE; std::string strNewMac; LOG_ASSERT(!m_strTerminalNo.IsNullOrEmpty()); LOG_ASSERT(!mMBBParam.wlanConnectParam.strUsername.IsNullOrEmpty()); CSimpleStringA strTerminalxSSID = m_strTerminalNo + "x" + mMBBParam.wlanConnectParam.strUsername; int insertOrNot = 0; //spConfigRun->ReadConfigValueInt("MIFI", strTerminalxSSID, insertOrNot); //if(insertOrNot > 0) { // return Error_Succeed; //} spConfigRun->ReadConfigValue("MIFI", "WlanMacName", csWlanName); if(!csWlanName.IsNullOrEmpty()) { Dbg("add wlan name from run config: %s", csWlanName.GetData()); CAutoArray csMacAddress = csWlanName.Split(':'); if(csMacAddress.GetCount() == 6) { fNeedEnum = FALSE; strNewMac = csWlanName.GetData(); } } if(fNeedEnum) { int aimIndex = -1; network_adapters local_adapters; const int count_of_adapters = spagent::spagent_assistor::get_network_adapters(local_adapters); for(int i=0; iinsert_mac_filter(filter_info); Dbg("insert mac returned: %d", res); if(res == 0) break; Sleep(300*t); } if(res != 0) { //LogError(Severity_High, Error_Unexpect, // CombineErrorCode(MBBResult2Status(res)), // ); ShowFatalError(CSimpleStringA::Format("写入MAC白名单失败:%s", ConvertStatusToString(MBBResult2Status(res)))); } else { spConfigRun->WriteConfigValueInt("MIFI", strTerminalxSSID, 1); } } else { ShowFatalError("获取不到 WLAN 网卡信息,请联系信息技术人员协助处理!"); } return ec; } void CMobileDialFSM::SetSysVal(int nFlag) { CSmartPointer spFunction = this->GetEntityBase()->GetFunction(); CSimpleStringA csStatus; CSimpleStringA csNewStatus = sysVarNetStatusEnum[NET_STATUS_UNINIT]; ErrorCodeEnum err; err = spFunction->GetSysVar(SYSVAR_NET_STATUS, csStatus); Dbg("Current sys val of " SYSVAR_NET_STATUS " : %s(%d)", (LPCTSTR)csStatus, err); if(nFlag >= sizeof(sysVarNetStatusEnum)/sizeof(sysVarNetStatusEnum[0])) { Dbg("out range of current sys var list: %d", nFlag); } else { csNewStatus = sysVarNetStatusEnum[nFlag]; } if(csNewStatus != csStatus) { err = spFunction->SetSysVar(SYSVAR_NET_STATUS, csNewStatus, true); Dbg("SetSysVar " SYSVAR_NET_STATUS " from '%s' to '%s' returned %d", (LPCTSTR)csStatus, (LPCTSTR)csNewStatus, err); } else { Dbg("system value is same with already one."); } return; } void CMobileDialFSM::ReportConnectType() { CSimpleStringA str(true); MOBILEDIAL_CONNECTION_STATE state = MBD_NOT_INITIALIZED; if(!m_bManufactureSignal) { if(m_bPadAndLIB) { state = MBD_CABLE_TYPE_WIRE; } else if(m_nAdvancedGen == ADVANCE_MBB) { state = MBD_CABLE_TYPE_MBB; } else if(m_nAdvancedGen == ADVANCE_RAS) { state = MBD_CABLE_TYPE_DONGLE; } else if(g_DongleInfos.GetCount() > 0){ const int cnt = g_DongleInfos.GetCount(); for(int i=0; iget_network_info(info); if(res == 0) { CSimpleStringA strNewDevName = CSimpleStringW2A(CSimpleStringW(info.dev_name)); if(m_curMIFIDevName.IsNullOrEmpty() || m_curMIFIDevName.Compare(strNewDevName) != 0) { /*借来一用,反正新版多合一没戏了*/ EnterCriticalSection(&m_cs4WirlessClient); m_curMIFIDevName = strNewDevName; LeaveCriticalSection(&m_cs4WirlessClient); } if((m_nAdvancedGen != ADVANCE_MBB || mMBBParam.connectType != MBB_CONNECT_WIRE) && !IsWifiConnected()) { Dbg("plug in status: %d", info.usb_plug_in_status ? 1 : 0); if(info.usb_plug_in_status) { if(GetCurrState()->id != CMobileDialFSM::s8 && GetCurrState()->id != CMobileDialFSM::s2) { ShowFatalError(CSimpleStringA::Format("检测到华为MIFI设备 %s 插入", m_curMIFIDevName.GetData())); if(DetectMBBConfigUpdate(FALSE)) { Dbg("post USER_EVT_CONFIG_DETECT event."); FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CONFIG_DETECT); fsmEvent->param1 = 1; PostEventFIFO(fsmEvent); } } else { LogEvent(Severity_Middle, CombineErrorCode(MBD_HOLD_MOBILEDONGLE), CSimpleStringA::Format("检测到华为MIFI: %s 设备插入", m_curMIFIDevName.GetData())); sleepMaxTimes = 20; } } } else { if(m_mifiBattery != (int)info.battery_percent) { Dbg("mifi's battery changed from %d to %d", m_mifiBattery, (int)info.battery_percent); if(info.battery_percent == 0) { LogWarn(Severity_High, Error_Hardware, CombineErrorCode(MBD_MIFI_LOW_BATTERY), "MIFI设备电量低!"); } m_mifiBattery = (int)info.battery_percent; } const MOBILEDIAL_CONNECTION_STATE current_state = GetMBBConnectState(info); if(GetHWStatus() != current_state) { const auto old_status = SetHWStatus(current_state); if(current_state == MBD_ACTIVATION_CONNECTED) { TellDlgTheResult(Error_Succeed, WM_DIAL_RESULT, ADVANCE_MBB); FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CONNECT_COMPLETE); fsmEvent->param1 = 0; fsmEvent->param2 = ADVANCE_MBB; PostEventLIFO(fsmEvent); } else if(current_state == MBD_ACTIVATION_DISCONNECTED) { TellDlgTheResult(Error_Succeed, WM_DIAL_DISCONNECT, ADVANCE_MBB); FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DISCONNECT_COMPLETE); fsmEvent->param1 = 0; fsmEvent->param2 = ADVANCE_MBB; } } if(current_state == MBD_ACTIVATION_CONNECTED) { TellDlgTheResult(Error_Succeed, WM_SIGNAL_CHANGE, info.signal_strength); const int signalVal = (int)(0.05f * info.signal_strength / 5 * 4); if(signalVal != m_signalVal) { Dbg("mifi's network signal changed from %d to %d", m_signalVal, signalVal); FSMEvent* signalEvent = new FSMEvent(USER_EVT_SIGNAL); signalEvent->param1 = signalVal; PostEventFIFO(signalEvent); m_signalVal = signalVal; } } } } else if(res != -12 && res != -18 && res != -10) { LogWarn(Severity_Low, Error_Unexpect, CombineErrorCode(MBBResult2Status(res)), CSimpleStringA::Format("Try to get MBB network infor failed: %s!", ConvertStatusToString(MBBResult2Status(res)))); } else if(m_nAdvancedGen != ADVANCE_MBB) { if(MBD_MIFI_START < GetHWStatus() && GetHWStatus() < MBD_MIFI_END) { SetHWStatus(MBD_NOT_INITIALIZED); } } sleepTimes = 0; while(!m_fMBBDeviceMonitorStop && ++sleepTimes <= sleepMaxTimes) { Sleep(1000); } } Dbg("out of while %d", m_fMBBDeviceMonitorStop); m_fMBBDeviceMonitoring = FALSE; } void CMobileDialFSM::BroadcastCableChangedEvent(MOBILEDIAL_CONNECTION_STATE state) { //let it empty at current time. bool fDeal = true; MOBILEDIAL_CONNECTION_STATE cur_state = state; if(state >= MBD_CABLE_DEVICE_REMOVE && state < MBD_CABLE_DEVICE_ARRIVAL) { cur_state = MBD_CABLE_DEVICE_REMOVE; } else if(state >= MBD_CABLE_DEVICE_ARRIVAL && state < MBD_CABLE_DIALUP_CONNETED) { cur_state = MBD_CABLE_DEVICE_ARRIVAL; } else if(state >= MBD_CABLE_DIALUP_CONNETED && state < MBD_CABLE_DIALUP_DISCONNETED) { cur_state = MBD_CABLE_DIALUP_CONNETED; } else if(state >= MBD_CABLE_DIALUP_DISCONNETED && state <= MBD_RAS_DIALUP_DISCONNETED_IN_BUSINESS) { cur_state = MBD_CABLE_DIALUP_DISCONNETED; } else { Dbg("unsupport event: %s", ConvertStatusToString(state)); fDeal = false; } if(fDeal) { LogEvent(Severity_High, CombineErrorCode(cur_state), ConvertStatusToString(state)); } } void CMobileDialFSM::BroadcastCableChangedFSMEvent(const FSMEvent* pEvt) { switch(pEvt->iEvt) { case USER_EVT_DEVICE_ARRIVAL: { if(pEvt->param2 == 3) { if(pEvt->param1 == 1) { Dbg("UserCode:0x%08X, 收到3G网卡插入的外部监听事件", CombineErrorCode(MBD_RAS_DEVICE_ARRIVAL)); //LogEvent(Severity_Middle, CombineErrorCode(MBD_RAS_DEVICE_ARRIVAL), "收到3G网卡插入的外部监听事件"); } else if(pEvt->param1 == 0) { Dbg("UserCode:0x%08X, 收到3G网卡插入的内部处理事件", CombineErrorCode(MBD_RAS_DEVICE_ARRIVAL)); //LogEvent(Severity_Middle, CombineErrorCode(MBD_RAS_DEVICE_ARRIVAL), "收到3G网卡插入的内部处理事件"); } BroadcastCableChangedEvent(MBD_RAS_DEVICE_ARRIVAL); } else if(pEvt->param2 == 4) { if(pEvt->param1 == 1) { Dbg("UserCode:0x%08X, 收到4G网卡插入的外部监听事件", CombineErrorCode(MBD_MBN_DEVICE_ARRIVAL)); //LogEvent(Severity_Middle, CombineErrorCode(MBD_MBN_DEVICE_ARRIVAL), "收到4G网卡插入的外部监听事件"); } else if(pEvt->param1 == 0) { Dbg("UserCode:0x%08X, 收到4G网卡插入的内部处理事件", CombineErrorCode(MBD_MBN_DEVICE_ARRIVAL)); LogEvent(Severity_Middle, CombineErrorCode(MBD_MBN_DEVICE_ARRIVAL), "收到4G网卡插入的内部处理事件"); } BroadcastCableChangedEvent(MBD_MBN_DEVICE_ARRIVAL); } else if(pEvt->param2 == 2) { LogEvent(Severity_Middle, CombineErrorCode(MBD_MBB_DEVICE_ARRIVAL), "收到有线卡托插入的外部监听事件"); } } break; case USER_EVT_DEVICE_LEAVE: { if(pEvt->param2 == 3) { if(pEvt->param1 == 1) { Dbg("UserCode:0x%08X, 收到3G网卡拔离的外部监听事件", CombineErrorCode(MBD_RAS_DEVICE_REMOVE)); //LogEvent(Severity_Middle, CombineErrorCode(MBD_RAS_DEVICE_REMOVE), "收到3G网卡拔离的外部监听事件"); } else if(pEvt->param1 == 0) { Dbg("UserCode:0x%08X, 收到3G网卡拔离的内部处理事件", CombineErrorCode(MBD_RAS_DEVICE_REMOVE)); //LogEvent(Severity_Middle, CombineErrorCode(MBD_RAS_DEVICE_REMOVE), "收到3G网卡拔离的内部处理事件"); } BroadcastCableChangedEvent(MBD_RAS_DEVICE_REMOVE); } else if(pEvt->param2 == 4) { if(pEvt->param1 == 1) { Dbg("UserCode:0x%08X, 收到4G网卡拔离的外部监听事件", CombineErrorCode(MBD_MBN_DEVICE_REMOVE)); //LogEvent(Severity_Middle, CombineErrorCode(MBD_MBN_DEVICE_REMOVE), "收到4G网卡拔离的外部监听事件"); } else if(pEvt->param1 == 0) { Dbg("UserCode:0x%08X, 收到4G网卡拔离的内部处理事件", CombineErrorCode(MBD_MBN_DEVICE_REMOVE)); //LogEvent(Severity_Middle, CombineErrorCode(MBD_MBN_DEVICE_REMOVE), "收到4G网卡拔离的内部处理事件"); } BroadcastCableChangedEvent(MBD_MBN_DEVICE_REMOVE); } } break; case USER_EVT_CONNECT_COMPLETE: { Dbg("connect complement! param1(%d)::param2(%d)", pEvt->param1, pEvt->param2); if(pEvt->param2 == ADVANCE_RAS) { if(pEvt->param1 == 0) { Dbg("UserCode:0x%08X, 收到3G网卡已连接的内部处理事件", CombineErrorCode(MBD_RAS_DIALUP_CONNETED)); //LogEvent(Severity_Middle,CombineErrorCode(MBD_RAS_DIALUP_CONNETED),"收到3G网卡已连接的内部处理事件"); } else if(pEvt->param1 == 1) { Dbg("UserCode:0x%08X, 收到3G网卡已连接的外部监听事件", CombineErrorCode(MBD_RAS_DIALUP_CONNETED)); //LogEvent(Severity_Middle,CombineErrorCode(MBD_RAS_DIALUP_CONNETED),"收到3G网卡已连接的外部监听事件"); } else if(pEvt->param1 == -1) { Dbg("UserCode:0x%08X, 收到3G网卡连接失败的外部监听事件", CombineErrorCode(MBD_RAS_DIALUP_CONNETED)); //LogEvent(Severity_Middle,CombineErrorCode(MBD_RAS_DIALUP_CONNETED),"收到3G网卡连接失败的外部监听事件"); break; } BroadcastCableChangedEvent(MBD_RAS_DIALUP_CONNETED); } else if(pEvt->param2 <= 1 && pEvt->param2 >= -1) { if(pEvt->param1 == 0) { if(pEvt->param2) { Dbg("UserCode:0x%08X, 收到4G网卡拨号连接的 MBN 事件", CombineErrorCode(MBD_MBN_DIALUP_CONNETED)); BroadcastCableChangedEvent(MBD_MBN_DIALUP_CONNETED); break; } } else if(pEvt->param1 == -1) { break; } BroadcastCableChangedEvent(MBD_CABLE_DIALUP_CONNETED); } else { BroadcastCableChangedEvent(MBD_CABLE_DIALUP_CONNETED); } } break; case USER_EVT_DISCONNECT_COMPLETE: {// let the FSM(s5) do this [4/15/2020 18:59 @Gifur] if(pEvt->param2 == ADVANCE_RAS && pEvt->param1 == 1) { Dbg("UserCode:0x%08X, 收到3G网卡连接断开的外部监听事件", CombineErrorCode(MBD_RAS_DIALUP_DISCONNETED)); //LogEvent(Severity_Middle,CombineErrorCode(MBD_RAS_DIALUP_DISCONNETED),"收到3G网卡连接断开的外部监听事件"); //BroadcastCableChangedEvent(MBD_RAS_DIALUP_DISCONNETED); } if(pEvt->param2 == ADVANCE_MBN) { Dbg("UserCode:0x%08X, 收到4G网卡连接断开事件", CombineErrorCode(MBD_MBN_DIALUP_DISCONNETED)); //LogEvent(Severity_Middle,CombineErrorCode(MBD_MBN_DIALUP_DISCONNETED),"收到4G网卡连接断开事件"); BroadcastCableChangedEvent(MBD_MBN_DIALUP_DISCONNETED); } else { //BroadcastCableChangedEvent(MBD_CABLE_DIALUP_DISCONNETED); } } break; case EVT_USER_WIRELESS_STATE: { if(pEvt->param1 == 0) { if(pEvt->param2 == 1) //LogEvent(Severity_Middle, CombineErrorCode(MBD_WLAN_DISCONNECTED), "收到指定WIFI断开连接的事件"); LogError(Severity_Middle, Error_NetBroken, CombineErrorCode(MBD_WLAN_DISCONNECTED), "收到指定WIFI断开连接的事件"); else if(pEvt->param2 == 2) LogWarn(Severity_Middle, Error_Unexpect, CombineErrorCode(MBD_WLAN_CONNECTED), "收到未知WIFI连接的事件"); } else if(pEvt->param1 == 1) { LogEvent(Severity_Middle, CombineErrorCode(MBD_WLAN_CONNECTED), "收到指定WIFI连接的事件"); } } break; } } int CMobileDialFSM::DealMBBConfigUpdate(BOOL fCheckOnly) { LOG_FUNCTION(); int ec = 0; bool fFirstLogin = false; MBBParams defaultParam; MBBParams* paramPtr = NULL; if(fCheckOnly) { paramPtr = &defaultParam; } else { paramPtr = &mMBBParam; } // 1: write to device, // 2: update from device // 3: both save and need to update the login password. int nNeedConfig = 0; if(fCheckOnly || m_HwDeviceMnt->detect_devices()) { GetMBBConfig(paramPtr); bool fEmptyParam = false; if(paramPtr->loginParam.strUsername.IsNullOrEmpty() || paramPtr->loginParam.strPassword.IsNullOrEmpty()) { paramPtr->loginParam.strUsername = DEFAULT_MIFI_LOGIN_USERNAME; paramPtr->loginParam.strPassword = DEFAULT_PASSWORD_PREFIX; LOG_ASSERT(!m_strTerminalNo.IsNullOrEmpty()); paramPtr->loginParam.strPassword += m_strTerminalNo.SubString(0, 6); Dbg("default password."); fEmptyParam = true; bool firstLogin; LOG_ASSERT(!m_HwDeviceMnt->has_login(firstLogin)); } int res = 0; res = _LoginMBBDevice(*paramPtr); if(res == -10) { Dbg("detect it's invalid certificate."); Sleep(100); res = _LoginMBBDevice(*paramPtr); } if(res == -3) { if(!IsMIFI3()) { paramPtr->loginParam.strPassword = DEFAULT_MIFI_LOGIN_PASSWORD; res = _LoginMBBDevice(*paramPtr); //if(res == -3) { // Dbg("use backup default password."); // paramPtr->loginParam.strPassword = DEFAULT_MIFI_LOGIN_PASSWORD_BACKUP; // res = _LoginMBBDevice(*paramPtr); //} } else { // 添加对华为MIFI3初始化的处理办法 [7/23/2020 14:49 @Gifur] if(fCheckOnly) { Dbg("detect mifi3 and login failed, check flag return 1"); return 1; } else { Dbg("open CMIFIPswDlg..."); CMIFIPswDlg dlgMain; int nRet = dlgMain.DoModal(); Dbg("open CMIFIPswDlg return: %d %d", nRet, dlgMain.m_strLoginPassword.GetLength()); if(nRet > 0 && dlgMain.m_strLoginPassword.GetLength() != 0) { paramPtr->loginParam.strPassword = (LPCTSTR)dlgMain.m_strLoginPassword; Dbg("user input password: %s", paramPtr->loginParam.strPassword.GetData()); res = _LoginMBBDevice(*paramPtr); } } } if(res == 0) { fFirstLogin = true; } } if(res == 0) { if(!fEmptyParam && !fFirstLogin && paramPtr->customSet) { /*如果是手工添加的配置内容,不做更新操作*/ Dbg("stop from updating mifi config due to customized configure."); return 6; } hw::wlan_config_t wlan_config; res = m_HwDeviceMnt->get_wlan_config(wlan_config); if(res == 0) { CSimpleStringA strSSID(CSimpleStringW2A(wlan_config.ssid)); CSimpleStringA strPassword(CSimpleStringW2A(wlan_config.password)); BOOL fvalidSSID = FALSE; const BOOL fPswEmpty = strPassword.IsNullOrEmpty(); if(strSSID.IndexOf("-") == 10) {//TODO: 判断名称是否符合要求 fvalidSSID = TRUE; CSimpleStringA strThirdTerminalNo = strSSID.SubString(0, 10); LogEvent(Severity_Low, CombineErrorCode(MBD_HOLD_MOBILEDONGLE), CSimpleStringA::Format("the terminal sn in ssid: %s", strThirdTerminalNo.GetData())); if(fPswEmpty) { Dbg("wlan password is empty."); CSimpleStringA strNewPassword(DEFAULT_PASSWORD_PREFIX); strNewPassword += strThirdTerminalNo.SubString(6, strThirdTerminalNo.GetLength() - 6); strPassword = strNewPassword; Dbg("combile the existed password @1"); //Dbg("combile the existed password: %s", strPassword.GetData()); } } if(strSSID.IsStartWith(m_strTerminalNo.GetData())) { //自家的设备 if(strPassword.IsNullOrEmpty()) { Dbg("wlan password is empty."); CSimpleStringA strNewPassword(DEFAULT_PASSWORD_PREFIX); strNewPassword += m_strTerminalNo.SubString(6, m_strTerminalNo.GetLength() - 6); strPassword = strNewPassword; Dbg("combile the existed password @2"); //Dbg("combile the existed password: %s", strPassword.GetData()); } if((paramPtr->wlanConnectParam.strUsername.Compare(strSSID) != 0 || paramPtr->wlanConnectParam.strPassword.Compare(strPassword) != 0 || wlan_config.hidden != (!!paramPtr->wlanConnectParam.Flag))) { //从设备中写进来 paramPtr->wlanConnectParam.strUsername = strSSID; paramPtr->wlanConnectParam.strPassword = strPassword; paramPtr->wlanConnectParam.Flag = wlan_config.hidden ? TRUE : FALSE; paramPtr->connectType = MBB_CONNECT_WIFI; nNeedConfig = 2; } } else if(fvalidSSID) { //他家的设备 Dbg("the third terminal sn."); if(strSSID.Compare(paramPtr->wlanConnectParam.strUsername) != 0 || strPassword.Compare(paramPtr->wlanConnectParam.strPassword) != 0 || wlan_config.hidden != (!!paramPtr->wlanConnectParam.Flag)) { paramPtr->wlanConnectParam.strUsername = strSSID; paramPtr->wlanConnectParam.strPassword = strPassword; paramPtr->wlanConnectParam.Flag = wlan_config.hidden ? TRUE : FALSE; paramPtr->connectType = MBB_CONNECT_WIFI; nNeedConfig = 2; } if(fPswEmpty) { LogWarn(Severity_Middle, Error_Unexpect, CombineErrorCode(MBD_MIFI_NO_DATA), "尝试获取WLAN密码失败,该设备不支持共享使用!"); } } else { //新的设备(有可能) CSimpleStringA strNewSSID(m_strTerminalNo.GetData()); CSimpleStringA strNewPassword(DEFAULT_PASSWORD_PREFIX); strNewPassword += m_strTerminalNo.SubString(6, m_strTerminalNo.GetLength() - 6); hw::dev_info_t dev_info; int get_dev_res = m_HwDeviceMnt->get_dev_info(dev_info); if(get_dev_res == 0) { CSimpleStringA strDevName(CSimpleStringW2A(dev_info.dev_name)); const int index_dev = strDevName.IndexOf("-"); strNewSSID += "-"; if(index_dev != -1) { strNewSSID += strDevName.SubString(0, index_dev); } else { strNewSSID += strDevName; } } else { Dbg("get dev info faiiled: %d", get_dev_res); strNewSSID += "-MIFI"; } paramPtr->wlanConnectParam.strUsername = strNewSSID; paramPtr->wlanConnectParam.strPassword = strNewPassword; paramPtr->wlanConnectParam.Flag = TRUE; Dbg("new ssid name: %s", paramPtr->wlanConnectParam.strUsername.GetData()); //Dbg("new password: %s", paramPtr->wlanConnectParam.strPassword.GetData()); paramPtr->connectType = MBB_CONNECT_WIFI; nNeedConfig = 3; } if((nNeedConfig & 2) == 0 && fEmptyParam) { nNeedConfig |= 2; } if(fFirstLogin) { //密码要更新 nNeedConfig |= 4; } ////////////////////////////////////////////////////////////////////////// if(!!nNeedConfig) { ec = 1; } if(!fCheckOnly) { if(0 != _UpdateMBBDualParam(nNeedConfig, *paramPtr)) { ec = 4; } else if(_InsertLocal2MacFilter() != Error_Succeed){ //MIFI3必须在更改了密码之后才能插入过滤白名单 //Always return Succeed. ec = 6; } } else { Dbg("only check this time."); if(fFirstLogin || fEmptyParam) { Dbg("logout returned: %d.", m_HwDeviceMnt->logout()); } } } else { Dbg("get wlan config failed: %d", res); ec = 2; } } else { Dbg("login failed: %d", res); if(-17 == res) { //LogWarn(Severity_Middle, Error_Unexpect, CombineErrorCode(MBBResult2Status(res)), // "尝试登录MIFI失败次数超限,请拔离设备10分钟再试"); ShowFatalError("尝试登录MIFI失败次数超限,请拔离设备10分钟后再试,或直接重置设备!"); Sleep(10000); } else { LogWarn(Severity_Middle, Error_Unexpect, CombineErrorCode(MBBResult2Status(res)), CSimpleStringA::Format("尝试登录到 MIFI 设备失败(%s)!", ConvertStatusToString(MBBResult2Status(res)))); } //SetHWStatus(MBBResult2Status(res)); if(res == -3) { //SetHWStatus(MBD_MIFI_LOGIN_INVALID_NAMEORPASSWORD); //ShowFatalError(GetFurtherDetail()); //SendNetStatusMsg(); ec = 5; } else { ec = 3; } } } else { Dbg("no detect device"); ec = 4; } return ec; } BOOL CMobileDialFSM::DetectMBBConfigUpdate(BOOL fNeedCheck) { static BOOL fFirstFlag = TRUE; if((m_nAdvancedGen != ADVANCE_MBB || mMBBParam.connectType != MBB_CONNECT_WIRE) && !IsWifiConnected()) { if(!fNeedCheck || m_HwDeviceMnt->detect_devices()) { int res = 1; if(fFirstFlag && (res = DealMBBConfigUpdate(TRUE)) == 1) { return TRUE; } else if(fFirstFlag && res == 0) { fFirstFlag = FALSE; } } else if(!fFirstFlag) { fFirstFlag = TRUE; } } return FALSE; } void CMobileDialFSM::ForbidAutoConnnectBySystem() { LOG_FUNCTION(); HKEY hKey = NULL; HKEY hSubKey = NULL; HKEY hSvcKey = NULL; BOOL fNeedCheck = FALSE; BOOL fEnableSet = FALSE; DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS; if (gArch == 64/*Win64Bit*/) { dwFlag |= KEY_WOW64_64KEY; } else { dwFlag |= KEY_WOW64_32KEY; } LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Policies\\Microsoft\\Windows"), 0, dwFlag, &hKey); if(lResult == ERROR_SUCCESS) { lResult = RegOpenKeyEx(hKey, "WwanSvc\\GroupPolicy", 0, dwFlag, &hSubKey); if(lResult == ERROR_FILE_NOT_FOUND) { DWORD dwDisposition = REG_OPENED_EXISTING_KEY; Dbg("Start to create \"WwanSvc\\GroupPolicy\" key..."); lResult = RegCreateKeyEx(hKey, "WwanSvc\\GroupPolicy", 0, NULL,REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hSubKey, &dwDisposition); Dbg("Create it return %d", lResult); } if(lResult == ERROR_SUCCESS) { DWORD dwType = REG_DWORD; DWORD dwValue = 0; DWORD dwSize = sizeof(dwValue); lResult = RegQueryValueEx(hSubKey, "DisableWwanAutoConnect", NULL, &dwType, (LPBYTE)&dwValue, &dwSize); if(lResult == ERROR_FILE_NOT_FOUND || (lResult == ERROR_SUCCESS && dwValue == 0)) { fNeedCheck = TRUE; } else { Dbg("needless to check: result:%d, value:%d", lResult, dwValue); } } } else { Dbg("RegOpenKeyEx \"SOFTWARE\\Policies\\Microsoft\\Windows\" failed %d", lResult); } if(fNeedCheck) { lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\WwanSvc\\DisallowAutoConnectByClient"), 0, dwFlag, &hSvcKey); if(lResult == ERROR_FILE_NOT_FOUND) { fEnableSet = TRUE; } else if(lResult == ERROR_SUCCESS) { DWORD dwClass = 0; DWORD dwCount = 0, dwSubKeys = 0; lResult = RegQueryInfoKey(hSvcKey, NULL, &dwClass, NULL, &dwSubKeys, NULL, NULL, &dwCount, NULL, NULL, NULL, NULL); if(lResult != ERROR_SUCCESS) { fEnableSet = FALSE; } else if(dwCount > 0) { Dbg("Number of subValue: %d", dwCount); char szValue[128]; DWORD dwLen = sizeof(szValue); DWORD dwValue = 0; DWORD dwSize = sizeof(dwValue); DWORD dwType = REG_DWORD; for(int i=0; lResult == ERROR_SUCCESS && i<(int)dwCount; ++i) { memset(szValue, 0, sizeof(szValue)); lResult = RegEnumValue(hSvcKey, i, szValue, &dwLen, NULL, &dwType, (LPBYTE)&dwValue, &dwSize); if(lResult == ERROR_SUCCESS) { Dbg("RegEnumValue: %s - %d", szValue, dwValue); if(dwValue > 0) { Dbg("Because..."); fEnableSet = FALSE; } } } } else { fEnableSet = TRUE; } } } if(fEnableSet) { DWORD dwType = REG_DWORD; DWORD dwValue = 1; DWORD dwSize = sizeof(dwValue); lResult = RegSetValueEx(hSubKey, "DisableWwanAutoConnect", 0, REG_DWORD, (const BYTE*)&dwValue, dwSize); if(lResult == ERROR_SUCCESS) { Dbg("RegSetValueEx for DisableWwanAutoConnect succ."); } else { Dbg("RegSetValueEx for DisableWwanAutoConnect failed, %d", lResult); } } RegCloseKey(hKey); RegCloseKey(hSvcKey); RegCloseKey(hSubKey); } const MOBILEDIAL_CONNECTION_STATE& CMobileDialFSM::GetRasStatus() const { return m_3gState; } BOOL CMobileDialFSM::RasHangUpSuffix(BOOL bOrigin) { LOG_FUNCTION(); BOOL fResult = TRUE; if(g_hrasconn != NULL) { DWORD dwRet = 0; dwRet = RasHangUp(g_hrasconn); Dbg("RasHangUp in DisConnect returned %d", dwRet); if(dwRet == ERROR_SUCCESS) { RASCONNSTATUS connStatus; connStatus.dwSize = sizeof(RASCONNSTATUS); Dbg("TickCount allocated 3 seconds after RasHangUp..."); //Reduce timeout tick in case occuring //UnLoading-Entity -Josephus@2017627 16:54:10 DWORD tcLast = GetTickCount() + 3 * 1100; while((( dwRet = RasGetConnectStatus(g_hrasconn, &connStatus)) != ERROR_INVALID_HANDLE) && (tcLast > GetTickCount())) { Sleep(0); } fResult = (dwRet == ERROR_INVALID_HANDLE); Dbg("Cycle is done %snormally", fResult ? "" : "ab"); } else { if(dwRet == ERROR_INVALID_HANDLE) { Dbg("to RasHandup: The handle specified in RashandUp is invalid."); } else if(dwRet == ERROR_NO_CONNECTION) { Dbg("to RasHandup: The connection was dropped."); } else { Dbg("Invoke RasHangUp failed returned: %d", dwRet); } fResult = FALSE; } g_hrasconn = NULL; } else { m_csErrMsg = "RAS句柄不存在"; fResult = FALSE; } return fResult; } int CMobileDialFSM::EnumCurRasDevices(BOOL bUpdate) { if(m_nAdvancedGen == 4 || m_nAdvancedGen == 2) { return 0; } LOG_FUNCTION(); Dbg("bUpdate: %d", bUpdate); int nRes = 0; DWORD dwCb = 0; DWORD dwRet = ERROR_SUCCESS; DWORD dwDevices = 0; LPRASDEVINFO lpRasDevInfo = NULL; dwRet = RasEnumDevices(lpRasDevInfo, &dwCb, &dwDevices); if (dwRet == ERROR_BUFFER_TOO_SMALL) { lpRasDevInfo = (LPRASDEVINFO)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb); if (lpRasDevInfo == NULL) { Dbg("HeapAlloc failed when enuming ras devices."); SetRasStatus(MBD_INTERNAL_ERROR); return -1; } lpRasDevInfo[0].dwSize = sizeof(RASDEVINFO); dwRet = RasEnumDevices(lpRasDevInfo, &dwCb, &dwDevices); if (ERROR_SUCCESS == dwRet) { for (DWORD i = 0; i < dwDevices; i++) { if(!_strnicmp(lpRasDevInfo[i].szDeviceType, RASDT_Modem, strlen(RASDT_Modem))) { nRes++; if(!bUpdate) { Dbg("%s <%s>",lpRasDevInfo[i].szDeviceName,lpRasDevInfo[i].szDeviceType); } } } Dbg("The above RAS devices were found(%d)", nRes); if(nRes > 0) { if(bUpdate) { int nEntryNum = RefreshRasEntry(); Dbg("nEntryNum(%d) vs Count(%d)", nEntryNum, m_rasEntries.GetCount()); DongleList donglist; donglist.Init(nRes); Dbg("Dream device count: %d", nRes); bool fHasCfg = false; DWORD k = 0; for (DWORD i = 0; i < dwDevices; i++) { if(!_strnicmp(lpRasDevInfo[i].szDeviceType, RASDT_Modem, strlen(RASDT_Modem))) { Dbg("%s <%s>",lpRasDevInfo[i].szDeviceName,lpRasDevInfo[i].szDeviceType); memset(&donglist[k], 0, sizeof(MbnDongleInfo)); donglist[k].usDeviceType = DEVTYPE_MODEM; //TODO: donglist[k].csInterfaceId = lpRasDevInfo[i].szDeviceName; InitMbnDongleSubInfo(&donglist[k].subInfo); donglist[k].subInfo.ulSingnal = 0xFFFFFFFF; donglist[k].subInfo.strProviderName = lpRasDevInfo[i].szDeviceName; donglist[k].subInfo.mbnCntState = MBN_ACTIVATION_STATE_DEACTIVATED; donglist[k].subInfo.strProfileName = ""; donglist[k].state = /*MBD_NOT_INITIALIZED*/MBD_ACTIVATION_DISCONNECTED; int num = 0; for(int j=0; j 0) { donglist[k].profileList.Init(num); for(int j=0, z=0; j= 1) { Dbg("The operation failed to acquire the buffer size."); SetRasStatus(MBD_INTERNAL_ERROR); return -1; } Dbg("There were no RAS devices found."); SetRasStatus(MBD_NO_MOBILEDONGLE); return 0; } BOOL CMobileDialFSM::Init3GComponent() { bool bContinue = true; for(int i=0; iAdviseCntMnrEvent(); m_pMbn->AdviseConnectEvent(); m_pMbn->AdviseSignalEvent(); m_pMbn->AdviseCntProfileMnrEvent(); m_pMbn->AdviseCntProfileEvent(); } return TRUE; } BOOL CMobileDialFSM::InitHuaweiComponent() { GetMBBConfig(&mMBBParam); Dbg("connect type: %d", mMBBParam.connectType); Dbg("username: %s", (LPCTSTR)mMBBParam.loginParam.strUsername); Dbg("ssid: %s", (LPCTSTR)mMBBParam.wlanConnectParam.strUsername); if(m_WifiChangedEvt == NULL) { spagent::spagent_assistor::init("mobile"); m_WifiChangedEvt = new WifiChangeEvent(this); if(mMBBParam.connectType == MBB_CONNECT_WIRE) { spagent::spagent_assistor::disconnect(conn_tool_wifi, true); } } if(!m_WifiChangedEvt->m_bRegistered) { int rc = spagent::spagent_assistor::register_notification_events(conn_tool_wifi, m_WifiChangedEvt); Dbg("Register wifi changed event return: %d", rc); m_WifiChangedEvt->m_bRegistered = rc == 0 ? TRUE : FALSE; } return TRUE; } BOOL CMobileDialFSM::IsWifiConnected() { std::string ssid; return spagent::spagent_assistor::is_connected(conn_tool_wifi, ssid) ? TRUE : FALSE; } void CMobileDialFSM::_FormatRasError(DWORD dwRasCode) { DWORD cBufSize = 256; char lpszBuf[256] = {0}; DWORD dwRetVal = RasGetErrorString((UINT)dwRasCode, lpszBuf, cBufSize); if(dwRetVal == ERROR_SUCCESS) { LogError(Severity_Middle, Error_Unrecover, CombineErrorCode(MBD_RASDIAL_FAILED), CSimpleStringA::Format("错误 %d:%s", dwRasCode, lpszBuf)); m_csErrMsg = CSimpleStringA::Format("%s : %d", lpszBuf, dwRasCode); }else { m_csErrMsg = CSimpleStringA::Format("RasDial failed: %u", dwRasCode); LogError(Severity_Middle, Error_Unrecover, CombineErrorCode(MBD_RASDIAL_FAILED), CSimpleStringA::Format("3G拨号失败:%u", dwRasCode)); } } int CMobileDialFSM::CheckNetSituationWithPing() { int nRes = 0; if((ping1 == NULL || !ping1->IsValid()) && (ping2 == NULL || !ping2->IsValid())) return -1; int t1 = 0, t2 = 0; const int max_times = 4; if(ping1 != NULL && ping1->IsValid()) { for(t1=0; t1PingOnce() == 0) { nRes += 1; break; } Sleep(1000); } } if(ping2 != NULL && ping2->IsValid()) { for(t2=0; t2PingOnce() == 0) { nRes += 2; break; } } } return nRes; }