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.Http;
29 using System.Threading;
30 using System.Threading.Tasks;
32 namespace OpenTween.Connection
34 public static class Networking
36 public static TimeSpan DefaultTimeout { get; set; }
41 public static ProxyType ProxyType
43 get { return proxyType; }
49 public static IWebProxy Proxy
55 /// OpenTween 内で共通して使用する HttpClient インスタンス
57 public static HttpClient Http
59 get { return globalHttpClient; }
63 /// pbs.twimg.com で IPv4 を強制的に使用する
65 public static bool ForceIPv4
67 get { return forceIPv4; }
70 if (forceIPv4 == value)
75 // Network.Http を再作成させる
76 OnWebProxyChanged(EventArgs.Empty);
81 /// Webプロキシの設定が変更された場合に発生します
83 public static event EventHandler WebProxyChanged;
85 private static bool initialized = false;
86 private static HttpClient globalHttpClient;
87 private static ProxyType proxyType = ProxyType.IE;
88 private static IWebProxy proxy = null;
89 private static bool forceIPv4 = false;
91 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
94 DefaultTimeout = TimeSpan.FromSeconds(20);
95 globalHttpClient = CreateHttpClient(new HttpClientHandler());
99 /// ネットワーク接続前に行う処理。起動時に一回だけ実行する必要があります。
101 public static void Initialize()
103 Networking.initialized = true;
105 ServicePointManager.Expect100Continue = false;
108 public static void SetWebProxy(ProxyType proxyType, string proxyAddress, int proxyPort,
109 string proxyUser, string proxyPassword)
117 case ProxyType.Specified:
118 proxy = new WebProxy(proxyAddress, proxyPort);
119 if (!string.IsNullOrEmpty(proxyUser) || !string.IsNullOrEmpty(proxyPassword))
120 proxy.Credentials = new NetworkCredential(proxyUser, proxyPassword);
124 proxy = WebRequest.GetSystemWebProxy();
128 Networking.proxyType = proxyType;
129 Networking.proxy = proxy;
131 NativeMethods.SetProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword);
133 OnWebProxyChanged(EventArgs.Empty);
137 /// プロキシ等の設定を施した HttpClient インスタンスを生成します
140 /// 通常は Networking.Http を使用すべきです。
141 /// このメソッドを使用する場合は、WebProxyChanged イベントが発生する度に HttpClient を生成し直すように実装してください。
143 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
144 public static HttpClient CreateHttpClient(HttpClientHandler handler)
146 if (Networking.Proxy != null)
148 handler.UseProxy = true;
149 handler.Proxy = Networking.Proxy;
153 handler.UseProxy = false;
158 client = new HttpClient(new ForceIPv4Handler(handler));
160 client = new HttpClient(handler);
162 client.Timeout = Networking.DefaultTimeout;
163 client.DefaultRequestHeaders.Add("User-Agent", Networking.GetUserAgentString());
168 public static string GetUserAgentString(bool fakeMSIE = false)
171 return MyCommon.GetAssemblyName() + "/" + MyCommon.FileVersion + " (compatible; MSIE 10.0)";
173 return MyCommon.GetAssemblyName() + "/" + MyCommon.FileVersion;
177 /// Initialize() メソッドが事前に呼ばれているか確認します
179 internal static void CheckInitialized()
181 if (!Networking.initialized)
182 throw new InvalidOperationException("Sequence error.(not initialized)");
185 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
186 private static void OnWebProxyChanged(EventArgs e)
188 var newClient = Networking.CreateHttpClient(new HttpClientHandler());
189 var oldClient = Interlocked.Exchange(ref globalHttpClient, newClient);
192 WebProxyChanged?.Invoke(null, e);
195 private class ForceIPv4Handler : DelegatingHandler
197 private readonly IPAddress ipv4Address;
199 public ForceIPv4Handler(HttpMessageHandler innerHandler)
202 foreach (var address in Dns.GetHostAddresses("pbs.twimg.com"))
203 if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
204 this.ipv4Address = address;
207 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
209 var requestUri = request.RequestUri;
210 if (requestUri.Host == "pbs.twimg.com")
212 var rewriteUriStr = requestUri.GetLeftPart(UriPartial.Scheme) + this.ipv4Address + requestUri.PathAndQuery;
213 request.RequestUri = new Uri(rewriteUriStr);
214 request.Headers.Host = "pbs.twimg.com";
217 return base.SendAsync(request, cancellationToken);
222 public enum ProxyType