GetTextureModule.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Specialized;
  30. using System.Reflection;
  31. using System.IO;
  32. using System.Web;
  33. using log4net;
  34. using Nini.Config;
  35. using OpenMetaverse;
  36. using OpenMetaverse.StructuredData;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Servers;
  39. using OpenSim.Framework.Servers.HttpServer;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. using OpenSim.Services.Interfaces;
  43. using Caps = OpenSim.Framework.Capabilities.Caps;
  44. namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps
  45. {
  46. #region Stream Handler
  47. public delegate byte[] StreamHandlerCallback(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse);
  48. public class StreamHandler : BaseStreamHandler
  49. {
  50. StreamHandlerCallback m_callback;
  51. public StreamHandler(string httpMethod, string path, StreamHandlerCallback callback)
  52. : base(httpMethod, path)
  53. {
  54. m_callback = callback;
  55. }
  56. public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  57. {
  58. return m_callback(path, request, httpRequest, httpResponse);
  59. }
  60. }
  61. #endregion Stream Handler
  62. public class GetTextureModule : IRegionModule
  63. {
  64. private static readonly ILog m_log =
  65. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  66. private Scene m_scene;
  67. private IAssetService m_assetService;
  68. #region IRegionModule Members
  69. public void Initialise(Scene pScene, IConfigSource pSource)
  70. {
  71. m_scene = pScene;
  72. }
  73. public void PostInitialise()
  74. {
  75. m_assetService = m_scene.RequestModuleInterface<IAssetService>();
  76. m_scene.EventManager.OnRegisterCaps += RegisterCaps;
  77. }
  78. public void Close() { }
  79. public string Name { get { return "GetTextureModule"; } }
  80. public bool IsSharedModule { get { return false; } }
  81. public void RegisterCaps(UUID agentID, Caps caps)
  82. {
  83. UUID capID = UUID.Random();
  84. m_log.Info("[GETTEXTURE]: /CAPS/" + capID);
  85. caps.RegisterHandler("GetTexture", new StreamHandler("GET", "/CAPS/" + capID, ProcessGetTexture));
  86. }
  87. #endregion
  88. private byte[] ProcessGetTexture(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  89. {
  90. // TODO: Change this to a config option
  91. const string REDIRECT_URL = null;
  92. // Try to parse the texture ID from the request URL
  93. NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
  94. string textureStr = query.GetOne("texture_id");
  95. if (m_assetService == null)
  96. {
  97. m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service");
  98. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  99. return null;
  100. }
  101. UUID textureID;
  102. if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID))
  103. {
  104. //m_log.DebugFormat("[GETTEXTURE]: {0}", textureID);
  105. AssetBase texture;
  106. if (!String.IsNullOrEmpty(REDIRECT_URL))
  107. {
  108. // Only try to fetch locally cached textures. Misses are redirected
  109. texture = m_assetService.GetCached(textureID.ToString());
  110. if (texture != null)
  111. {
  112. if (texture.Type != (sbyte)AssetType.Texture)
  113. {
  114. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  115. httpResponse.Send();
  116. return null;
  117. }
  118. SendTexture(httpRequest, httpResponse, texture);
  119. }
  120. else
  121. {
  122. string textureUrl = REDIRECT_URL + textureID.ToString();
  123. m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl);
  124. httpResponse.RedirectLocation = textureUrl;
  125. }
  126. }
  127. else
  128. {
  129. // Fetch locally or remotely. Misses return a 404
  130. texture = m_assetService.Get(textureID.ToString());
  131. if (texture != null)
  132. {
  133. if (texture.Type != (sbyte)AssetType.Texture)
  134. {
  135. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  136. httpResponse.Send();
  137. return null;
  138. }
  139. SendTexture(httpRequest, httpResponse, texture);
  140. }
  141. else
  142. {
  143. m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found");
  144. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  145. }
  146. }
  147. }
  148. else
  149. {
  150. m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url);
  151. }
  152. httpResponse.Send();
  153. return null;
  154. }
  155. private void SendTexture(OSHttpRequest request, OSHttpResponse response, AssetBase texture)
  156. {
  157. string range = request.Headers.GetOne("Range");
  158. //m_log.DebugFormat("[GETTEXTURE]: Range {0}", range);
  159. if (!String.IsNullOrEmpty(range))
  160. {
  161. // Range request
  162. int start, end;
  163. if (TryParseRange(range, out start, out end))
  164. {
  165. end = Utils.Clamp(end, 1, texture.Data.Length);
  166. start = Utils.Clamp(start, 0, end - 1);
  167. //m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);
  168. if (end - start < texture.Data.Length)
  169. response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent;
  170. response.ContentLength = end - start;
  171. response.ContentType = texture.Metadata.ContentType;
  172. response.Body.Write(texture.Data, start, end - start);
  173. }
  174. else
  175. {
  176. m_log.Warn("Malformed Range header: " + range);
  177. response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
  178. }
  179. }
  180. else
  181. {
  182. // Full content request
  183. response.ContentLength = texture.Data.Length;
  184. response.ContentType = texture.Metadata.ContentType;
  185. response.Body.Write(texture.Data, 0, texture.Data.Length);
  186. }
  187. }
  188. private bool TryParseRange(string header, out int start, out int end)
  189. {
  190. if (header.StartsWith("bytes="))
  191. {
  192. string[] rangeValues = header.Substring(6).Split('-');
  193. if (rangeValues.Length == 2)
  194. {
  195. if (Int32.TryParse(rangeValues[0], out start) && Int32.TryParse(rangeValues[1], out end))
  196. return true;
  197. }
  198. }
  199. start = end = 0;
  200. return false;
  201. }
  202. }
  203. }