1 // OpenTween - Client of Twitter
2 // Copyright (c) 2014 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
3 // All rights reserved.
5 // This file is part of OpenTween.
7 // This program is free software; you can redistribute it and/or modify it
8 // under the terms of the GNU General Public License as published by the Free
9 // Software Foundation; either version 3 of the License, or (at your option)
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 // You should have received a copy of the GNU General Public License along
18 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
19 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
20 // Boston, MA 02110-1301, USA.
23 using System.Collections.Generic;
24 using System.Diagnostics.CodeAnalysis;
27 using System.Net.Cache;
28 using System.Net.Http;
30 using System.Threading;
31 using System.Threading.Tasks;
33 namespace OpenTween.Connection
35 public static class Networking
37 public static TimeSpan DefaultTimeout { get; set; }
38 public static TimeSpan UploadImageTimeout { get; set; }
43 public static ProxyType ProxyType { get; private set; } = ProxyType.IE;
48 public static IWebProxy Proxy { get; private set; } = null;
51 /// OpenTween 内で共通して使用する HttpClient インスタンス
53 public static HttpClient Http => globalHttpClient;
56 /// pbs.twimg.com で IPv4 を強制的に使用する
58 public static bool ForceIPv4
63 if (forceIPv4 == value)
68 // Network.Http を再作成させる
69 OnWebProxyChanged(EventArgs.Empty);
74 /// Webプロキシの設定が変更された場合に発生します
76 public static event EventHandler WebProxyChanged;
78 private static bool initialized = false;
79 private static HttpClient globalHttpClient;
80 private static bool forceIPv4 = false;
82 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
85 DefaultTimeout = TimeSpan.FromSeconds(20);
86 UploadImageTimeout = TimeSpan.FromSeconds(60);
87 globalHttpClient = CreateHttpClient(new HttpClientHandler());
91 /// ネットワーク接続前に行う処理。起動時に一回だけ実行する必要があります。
93 public static void Initialize()
95 Networking.initialized = true;
97 ServicePointManager.Expect100Continue = false;
99 // 明示的に指定しないと、デフォルトでは SSL3.0, TLS1.0 のみ有効となる (.NET Framework 4.5.1)
100 // https://blogs.technet.microsoft.com/jpieblog/2015/04/07/net-framework-tls1-1-1-2/
101 ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
104 public static void SetWebProxy(ProxyType proxyType, string proxyAddress, int proxyPort,
105 string proxyUser, string proxyPassword)
113 case ProxyType.Specified:
114 proxy = new WebProxy(proxyAddress, proxyPort);
115 if (!string.IsNullOrEmpty(proxyUser) || !string.IsNullOrEmpty(proxyPassword))
116 proxy.Credentials = new NetworkCredential(proxyUser, proxyPassword);
120 proxy = WebRequest.GetSystemWebProxy();
124 Networking.ProxyType = proxyType;
125 Networking.Proxy = proxy;
127 NativeMethods.SetProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword);
129 OnWebProxyChanged(EventArgs.Empty);
133 /// OpenTween で必要な設定を施した HttpClientHandler インスタンスを生成します
135 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
136 public static WebRequestHandler CreateHttpClientHandler()
138 var handler = new WebRequestHandler
140 AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
143 if (Networking.Proxy != null)
145 handler.UseProxy = true;
146 handler.Proxy = Networking.Proxy;
150 handler.UseProxy = false;
157 /// OpenTween で必要な設定を施した HttpClient インスタンスを生成します
160 /// 通常は Networking.Http を使用すべきです。
161 /// このメソッドを使用する場合は、WebProxyChanged イベントが発生する度に HttpClient を生成し直すように実装してください。
163 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
164 public static HttpClient CreateHttpClient(HttpMessageHandler handler)
168 client = new HttpClient(new ForceIPv4Handler(handler));
170 client = new HttpClient(handler);
172 client.Timeout = Networking.DefaultTimeout;
173 client.DefaultRequestHeaders.Add("User-Agent", Networking.GetUserAgentString());
178 public static string GetUserAgentString(bool fakeMSIE = false)
181 return ApplicationSettings.AssemblyName + "/" + MyCommon.FileVersion + " (compatible; MSIE 10.0)";
183 return ApplicationSettings.AssemblyName + "/" + MyCommon.FileVersion;
187 /// Initialize() メソッドが事前に呼ばれているか確認します
189 internal static void CheckInitialized()
191 if (!Networking.initialized)
192 throw new InvalidOperationException("Sequence error.(not initialized)");
195 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
196 private static void OnWebProxyChanged(EventArgs e)
198 var newClient = Networking.CreateHttpClient(Networking.CreateHttpClientHandler());
199 var oldClient = Interlocked.Exchange(ref globalHttpClient, newClient);
202 WebProxyChanged?.Invoke(null, e);
205 private class ForceIPv4Handler : DelegatingHandler
207 private readonly IPAddress ipv4Address;
209 public ForceIPv4Handler(HttpMessageHandler innerHandler)
212 foreach (var address in Dns.GetHostAddresses("pbs.twimg.com"))
213 if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
214 this.ipv4Address = address;
217 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
219 var requestUri = request.RequestUri;
220 if (requestUri.Host == "pbs.twimg.com")
222 var rewriteUriStr = requestUri.GetLeftPart(UriPartial.Scheme) + this.ipv4Address + requestUri.PathAndQuery;
223 request.RequestUri = new Uri(rewriteUriStr);
224 request.Headers.Host = "pbs.twimg.com";
227 return base.SendAsync(request, cancellationToken);
232 public enum ProxyType