📄 connectionmanagerimp.cs
字号:
namespace Imps.Client.CommLayer
{
using Imps.Client.Base;
using Imps.Client.CommLayer.HTSipConnection;
using Imps.Client.CommLayer.HttpSipConnection;
using Imps.Client.CommLayer.SocksSipConnection;
using Imps.Client.CommLayer.TcpSipConnection;
using Imps.Client.Core;
using Imps.Client.Resource;
using Imps.Client.Utils;
using Imps.Common;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
public class ConnectionManagerImp : IConnectionManager
{
private bool _doTcpTestSuccessed;
private ManualResetEvent _tcpTestWaitEvent;
private Imps.Client.Core.User _User;
private string _userAgent;
private IWebProxy _webProxy;
private const string HOST_REGEX_STRING = @"^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$";
private volatile bool IsHttpConnectionInitialized;
private const int MAX_NETBIOS_NAME_LENGTH = 15;
private const string NETBIOS_REGEX = @"^[a-zA-Z0-9\-]{1,15}$";
private const string NoExistMobileNo = "13910000000";
public event HttpConnectionModeChangedDelegate ConnectionModeChanged;
public ConnectionManagerImp(Imps.Client.Core.User user)
{
if (user == null)
{
throw new ArgumentNullException("user");
}
this._User = user;
Imps.Client.Core.NetworkSetting.Instance.Changed += new EventHandler(this.Instance_Changed);
ServicePointManager.set_ServerCertificateValidationCallback(new RemoteCertificateValidationCallback(null, (IntPtr) ValidateSSLCert));
this._userAgent = string.Format("IIC2.0/PC {0}", Imps.Client.Core.Configuration.FixedClientSetting.Version);
}
public static bool AreAllCharsNumber(string s)
{
if (string.IsNullOrEmpty(s))
{
return false;
}
foreach (char ch in s)
{
if (!char.IsNumber(ch))
{
return false;
}
}
return true;
}
public HttpWebRequest CreateHttpWebRequest(string url, object context, bool doPost, bool withCookie)
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.UserAgent = this._userAgent;
if (doPost)
{
request.Method = "POST";
}
request.Proxy = this.WebProxy;
if (withCookie)
{
CookieCollection cookies = new CookieCollection();
Cookie cookie = new Cookie("ssic", this._User.SsiCredential);
cookies.Add(cookie);
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(request.RequestUri, cookies);
}
request.ServicePoint.Expect100Continue = false;
return request;
}
public ISipConnection CreateSipConnection(object context)
{
string detail = string.Empty;
Imps.Client.Core.NetworkSetting instance = Imps.Client.Core.NetworkSetting.Instance;
SipConnectionImp myImp = new SipConnectionImp(context);
if (Imps.Client.Core.FixedClientSetting.Instance.Debug_TestHttpConnection)
{
HttpSipConnectionOption option = new HttpSipConnectionOption();
option.HttpTurnal = this._User.Configuration.SystemSetting.ServerUriSetting.UriHttpTunnel;
myImp.RegisterConnectionType(typeof(Imps.Client.CommLayer.HttpSipConnection.HttpSipConnection), option);
detail = detail + "HttpSipConnection: HttpTunnel=" + option.HttpTurnal + " (No Proxy) \r\n";
}
else
{
TcpSipConnectionOption option2 = new TcpSipConnectionOption(this._User.Configuration.SystemSetting.ServerUriSetting);
if (instance.UseDirect)
{
myImp.RegisterConnectionType(typeof(Imps.Client.CommLayer.TcpSipConnection.TcpSipConnection), option2);
detail = detail + "TcpSipConnection: (No Parameters) \r\n";
}
this.RegHTSipConnection(myImp, option2);
HttpSipConnectionOption option3 = new HttpSipConnectionOption();
option3.HttpTurnal = this._User.Configuration.SystemSetting.ServerUriSetting.UriHttpTunnel;
myImp.RegisterConnectionType(typeof(Imps.Client.CommLayer.HttpSipConnection.HttpSipConnection), option3);
object obj2 = detail;
detail = string.Concat(new object[] { obj2, "HttpSipConnection: HttpTunnel=", option3.HttpTurnal, " ProxyHost=", CommHelper.GetProxyHost(this.WebProxy), " ProxyPort=", CommHelper.GetProxyPort(this.WebProxy), " \r\n" });
}
ClientLogger.WriteConnection("ConnectionList", 0, detail, 0);
return myImp;
}
internal static void DoCallBack(TestConnectionCallBack callback, TestConnectionStatus status, string desc)
{
if (callback != null)
{
callback(status, desc);
}
}
private static IWebProxy FixWebProxy()
{
Imps.Client.Core.NetworkSetting instance = Imps.Client.Core.NetworkSetting.Instance;
return FixWebProxy(instance.HttpProxy.ServerUri, instance.HttpProxy.ServerPort, instance.HttpProxy.UserName, instance.HttpProxy.Password, instance.UseDirect, instance.UseHttpProxy, instance.UseIeProxy);
}
private static IWebProxy FixWebProxy(string proxyHost, int proxyPort, string username, string password, bool useDirect, bool useHttpProxy, bool useIeProxy)
{
Trace.WriteLine(string.Format("[{0:HH-mm-ss.ffff}]FixWebProxy - useDirect={1}, useHttpProxy={2}, useIeProxy={3}", new object[] { DateTime.Now, useDirect, useHttpProxy, useIeProxy }));
Imps.Client.Core.NetworkSetting instance = Imps.Client.Core.NetworkSetting.Instance;
if (useDirect && (!instance.UseHttpProxy || TestWebProxy(null)))
{
return null;
}
if (!useHttpProxy)
{
return null;
}
if (string.IsNullOrEmpty(proxyHost) && !useIeProxy)
{
return null;
}
IWebProxy proxy = useIeProxy ? WebRequest.get_DefaultWebProxy() : new System.Net.WebProxy(proxyHost, proxyPort);
if (!string.IsNullOrEmpty(username) && instance.UseHttpProxy)
{
int length = username.IndexOf('\\');
if (length >= 0)
{
proxy.Credentials = new NetworkCredential(username.Substring(length + 1), password, username.Substring(0, length));
return proxy;
}
proxy.Credentials = new NetworkCredential(username, password);
return proxy;
}
proxy.Credentials = CredentialCache.get_DefaultNetworkCredentials();
return proxy;
}
public void Instance_Changed(object sender, EventArgs e)
{
this.Reset();
}
private void LogProxyInfo()
{
try
{
if (this._webProxy != null)
{
Uri proxy = this._webProxy.GetProxy(new Uri(Imps.Client.Core.Configuration.FixedClientSetting.TestConnectionUrl));
ClientLogger.WriteGeneral("Http proxy setting", string.Format("Proxy address - {0}:{1}\r\nUser name - [{2}]", proxy.Host, proxy.Port, Imps.Client.Core.NetworkSetting.Instance.HttpProxy.UserName));
}
}
catch
{
}
}
private static void LogTestHttpProxy(IWebProxy webProxy, bool successed)
{
string detail = "(No Proxy)";
if (webProxy != null)
{
if (webProxy == WebRequest.get_DefaultWebProxy())
{
detail = "使用浏览器默认代理";
}
else if (webProxy is System.Net.WebProxy)
{
System.Net.WebProxy proxy = (System.Net.WebProxy) webProxy;
detail = proxy.Address.ToString();
}
}
if (successed)
{
ClientLogger.WriteGeneral("测试Http代理成功 : ", detail);
}
else
{
ClientLogger.WriteGeneral("测试Http代理失败 : ", detail);
}
}
private bool QueryNavigator(out string serverHost, out int serverPort, IWebProxy webProxy)
{
string httpTurnal;
string ssiUrl;
return this.QueryNavigator(out serverHost, out serverPort, out httpTurnal, out ssiUrl, webProxy);
}
private bool QueryNavigator(out string serverHost, out int serverPort, out string httpTurnal, out string ssiUrl, IWebProxy webProxy)
{
serverHost = string.Empty;
serverPort = 0;
httpTurnal = string.Empty;
ssiUrl = string.Empty;
try
{
HttpWebRequest request = this.CreateHttpWebRequest(Imps.Client.Core.FixedClientSetting.Instance.NavigatorServerUri, null, true, false);
request.Proxy = webProxy;
using (Stream w = request.GetRequestStream())
{
XmlTextWriter writer = new XmlTextWriter(w, Encoding.UTF8);
writer.WriteStartElement("config");
writer.WriteStartElement("user");
writer.WriteAttributeString("mobile-no", "13910000000");
writer.WriteEndElement();
writer.WriteStartElement("client");
writer.WriteAttributeString("type", "PC");
writer.WriteAttributeString("version", Imps.Client.Core.Configuration.FixedClientSetting.Version);
writer.WriteAttributeString("platform", EnvHelper.GetOsString());
writer.WriteEndElement();
writer.WriteStartElement("servers");
writer.WriteAttributeString("version", "0");
writer.WriteEndElement();
writer.WriteEndElement();
writer.Flush();
}
using (HttpWebResponse response = ((HttpWebResponse) request.GetResponse()))
{
using (Stream stream2 = response.GetResponseStream())
{
XmlReader reader = XmlReader.Create(stream2);
reader.ReadToFollowing("servers");
while (reader.Read())
{
string name;
if ((reader.NodeType == XmlNodeType.Element) && ((name = reader.Name) != null))
{
if (name != "http-tunnel")
{
if (name == "sipc-proxy")
{
goto Label_016F;
}
if (name == "ssi-app-sign-in")
{
goto Label_01A0;
}
}
else
{
httpTurnal = reader.ReadString();
}
}
continue;
Label_016F:;
string[] textArray = reader.ReadString().Split(new char[] { ':' });
serverHost = textArray[0];
serverPort = int.Parse(textArray[1]);
continue;
Label_01A0:
ssiUrl = reader.ReadString();
}
}
}
return true;
}
catch
{
return false;
}
}
private static bool QueryTestPage(string orgUrl, IWebProxy webProxy, bool hasTestPage)
{
if (string.IsNullOrEmpty(orgUrl))
{
throw new ArgumentNullException("orgUrl");
}
string requestUriString = orgUrl;
if (hasTestPage)
{
requestUriString = orgUrl.Substring(0, orgUrl.LastIndexOf('/') + 1) + "tc.htm";
}
try
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(requestUriString);
request.Proxy = webProxy;
request.KeepAlive = false;
((HttpWebResponse) request.GetResponse()).Close();
return true;
}
catch (Exception)
{
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -