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; }
42 public static ProxyType ProxyType
44 get { return proxyType; }
50 public static IWebProxy Proxy
56 /// OpenTween 内で共通して使用する HttpClient インスタンス
58 public static HttpClient Http
60 get { return globalHttpClient; }
64 /// pbs.twimg.com で IPv4 を強制的に使用する
66 public static bool ForceIPv4
68 get { return forceIPv4; }
71 if (forceIPv4 == value)
76 // Network.Http を再作成させる
77 OnWebProxyChanged(EventArgs.Empty);
82 /// Webプロキシの設定が変更された場合に発生します
84 public static event EventHandler WebProxyChanged;
86 private static bool initialized = false;
87 private static HttpClient globalHttpClient;
88 private static ProxyType proxyType = ProxyType.IE;
89 private static IWebProxy proxy = null;
90 private static bool forceIPv4 = false;
92 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
95 DefaultTimeout = TimeSpan.FromSeconds(20);
96 globalHttpClient = CreateHttpClient(new HttpClientHandler());
100 /// ネットワーク接続前に行う処理。起動時に一回だけ実行する必要があります。
102 public static void Initialize()
104 Networking.initialized = true;
106 ServicePointManager.Expect100Continue = false;
107 WebRequest.DefaultCachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
110 public static void SetWebProxy(ProxyType proxyType, string proxyAddress, int proxyPort,
111 string proxyUser, string proxyPassword)
119 case ProxyType.Specified:
120 proxy = new WebProxy(proxyAddress, proxyPort);
121 if (!string.IsNullOrEmpty(proxyUser) || !string.IsNullOrEmpty(proxyPassword))
122 proxy.Credentials = new NetworkCredential(proxyUser, proxyPassword);
126 proxy = WebRequest.GetSystemWebProxy();
130 Networking.proxyType = proxyType;
131 Networking.proxy = proxy;
133 NativeMethods.SetProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword);
135 OnWebProxyChanged(EventArgs.Empty);
139 /// プロキシ等の設定を施した HttpClient インスタンスを生成します
142 /// 通常は Networking.Http を使用すべきです。
143 /// このメソッドを使用する場合は、WebProxyChanged イベントが発生する度に HttpClient を生成し直すように実装してください。
145 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
146 public static HttpClient CreateHttpClient(HttpClientHandler handler)
148 if (Networking.Proxy != null)
150 handler.UseProxy = true;
151 handler.Proxy = Networking.Proxy;
155 handler.UseProxy = false;
160 client = new HttpClient(new ForceIPv4Handler(handler));
162 client = new HttpClient(handler);
164 client.Timeout = Networking.DefaultTimeout;
165 client.DefaultRequestHeaders.Add("User-Agent", Networking.GetUserAgentString());
170 public static string GetUserAgentString(bool fakeMSIE = false)
173 return MyCommon.GetAssemblyName() + "/" + MyCommon.FileVersion + " (compatible; MSIE 10.0)";
175 return MyCommon.GetAssemblyName() + "/" + MyCommon.FileVersion;
179 /// Initialize() メソッドが事前に呼ばれているか確認します
181 internal static void CheckInitialized()
183 if (!Networking.initialized)
184 throw new InvalidOperationException("Sequence error.(not initialized)");
187 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
188 private static void OnWebProxyChanged(EventArgs e)
190 var newClient = Networking.CreateHttpClient(new HttpClientHandler());
191 var oldClient = Interlocked.Exchange(ref globalHttpClient, newClient);
194 WebProxyChanged?.Invoke(null, e);
197 private class ForceIPv4Handler : DelegatingHandler
199 private readonly IPAddress ipv4Address;
201 public ForceIPv4Handler(HttpMessageHandler innerHandler)
204 foreach (var address in Dns.GetHostAddresses("pbs.twimg.com"))
205 if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
206 this.ipv4Address = address;
209 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
211 var requestUri = request.RequestUri;
212 if (requestUri.Host == "pbs.twimg.com")
214 var rewriteUriStr = requestUri.GetLeftPart(UriPartial.Scheme) + this.ipv4Address + requestUri.PathAndQuery;
215 request.RequestUri = new Uri(rewriteUriStr);
216 request.Headers.Host = "pbs.twimg.com";
219 return base.SendAsync(request, cancellationToken);
224 public enum ProxyType