123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802 |
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- using BestHTTP.Caching;
- #endif
- using BestHTTP.Extensions;
- using BestHTTP.Logger;
- using BestHTTP.Statistics;
- namespace BestHTTP
- {
-
-
-
- public static class HTTPManager
- {
-
- static HTTPManager()
- {
- MaxConnectionPerServer = 4;
- KeepAliveDefaultValue = true;
- MaxPathLength = 255;
- MaxConnectionIdleTime = TimeSpan.FromSeconds(20);
- #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
- IsCookiesEnabled = true;
- #endif
- CookieJarSize = 10 * 1024 * 1024;
- EnablePrivateBrowsing = false;
- ConnectTimeout = TimeSpan.FromSeconds(20);
- RequestTimeout = TimeSpan.FromSeconds(60);
-
- logger = new BestHTTP.Logger.DefaultLogger();
- #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
- DefaultCertificateVerifyer = null;
- UseAlternateSSLDefaultValue = true;
- #endif
- }
- #region Global Options
-
-
-
- public static byte MaxConnectionPerServer
- {
- get{ return maxConnectionPerServer; }
- set
- {
- if (value <= 0)
- throw new ArgumentOutOfRangeException("MaxConnectionPerServer must be greater than 0!");
- maxConnectionPerServer = value;
- }
- }
- private static byte maxConnectionPerServer;
-
-
-
- public static bool KeepAliveDefaultValue { get; set; }
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
-
-
-
- public static bool IsCachingDisabled { get; set; }
- #endif
-
-
-
- public static TimeSpan MaxConnectionIdleTime { get; set; }
- #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
-
-
-
- public static bool IsCookiesEnabled { get; set; }
- #endif
-
-
-
- public static uint CookieJarSize { get; set; }
-
-
-
- public static bool EnablePrivateBrowsing { get; set; }
-
-
-
- public static TimeSpan ConnectTimeout { get; set; }
-
-
-
- public static TimeSpan RequestTimeout { get; set; }
- #if !((BESTHTTP_DISABLE_CACHING && BESTHTTP_DISABLE_COOKIES) || (UNITY_WEBGL && !UNITY_EDITOR))
-
-
-
-
-
- public static System.Func<string> RootCacheFolderProvider { get; set; }
- #endif
- #if !BESTHTTP_DISABLE_PROXY
-
-
-
- public static HTTPProxy Proxy { get; set; }
- #endif
-
-
-
- public static HeartbeatManager Heartbeats
- {
- get
- {
- if (heartbeats == null)
- heartbeats = new HeartbeatManager();
- return heartbeats;
- }
- }
- private static HeartbeatManager heartbeats;
-
-
-
- public static BestHTTP.Logger.ILogger Logger
- {
- get
- {
-
- if (logger == null)
- {
- logger = new DefaultLogger();
- logger.Level = Loglevels.None;
- }
- return logger;
- }
- set { logger = value; }
- }
- private static BestHTTP.Logger.ILogger logger;
- #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
-
-
-
- public static Org.BouncyCastle.Crypto.Tls.ICertificateVerifyer DefaultCertificateVerifyer { get; set; }
-
-
-
- public static Org.BouncyCastle.Crypto.Tls.IClientCredentialsProvider DefaultClientCredentialsProvider { get; set; }
-
-
-
- public static bool UseAlternateSSLDefaultValue { get; set; }
- #endif
- #if !NETFX_CORE && !UNITY_WP8
- public static Func<HTTPRequest, System.Security.Cryptography.X509Certificates.X509Certificate, System.Security.Cryptography.X509Certificates.X509Chain, bool> DefaultCertificationValidator { get; set; }
- #endif
-
-
-
- public static bool TryToMinimizeTCPLatency = false;
- public static int SendBufferSize = 65 * 1024;
- public static int ReceiveBufferSize = 65 * 1024;
-
-
-
-
- internal static int MaxPathLength { get; set; }
- #endregion
- #region Manager variables
-
-
-
- private static Dictionary<string, List<ConnectionBase>> Connections = new Dictionary<string, List<ConnectionBase>>();
-
-
-
- private static List<ConnectionBase> ActiveConnections = new List<ConnectionBase>();
-
-
-
- private static List<ConnectionBase> FreeConnections = new List<ConnectionBase>();
-
-
-
- private static List<ConnectionBase> RecycledConnections = new List<ConnectionBase>();
-
-
-
- private static List<HTTPRequest> RequestQueue = new List<HTTPRequest>();
- private static bool IsCallingCallbacks;
- internal static System.Object Locker = new System.Object();
- internal static bool IsQuitting { get; private set; }
- #endregion
- #region Public Interface
- public static void Setup()
- {
- HTTPUpdateDelegator.CheckInstance();
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- HTTPCacheService.CheckSetup();
- #endif
- #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
- Cookies.CookieJar.SetupFolder();
- #endif
- }
- public static HTTPRequest SendRequest(string url, OnRequestFinishedDelegate callback)
- {
- return SendRequest(new HTTPRequest(new Uri(url), HTTPMethods.Get, callback));
- }
- public static HTTPRequest SendRequest(string url, HTTPMethods methodType, OnRequestFinishedDelegate callback)
- {
- return SendRequest(new HTTPRequest(new Uri(url), methodType, callback));
- }
- public static HTTPRequest SendRequest(string url, HTTPMethods methodType, bool isKeepAlive, OnRequestFinishedDelegate callback)
- {
- return SendRequest(new HTTPRequest(new Uri(url), methodType, isKeepAlive, callback));
- }
- public static HTTPRequest SendRequest(string url, HTTPMethods methodType, bool isKeepAlive, bool disableCache, OnRequestFinishedDelegate callback)
- {
- return SendRequest(new HTTPRequest(new Uri(url), methodType, isKeepAlive, disableCache, callback));
- }
- public static HTTPRequest SendRequest(HTTPRequest request)
- {
- lock (Locker)
- {
- Setup();
- if (IsCallingCallbacks)
- {
- request.State = HTTPRequestStates.Queued;
- RequestQueue.Add(request);
- }
- else
- SendRequestImpl(request);
- return request;
- }
- }
- public static GeneralStatistics GetGeneralStatistics(StatisticsQueryFlags queryFlags)
- {
- GeneralStatistics stat = new GeneralStatistics();
- stat.QueryFlags = queryFlags;
- if ((queryFlags & StatisticsQueryFlags.Connections) != 0)
- {
- int connections = 0;
- foreach(var conn in HTTPManager.Connections)
- {
- if (conn.Value != null)
- connections += conn.Value.Count;
- }
- #if !BESTHTTP_DISABLE_WEBSOCKET && UNITY_WEBGL && !UNITY_EDITOR
- connections += WebSocket.WebSocket.WebSockets.Count;
- #endif
- stat.Connections = connections;
- stat.ActiveConnections = ActiveConnections.Count
- #if !BESTHTTP_DISABLE_WEBSOCKET && UNITY_WEBGL && !UNITY_EDITOR
- + WebSocket.WebSocket.WebSockets.Count
- #endif
- ;
- stat.FreeConnections = FreeConnections.Count;
- stat.RecycledConnections = RecycledConnections.Count;
- stat.RequestsInQueue = RequestQueue.Count;
- }
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- if ((queryFlags & StatisticsQueryFlags.Cache) != 0)
- {
- stat.CacheEntityCount = HTTPCacheService.GetCacheEntityCount();
- stat.CacheSize = HTTPCacheService.GetCacheSize();
- }
- #endif
- #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
- if ((queryFlags & StatisticsQueryFlags.Cookies) != 0)
- {
- List<Cookies.Cookie> cookies = Cookies.CookieJar.GetAll();
- stat.CookieCount = cookies.Count;
- uint cookiesSize = 0;
- for (int i = 0; i < cookies.Count; ++i)
- cookiesSize += cookies[i].GuessSize();
- stat.CookieJarSize = cookiesSize;
- }
- #endif
- return stat;
- }
- #endregion
- #region Private Functions
- private static void SendRequestImpl(HTTPRequest request)
- {
- ConnectionBase conn = FindOrCreateFreeConnection(request);
- if (conn != null)
- {
-
- if (ActiveConnections.Find((c) => c == conn) == null)
- ActiveConnections.Add(conn);
- FreeConnections.Remove(conn);
- request.State = HTTPRequestStates.Processing;
- request.Prepare();
-
- conn.Process(request);
- }
- else
- {
-
- request.State = HTTPRequestStates.Queued;
- RequestQueue.Add(request);
- }
- }
- private static string GetKeyForRequest(HTTPRequest request)
- {
- if (request.CurrentUri.IsFile)
- return request.CurrentUri.ToString();
-
-
- return
- #if !BESTHTTP_DISABLE_PROXY
- (request.Proxy != null ? new UriBuilder(request.Proxy.Address.Scheme, request.Proxy.Address.Host, request.Proxy.Address.Port).Uri.ToString() : string.Empty) +
- #endif
- new UriBuilder(request.CurrentUri.Scheme, request.CurrentUri.Host, request.CurrentUri.Port).Uri.ToString();
- }
-
-
-
- private static ConnectionBase CreateConnection(HTTPRequest request, string serverUrl)
- {
- if (request.CurrentUri.IsFile && Application.platform != RuntimePlatform.WebGLPlayer)
- return new FileConnection(serverUrl);
- #if UNITY_WEBGL && !UNITY_EDITOR
- return new WebGLConnection(serverUrl);
- #else
- return new HTTPConnection(serverUrl);
- #endif
- }
- private static ConnectionBase FindOrCreateFreeConnection(HTTPRequest request)
- {
- ConnectionBase conn = null;
- List<ConnectionBase> connections;
- string serverUrl = GetKeyForRequest(request);
- if (Connections.TryGetValue(serverUrl, out connections))
- {
-
- int activeConnections = 0;
- for (int i = 0; i < connections.Count; ++i)
- if (connections[i].IsActive)
- activeConnections++;
- if (activeConnections <= MaxConnectionPerServer)
-
- for (int i = 0; i < connections.Count && conn == null; ++i)
- {
- var tmpConn = connections[i];
- if (tmpConn != null &&
- tmpConn.IsFree &&
- (
- #if !BESTHTTP_DISABLE_PROXY
- !tmpConn.HasProxy ||
- #endif
- tmpConn.LastProcessedUri == null ||
- tmpConn.LastProcessedUri.Host.Equals(request.CurrentUri.Host, StringComparison.OrdinalIgnoreCase)))
- conn = tmpConn;
- }
- }
- else
- Connections.Add(serverUrl, connections = new List<ConnectionBase>(MaxConnectionPerServer));
-
- if (conn == null)
- {
-
- if (connections.Count >= MaxConnectionPerServer)
- return null;
-
- connections.Add(conn = CreateConnection(request, serverUrl));
- }
- return conn;
- }
-
-
-
- private static bool CanProcessFromQueue()
- {
- for (int i = 0; i < RequestQueue.Count; ++i)
- if (FindOrCreateFreeConnection(RequestQueue[i]) != null)
- return true;
- return false;
- }
- private static void RecycleConnection(ConnectionBase conn)
- {
- conn.Recycle(OnConnectionRecylced);
- }
- private static void OnConnectionRecylced(ConnectionBase conn)
- {
- lock (RecycledConnections)
- {
- RecycledConnections.Add(conn);
- }
- }
- #endregion
- #region Internal Helper Functions
-
-
-
- internal static ConnectionBase GetConnectionWith(HTTPRequest request)
- {
- lock (Locker)
- {
- for (int i = 0; i < ActiveConnections.Count; ++i)
- {
- var connection = ActiveConnections[i];
- if (connection.CurrentRequest == request)
- return connection;
- }
- return null;
- }
- }
- internal static bool RemoveFromQueue(HTTPRequest request)
- {
- return RequestQueue.Remove(request);
- }
- #if !((BESTHTTP_DISABLE_CACHING && BESTHTTP_DISABLE_COOKIES) || (UNITY_WEBGL && !UNITY_EDITOR))
-
-
-
- internal static string GetRootCacheFolder()
- {
- try
- {
- if (RootCacheFolderProvider != null)
- return RootCacheFolderProvider();
- }
- catch(Exception ex)
- {
- HTTPManager.Logger.Exception("HTTPManager", "GetRootCacheFolder", ex);
- }
- #if NETFX_CORE
- return Windows.Storage.ApplicationData.Current.LocalFolder.Path;
- #else
- return Application.persistentDataPath;
- #endif
- }
- #endif
- #endregion
- #region MonoBehaviour Events (Called from HTTPUpdateDelegator)
-
-
-
- public static void OnUpdate()
- {
-
- if (System.Threading.Monitor.TryEnter(Locker))
- {
- try
- {
- IsCallingCallbacks = true;
- try
- {
- for (int i = 0; i < ActiveConnections.Count; ++i)
- {
- ConnectionBase conn = ActiveConnections[i];
- switch (conn.State)
- {
- case HTTPConnectionStates.Processing:
- conn.HandleProgressCallback();
- if (conn.CurrentRequest.UseStreaming && conn.CurrentRequest.Response != null && conn.CurrentRequest.Response.HasStreamedFragments())
- conn.HandleCallback();
- try
- {
- if (((!conn.CurrentRequest.UseStreaming && conn.CurrentRequest.UploadStream == null) || conn.CurrentRequest.EnableTimoutForStreaming) &&
- DateTime.UtcNow - conn.StartTime > conn.CurrentRequest.Timeout)
- conn.Abort(HTTPConnectionStates.TimedOut);
- }
- catch (OverflowException)
- {
- HTTPManager.Logger.Warning("HTTPManager", "TimeSpan overflow");
- }
- break;
- case HTTPConnectionStates.TimedOut:
-
-
- try
- {
- if (DateTime.UtcNow - conn.TimedOutStart > TimeSpan.FromMilliseconds(500))
- {
- HTTPManager.Logger.Information("HTTPManager", "Hard aborting connection because of a long waiting TimedOut state");
- conn.CurrentRequest.Response = null;
- conn.CurrentRequest.State = HTTPRequestStates.TimedOut;
- conn.HandleCallback();
-
- RecycleConnection(conn);
- }
- }
- catch(OverflowException)
- {
- HTTPManager.Logger.Warning("HTTPManager", "TimeSpan overflow");
- }
- break;
- case HTTPConnectionStates.Redirected:
-
- SendRequest(conn.CurrentRequest);
- RecycleConnection(conn);
- break;
- case HTTPConnectionStates.WaitForRecycle:
-
- conn.CurrentRequest.FinishStreaming();
-
- conn.HandleCallback();
-
- RecycleConnection(conn);
- break;
- case HTTPConnectionStates.Upgraded:
-
- conn.HandleCallback();
- break;
- case HTTPConnectionStates.WaitForProtocolShutdown:
- var ws = conn.CurrentRequest.Response as IProtocol;
- if (ws != null)
- ws.HandleEvents();
- if (ws == null || ws.IsClosed)
- {
- conn.HandleCallback();
-
- conn.Dispose();
- RecycleConnection(conn);
- }
- break;
- case HTTPConnectionStates.AbortRequested:
-
- {
- ws = conn.CurrentRequest.Response as IProtocol;
- if (ws != null)
- {
- ws.HandleEvents();
- if (ws.IsClosed)
- {
- conn.HandleCallback();
- conn.Dispose();
- RecycleConnection(conn);
- }
- }
- }
- break;
- case HTTPConnectionStates.Closed:
-
- conn.CurrentRequest.FinishStreaming();
-
- conn.HandleCallback();
-
- RecycleConnection(conn);
- break;
- case HTTPConnectionStates.Free:
- RecycleConnection(conn);
- break;
- }
- }
- }
- finally
- {
- IsCallingCallbacks = false;
- }
-
-
- if (System.Threading.Monitor.TryEnter(RecycledConnections))
- try
- {
- if (RecycledConnections.Count > 0)
- {
- for (int i = 0; i < RecycledConnections.Count; ++i)
- {
- var connection = RecycledConnections[i];
-
-
- if (connection.IsFree)
- {
- ActiveConnections.Remove(connection);
- FreeConnections.Add(connection);
- }
- }
- RecycledConnections.Clear();
- }
- }
- finally
- {
- System.Threading.Monitor.Exit(RecycledConnections);
- }
- if (FreeConnections.Count > 0)
- for (int i = 0; i < FreeConnections.Count; i++)
- {
- var connection = FreeConnections[i];
- if (connection.IsRemovable)
- {
-
- List<ConnectionBase> connections = null;
- if (Connections.TryGetValue(connection.ServerAddress, out connections))
- connections.Remove(connection);
-
- connection.Dispose();
- FreeConnections.RemoveAt(i);
- i--;
- }
- }
- if (CanProcessFromQueue())
- {
-
- if (RequestQueue.Find((req) => req.Priority != 0) != null)
- RequestQueue.Sort((req1, req2) => req1.Priority - req2.Priority);
-
- var queue = RequestQueue.ToArray();
- RequestQueue.Clear();
- for (int i = 0; i < queue.Length; ++i)
- SendRequest(queue[i]);
- }
- }
- finally
- {
- System.Threading.Monitor.Exit(Locker);
- }
- }
- if (heartbeats != null)
- heartbeats.Update();
- }
- public static void OnQuit()
- {
- lock (Locker)
- {
- IsQuitting = true;
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- Caching.HTTPCacheService.SaveLibrary();
- #endif
- #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
- Cookies.CookieJar.Persist();
- #endif
- AbortAll(true);
- OnUpdate();
- }
- }
- public static void AbortAll(bool allowCallbacks = false)
- {
- lock (Locker)
- {
- var queue = RequestQueue.ToArray();
- RequestQueue.Clear();
- foreach (var req in queue)
- {
-
- try
- {
- if (!allowCallbacks)
- req.Callback = null;
- req.Abort();
- }
- catch { }
- }
-
- foreach (var kvp in Connections)
- {
- foreach (var conn in kvp.Value)
- {
-
- try
- {
- if (conn.CurrentRequest != null)
- {
- if (!allowCallbacks)
- conn.CurrentRequest.Callback = null;
- conn.CurrentRequest.State = HTTPRequestStates.Aborted;
- }
- conn.Abort(HTTPConnectionStates.Closed);
- conn.Dispose();
- }
- catch { }
- }
- kvp.Value.Clear();
- }
- Connections.Clear();
- }
- }
- #endregion
- }
- }
|