/// <summary> /// Проверяет различные параметры прокси-клиента на ошибочные значения. /// </summary> /// <exception cref="System.InvalidOperationException">Значение свойства <see cref="Host"/> равно <see langword="null"/> или имеет нулевую длину.</exception> /// <exception cref="System.InvalidOperationException">Значение свойства <see cref="Port"/> меньше 1 или больше 65535.</exception> /// <exception cref="System.InvalidOperationException">Значение свойства <see cref="Username"/> имеет длину более 255 символов.</exception> /// <exception cref="System.InvalidOperationException">Значение свойства <see cref="Password"/> имеет длину более 255 символов.</exception> protected void CheckState() { if (string.IsNullOrEmpty(_host)) { throw new InvalidOperationException( "The host may be uncertain or have zero length."); } if (!ExceptionHelper.ValidateTcpPort(_port)) { throw new InvalidOperationException( "The port can not be less than 1 or greater than 65535."); } if (_username != null && _username.Length > 255) { throw new InvalidOperationException( "User name can not be more than 255 characters."); } if (_password != null && _password.Length > 255) { throw new InvalidOperationException( "The password can not be more than 255 characters."); } }
/// <summary> /// Проверяет различные параметры прокси-клиента на ошибочные значения. /// </summary> /// <exception cref="System.InvalidOperationException">Значение свойства <see cref="Host"/> равно <see langword="null"/> или имеет нулевую длину.</exception> /// <exception cref="System.InvalidOperationException">Значение свойства <see cref="Port"/> меньше 1 или больше 65535.</exception> /// <exception cref="System.InvalidOperationException">Значение свойства <see cref="Username"/> имеет длину более 255 символов.</exception> /// <exception cref="System.InvalidOperationException">Значение свойства <see cref="Password"/> имеет длину более 255 символов.</exception> protected void CheckState() { if (string.IsNullOrEmpty(_host)) { throw new InvalidOperationException( Resources.InvalidOperationException_ProxyClient_WrongHost); } if (!ExceptionHelper.ValidateTcpPort(_port)) { throw new InvalidOperationException( Resources.InvalidOperationException_ProxyClient_WrongPort); } if (_username != null && _username.Length > 255) { throw new InvalidOperationException( Resources.InvalidOperationException_ProxyClient_WrongUsername); } if (_password != null && _password.Length > 255) { throw new InvalidOperationException( Resources.InvalidOperationException_ProxyClient_WrongPassword); } }
public override TcpClient CreateConnection( string destinationHost, int destinationPort, TcpClient tcpClient = null) { this.CheckState(); if (destinationHost == null) { throw new ArgumentNullException(nameof(destinationHost)); } if (destinationHost.Length == 0) { throw ExceptionHelper.EmptyString(nameof(destinationHost)); } if (!ExceptionHelper.ValidateTcpPort(destinationPort)) { throw ExceptionHelper.WrongTcpPort(nameof(destinationPort)); } TcpClient tcpClient1 = tcpClient ?? this.CreateConnectionToProxy(); try { this.SendCommand(tcpClient1.GetStream(), (byte)1, destinationHost, destinationPort); } catch (Exception ex) { tcpClient1.Close(); if (ex is IOException || ex is SocketException) { throw this.NewProxyException(Resources.ProxyException_Error, ex); } throw; } return(tcpClient1); }
/// <summary> /// Создаёт соединение с сервером через прокси-сервер. /// </summary> /// <param name="destinationHost">Хост сервера, с которым нужно связаться через прокси-сервер.</param> /// <param name="destinationPort">Порт сервера, с которым нужно связаться через прокси-сервер.</param> /// <param name="tcpClient">Соединение, через которое нужно работать, или значение <see langword="null"/>.</param> /// <returns>Соединение с сервером через прокси-сервер.</returns> /// <exception cref="System.InvalidOperationException"> /// Значение свойства <see cref="Host"/> равно <see langword="null"/> или имеет нулевую длину. /// -или- /// Значение свойства <see cref="Port"/> меньше 1 или больше 65535. /// -или- /// Значение свойства <see cref="Username"/> имеет длину более 255 символов. /// -или- /// Значение свойства <see cref="Password"/> имеет длину более 255 символов. /// </exception> /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="destinationHost"/> равно <see langword="null"/>.</exception> /// <exception cref="System.ArgumentException">Значение параметра <paramref name="destinationHost"/> является пустой строкой.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Значение параметра <paramref name="destinationPort"/> меньше 1 или больше 65535.</exception> /// <exception cref="xNet.Net.ProxyException">Ошибка при работе с прокси-сервером.</exception> public override TcpClient CreateConnection(string destinationHost, int destinationPort, TcpClient tcpClient = null) { CheckState(); #region Проверка параметров if (destinationHost == null) { throw new ArgumentNullException("destinationHost"); } if (destinationHost.Length == 0) { throw ExceptionHelper.EmptyString("destinationHost"); } if (!ExceptionHelper.ValidateTcpPort(destinationPort)) { throw ExceptionHelper.WrongTcpPort("destinationPort"); } #endregion TcpClient curTcpClient = tcpClient; if (curTcpClient == null) { curTcpClient = CreateConnectionToProxy(); } try { NetworkStream nStream = curTcpClient.GetStream(); InitialNegotiation(nStream); SendCommand(nStream, CommandConnect, destinationHost, destinationPort); } catch (Exception ex) { curTcpClient.Close(); if (ex is IOException || ex is SocketException) { throw NewProxyException("An error occurred while working with the proxy server '{0}'.", ex); } throw; } return(curTcpClient); }
/// <summary> /// Преобразует строку в экземпляр класса прокси-клиента, унаследованный от <see cref="ProxyClient"/>. Возвращает значение, указывающее, успешно ли выполнено преобразование. /// </summary> /// <param name="proxyType">Тип прокси-сервера.</param> /// <param name="proxyAddress">Строка вида - хост:порт:имя_пользователя:пароль. Три последних параметра являются необязательными.</param> /// <param name="result">Если преобразование выполнено успешно, то содержит экземпляр класса прокси-клиента, унаследованный от <see cref="ProxyClient"/>, иначе <see langword="null"/>.</param> /// <returns>Значение <see langword="true"/>, если параметр <paramref name="proxyAddress"/> преобразован успешно, иначе <see langword="false"/>.</returns> public static bool TryParse(ProxyType proxyType, string proxyAddress, out ProxyClient result) { result = null; #region Проверка параметров if (string.IsNullOrEmpty(proxyAddress)) { return(false); } #endregion string[] values = proxyAddress.Split(':'); int port = 0; string host = values[0]; if (values.Length >= 2) { if (!int.TryParse(values[1], out port) || !ExceptionHelper.ValidateTcpPort(port)) { return(false); } } string username = null; string password = null; if (values.Length >= 3) { username = values[2]; } if (values.Length >= 4) { password = values[3]; } try { result = ProxyHelper.CreateProxyClient(proxyType, host, port, username, password); } catch (InvalidOperationException) { return(false); } return(true); }
/// <summary> /// 创建服务器连接代理服务器。 /// </summary> /// <param name="destinationHost">主机服务器,需要通过代理服务器。</param> /// <param name="destinationPort">服务器端口,需要通过代理服务器。</param> /// <param name="tcpClient">在美国工作的需要,或值<see langword="null"/>.</param> /// <returns>与服务器的连接代理。</returns> /// <exception cref="System.InvalidOperationException"> /// 属性值<see cref="Host"/> 等于<see langword="null"/> 或具有零长度。 /// -或- /// 属性值<see cref="Port"/> 少1 或者更多65535. /// -或- /// 属性值<see cref="Username"/> 具有较长255 符号。 /// -或- /// 属性值<see cref="Password"/> 具有较长255 符号。 /// </exception> /// <exception cref="System.ArgumentNullException">参数值<paramref name="destinationHost"/> 等于<see langword="null"/>.</exception> /// <exception cref="System.ArgumentException">参数值<paramref name="destinationHost"/> 是空字符串。</exception> /// <exception cref="System.ArgumentOutOfRangeException">参数值<paramref name="destinationPort"/> 少1 或者更多65535.</exception> /// <exception cref="xNet.Net.ProxyException">错误与代理服务器。</exception> public override TcpClient CreateConnection(string destinationHost, int destinationPort, TcpClient tcpClient = null) { CheckState(); #region 检查参数 if (destinationHost == null) { throw new ArgumentNullException("destinationHost"); } if (destinationHost.Length == 0) { throw ExceptionHelper.EmptyString("destinationHost"); } if (!ExceptionHelper.ValidateTcpPort(destinationPort)) { throw ExceptionHelper.WrongTcpPort("destinationPort"); } #endregion TcpClient curTcpClient = tcpClient; if (curTcpClient == null) { curTcpClient = CreateConnectionToProxy(); } try { SendCommand(curTcpClient.GetStream(), CommandConnect, destinationHost, destinationPort); } catch (Exception ex) { curTcpClient.Close(); if (ex is IOException || ex is SocketException) { throw NewProxyException(Resources.ProxyException_Error, ex); } throw; } return(curTcpClient); }
public static void SetIEProxy(string host, int port) { if (host == null) { throw new ArgumentNullException(nameof(host)); } if (host.Length == 0) { throw ExceptionHelper.EmptyString(nameof(host)); } if (!ExceptionHelper.ValidateTcpPort(port)) { throw ExceptionHelper.WrongTcpPort(nameof(port)); } WinInet.SetIEProxy(host + ":" + port.ToString()); }
public override TcpClient CreateConnection( string destinationHost, int destinationPort, TcpClient tcpClient = null) { this.CheckState(); if (destinationHost == null) { throw new ArgumentNullException(nameof(destinationHost)); } if (destinationHost.Length == 0) { throw ExceptionHelper.EmptyString(nameof(destinationHost)); } if (!ExceptionHelper.ValidateTcpPort(destinationPort)) { throw ExceptionHelper.WrongTcpPort(nameof(destinationPort)); } TcpClient tcpClient1 = tcpClient ?? this.CreateConnectionToProxy(); if (destinationPort != 80) { HttpStatusCode response; try { NetworkStream stream = tcpClient1.GetStream(); this.SendConnectionCommand(stream, destinationHost, destinationPort); response = this.ReceiveResponse(stream); } catch (Exception ex) { tcpClient1.Close(); if (ex is IOException || ex is SocketException) { throw this.NewProxyException(Resources.ProxyException_Error, ex); } throw; } if (response != HttpStatusCode.OK) { tcpClient1.Close(); throw new ProxyException(string.Format(Resources.ProxyException_ReceivedWrongStatusCode, (object)response, (object)this.ToString()), (ProxyClient)this, (Exception)null); } } return(tcpClient1); }
public static ProxyClient Parse(ProxyType proxyType, string proxyAddress) { if (proxyAddress == null) { throw new ArgumentNullException(nameof(proxyAddress)); } if (proxyAddress.Length == 0) { throw ExceptionHelper.EmptyString(nameof(proxyAddress)); } string[] strArray = proxyAddress.Split(':'); int port = 0; string host = strArray[0]; if (strArray.Length >= 2) { try { port = int.Parse(strArray[1]); } catch (Exception ex) { if (ex is FormatException || ex is OverflowException) { throw new FormatException(Resources.InvalidOperationException_ProxyClient_WrongPort, ex); } throw; } if (!ExceptionHelper.ValidateTcpPort(port)) { throw new FormatException(Resources.InvalidOperationException_ProxyClient_WrongPort); } } string username = (string)null; string password = (string)null; if (strArray.Length >= 3) { username = strArray[2]; } if (strArray.Length >= 4) { password = strArray[3]; } return(ProxyHelper.CreateProxyClient(proxyType, host, port, username, password)); }
/// <summary> /// Задаёт значение прокси-сервера Internet Explorer'а. Значение задаётся в реестре. /// </summary> /// <param name="host">Хост прокси-сервера.</param> /// <param name="port">Порт прокси-сервера.</param> /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="host"/> равно <see langword="null"/>.</exception> /// <exception cref="System.ArgumentException">Значение параметра <paramref name="host"/> является пустой строкой.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Значение параметра <paramref name="port"/> меньше 1 или больше 65535.</exception> /// <exception cref="System.Security.SecurityException">У пользователя отсутствуют разрешения, необходимые для создания или открытия раздела реестра.</exception> /// <exception cref="System.ObjectDisposedException">Объект <see cref="Microsoft.Win32.RegistryKey"/>, для которого вызывается этот метод, закрыт (доступ к закрытым разделам невозможен).</exception> /// <exception cref="System.UnauthorizedAccessException">Запись в объект <see cref="Microsoft.Win32.RegistryKey"/> невозможна, например, он не может быть открыт как раздел, доступный для записи, или у пользователя нет необходимых прав доступа.</exception> public static void SetIEProxy(string host, int port) { #region Проверка параметров if (host == null) { throw new ArgumentNullException("host"); } if (host.Length == 0) { throw ExceptionHelper.EmptyString("host"); } if (!ExceptionHelper.ValidateTcpPort(port)) { throw ExceptionHelper.WrongTcpPort("port"); } #endregion SetIEProxy(host + ":" + port.ToString()); }
public static bool TryParse(ProxyType proxyType, string proxyAddress, out ProxyClient result) { result = (ProxyClient)null; if (string.IsNullOrEmpty(proxyAddress)) { return(false); } string[] strArray = proxyAddress.Split(':'); int result1 = 0; string host = strArray[0]; if (strArray.Length >= 2 && (!int.TryParse(strArray[1], out result1) || !ExceptionHelper.ValidateTcpPort(result1))) { return(false); } string username = (string)null; string password = (string)null; if (strArray.Length >= 3) { username = strArray[2]; } if (strArray.Length >= 4) { password = strArray[3]; } try { result = ProxyHelper.CreateProxyClient(proxyType, host, result1, username, password); } catch (InvalidOperationException ex) { return(false); } return(true); }
/// <summary> /// Преобразует строку в экземпляр класса прокси-клиента, унаследованный от <see cref="ProxyClient"/>. /// </summary> /// <param name="proxyType">Тип прокси-сервера.</param> /// <param name="proxyAddress">Строка вида - хост:порт:имя_пользователя:пароль. Три последних параметра являются необязательными.</param> /// <returns>Экземпляр класса прокси-клиента, унаследованный от <see cref="ProxyClient"/>.</returns> /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="proxyAddress"/> равно <see langword="null"/>.</exception> /// <exception cref="System.ArgumentException">Значение параметра <paramref name="proxyAddress"/> является пустой строкой.</exception> /// <exception cref="System.FormatException">Формат порта является неправильным.</exception> /// <exception cref="System.InvalidOperationException">Получен неподдерживаемый тип прокси-сервера.</exception> public static ProxyClient Parse(ProxyType proxyType, string proxyAddress) { #region Проверка параметров if (proxyAddress == null) { throw new ArgumentNullException("proxyAddress"); } if (proxyAddress.Length == 0) { throw ExceptionHelper.EmptyString("proxyAddress"); } #endregion string[] values = proxyAddress.Split(':'); int port = 0; string host = values[0]; if (values.Length >= 2) { #region Получение порта try { port = int.Parse(values[1]); } catch (Exception ex) { if (ex is FormatException || ex is OverflowException) { throw new FormatException( "The port can not be less than 1 or greater than 65535.", ex); } throw; } if (!ExceptionHelper.ValidateTcpPort(port)) { throw new FormatException( "The port can not be less than 1 or greater than 65535."); } #endregion } string username = null; string password = null; if (values.Length >= 3) { username = values[2]; } if (values.Length >= 4) { password = values[3]; } return(ProxyHelper.CreateProxyClient(proxyType, host, port, username, password)); }
/// <summary> /// Создаёт соединение с сервером через прокси-сервер. /// </summary> /// <param name="destinationHost">Хост сервера, с которым нужно связаться через прокси-сервер.</param> /// <param name="destinationPort">Порт сервера, с которым нужно связаться через прокси-сервер.</param> /// <param name="tcpClient">Соединение, через которое нужно работать, или значение <see langword="null"/>.</param> /// <returns>Соединение с сервером через прокси-сервер.</returns> /// <exception cref="System.InvalidOperationException"> /// Значение свойства <see cref="Host"/> равно <see langword="null"/> или имеет нулевую длину. /// -или- /// Значение свойства <see cref="Port"/> меньше 1 или больше 65535. /// -или- /// Значение свойства <see cref="Username"/> имеет длину более 255 символов. /// -или- /// Значение свойства <see cref="Password"/> имеет длину более 255 символов. /// </exception> /// <exception cref="System.ArgumentNullException">Значение параметра <paramref name="destinationHost"/> равно <see langword="null"/>.</exception> /// <exception cref="System.ArgumentException">Значение параметра <paramref name="destinationHost"/> является пустой строкой.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Значение параметра <paramref name="destinationPort"/> меньше 1 или больше 65535.</exception> /// <exception cref="xNet.Net.ProxyException">Ошибка при работе с прокси-сервером.</exception> /// <remarks>Если порт сервера неравен 80, то для подключения используется метод 'CONNECT'.</remarks> public override TcpClient CreateConnection(string destinationHost, int destinationPort, TcpClient tcpClient = null) { CheckState(); #region Проверка параметров if (destinationHost == null) { throw new ArgumentNullException("destinationHost"); } if (destinationHost.Length == 0) { throw ExceptionHelper.EmptyString("destinationHost"); } if (!ExceptionHelper.ValidateTcpPort(destinationPort)) { throw ExceptionHelper.WrongTcpPort("destinationPort"); } #endregion TcpClient curTcpClient = tcpClient; if (curTcpClient == null) { curTcpClient = CreateConnectionToProxy(); } if (destinationPort != 80) { HttpStatusCode statusCode = HttpStatusCode.OK; try { NetworkStream nStream = curTcpClient.GetStream(); SendConnectionCommand(nStream, destinationHost, destinationPort); statusCode = ReceiveResponse(nStream); } catch (Exception ex) { curTcpClient.Close(); if (ex is IOException || ex is SocketException) { throw NewProxyException(Resources.ProxyException_Error, ex); } throw; } if (statusCode != HttpStatusCode.OK) { curTcpClient.Close(); throw new ProxyException(string.Format( Resources.ProxyException_ReceivedWrongStatusCode, statusCode, ToString()), this); } } return(curTcpClient); }
/// <summary> /// 转换字符串类实例的代理客户,继承了<see cref="ProxyClient"/>. /// </summary> /// <param name="proxyType">代理服务器类型。</param> /// <param name="proxyAddress">行看主机:港口:名字_用户:密码。最后的三参数是可选的。</param> /// <returns>客户的代理类实例,继承了<see cref="ProxyClient"/>.</returns> /// <exception cref="System.ArgumentNullException">参数值<paramref name="proxyAddress"/> 等于<see langword="null"/>.</exception> /// <exception cref="System.ArgumentException">参数值<paramref name="proxyAddress"/> 是空字符串。</exception> /// <exception cref="System.FormatException">格式不对。港口是</exception> /// <exception cref="System.InvalidOperationException">获得代理服务器类型中。</exception> public static ProxyClient Parse(ProxyType proxyType, string proxyAddress) { #region 检查参数 if (proxyAddress == null) { throw new ArgumentNullException("proxyAddress"); } if (proxyAddress.Length == 0) { throw ExceptionHelper.EmptyString("proxyAddress"); } #endregion string[] values = proxyAddress.Split(':'); int port = 0; string host = values[0]; if (values.Length >= 2) { #region 接收端口 try { port = int.Parse(values[1]); } catch (Exception ex) { if (ex is FormatException || ex is OverflowException) { throw new FormatException( Resources.InvalidOperationException_ProxyClient_WrongPort, ex); } throw; } if (!ExceptionHelper.ValidateTcpPort(port)) { throw new FormatException( Resources.InvalidOperationException_ProxyClient_WrongPort); } #endregion } string username = null; string password = null; if (values.Length >= 3) { username = values[2]; } if (values.Length >= 4) { password = values[3]; } return(ProxyHelper.CreateProxyClient(proxyType, host, port, username, password)); }