GetTextureRobustHandler.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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.Drawing;
  31. using System.Drawing.Imaging;
  32. using System.Reflection;
  33. using System.IO;
  34. using System.Net;
  35. using System.Web;
  36. using log4net;
  37. using Nini.Config;
  38. using OpenMetaverse;
  39. using OpenMetaverse.StructuredData;
  40. using OpenMetaverse.Imaging;
  41. using OpenSim.Framework;
  42. using OpenSim.Framework.Servers;
  43. using OpenSim.Framework.Servers.HttpServer;
  44. using OpenSim.Region.Framework.Interfaces;
  45. using OpenSim.Services.Interfaces;
  46. using Caps = OpenSim.Framework.Capabilities.Caps;
  47. namespace OpenSim.Capabilities.Handlers
  48. {
  49. public class GetTextureRobustHandler : BaseStreamHandler
  50. {
  51. private static readonly ILog m_log =
  52. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  53. private IAssetService m_assetService;
  54. public const string DefaultFormat = "x-j2c";
  55. // TODO: Change this to a config option
  56. private string m_RedirectURL = null;
  57. public GetTextureRobustHandler(string path, IAssetService assService, string name, string description, string redirectURL)
  58. : base("GET", path, name, description)
  59. {
  60. m_assetService = assService;
  61. m_RedirectURL = redirectURL;
  62. if (m_RedirectURL != null && !m_RedirectURL.EndsWith("/"))
  63. m_RedirectURL += "/";
  64. }
  65. protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  66. {
  67. // Try to parse the texture ID from the request URL
  68. NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
  69. string textureStr = query.GetOne("texture_id");
  70. string format = query.GetOne("format");
  71. //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr);
  72. if (m_assetService == null)
  73. {
  74. m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service");
  75. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  76. return null;
  77. }
  78. UUID textureID;
  79. if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID))
  80. {
  81. // m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID);
  82. string[] formats;
  83. if (!string.IsNullOrEmpty(format))
  84. {
  85. formats = new string[1] { format.ToLower() };
  86. }
  87. else
  88. {
  89. formats = WebUtil.GetPreferredImageTypes(httpRequest.Headers.Get("Accept"));
  90. if (formats.Length == 0)
  91. formats = new string[1] { DefaultFormat }; // default
  92. }
  93. // OK, we have an array with preferred formats, possibly with only one entry
  94. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  95. foreach (string f in formats)
  96. {
  97. if (FetchTexture(httpRequest, httpResponse, textureID, f))
  98. break;
  99. }
  100. }
  101. else
  102. {
  103. m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url);
  104. }
  105. // m_log.DebugFormat(
  106. // "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}",
  107. // textureID, httpResponse.StatusCode, httpResponse.ContentLength);
  108. return null;
  109. }
  110. /// <summary>
  111. ///
  112. /// </summary>
  113. /// <param name="httpRequest"></param>
  114. /// <param name="httpResponse"></param>
  115. /// <param name="textureID"></param>
  116. /// <param name="format"></param>
  117. /// <returns>False for "caller try another codec"; true otherwise</returns>
  118. private bool FetchTexture(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID textureID, string format)
  119. {
  120. // m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format);
  121. if(!String.IsNullOrEmpty(m_RedirectURL))
  122. {
  123. string textureUrl = m_RedirectURL + "?texture_id=" + textureID.ToString();
  124. m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl);
  125. httpResponse.StatusCode = (int)HttpStatusCode.Moved;
  126. httpResponse.AddHeader("Location:", textureUrl);
  127. return true;
  128. }
  129. // Fetch, Misses or invalid return a 404
  130. AssetBase 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. return true;
  137. }
  138. if (format == DefaultFormat)
  139. {
  140. WriteTextureData(httpRequest, httpResponse, texture, format);
  141. return true;
  142. }
  143. // need to convert format
  144. AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID);
  145. newTexture.Data = ConvertTextureData(texture, format);
  146. if (newTexture.Data.Length == 0)
  147. return false; // !!! Caller try another codec, please!
  148. newTexture.Flags = AssetFlags.Collectable;
  149. newTexture.Temporary = true;
  150. newTexture.Local = true;
  151. WriteTextureData(httpRequest, httpResponse, newTexture, format);
  152. return true;
  153. }
  154. // not found
  155. // m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found");
  156. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  157. return true;
  158. }
  159. private void WriteTextureData(IOSHttpRequest request, IOSHttpResponse response, AssetBase texture, string format)
  160. {
  161. string range = request.Headers.GetOne("Range");
  162. if (!String.IsNullOrEmpty(range)) // JP2's only
  163. {
  164. // Range request
  165. int start, end;
  166. if (TryParseRange(range, out start, out end))
  167. {
  168. // Before clamping start make sure we can satisfy it in order to avoid
  169. // sending back the last byte instead of an error status
  170. if (start >= texture.Data.Length)
  171. {
  172. // m_log.DebugFormat(
  173. // "[GETTEXTURE]: Client requested range for texture {0} starting at {1} but texture has end of {2}",
  174. // texture.ID, start, texture.Data.Length);
  175. // Stricly speaking, as per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, we should be sending back
  176. // Requested Range Not Satisfiable (416) here. However, it appears that at least recent implementations
  177. // of the Linden Lab viewer (3.2.1 and 3.3.4 and probably earlier), a viewer that has previously
  178. // received a very small texture may attempt to fetch bytes from the server past the
  179. // range of data that it received originally. Whether this happens appears to depend on whether
  180. // the viewer's estimation of how large a request it needs to make for certain discard levels
  181. // (http://wiki.secondlife.com/wiki/Image_System#Discard_Level_and_Mip_Mapping), chiefly discard
  182. // level 2. If this estimate is greater than the total texture size, returning a RequestedRangeNotSatisfiable
  183. // here will cause the viewer to treat the texture as bad and never display the full resolution
  184. // However, if we return PartialContent (or OK) instead, the viewer will display that resolution.
  185. // response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable;
  186. // response.AddHeader("Content-Range", String.Format("bytes */{0}", texture.Data.Length));
  187. // response.StatusCode = (int)System.Net.HttpStatusCode.OK;
  188. response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent;
  189. response.ContentType = texture.Metadata.ContentType;
  190. }
  191. else
  192. {
  193. // Handle the case where no second range value was given. This is equivalent to requesting
  194. // the rest of the entity.
  195. if (end == -1)
  196. end = int.MaxValue;
  197. end = Utils.Clamp(end, 0, texture.Data.Length - 1);
  198. start = Utils.Clamp(start, 0, end);
  199. int len = end - start + 1;
  200. // m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);
  201. // Always return PartialContent, even if the range covered the entire data length
  202. // We were accidentally sending back 404 before in this situation
  203. // https://issues.apache.org/bugzilla/show_bug.cgi?id=51878 supports sending 206 even if the
  204. // entire range is requested, and viewer 3.2.2 (and very probably earlier) seems fine with this.
  205. //
  206. // We also do not want to send back OK even if the whole range was satisfiable since this causes
  207. // HTTP textures on at least Imprudence 1.4.0-beta2 to never display the final texture quality.
  208. // if (end > maxEnd)
  209. // response.StatusCode = (int)System.Net.HttpStatusCode.OK;
  210. // else
  211. response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent;
  212. response.ContentLength = len;
  213. response.ContentType = texture.Metadata.ContentType;
  214. response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length));
  215. response.RawBuffer = texture.Data;
  216. response.RawBufferStart = start;
  217. response.RawBufferLen = len;
  218. }
  219. }
  220. else
  221. {
  222. m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range);
  223. response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
  224. }
  225. }
  226. else // JP2's or other formats
  227. {
  228. // Full content request
  229. response.StatusCode = (int)System.Net.HttpStatusCode.OK;
  230. response.ContentLength = texture.Data.Length;
  231. if (format == DefaultFormat)
  232. response.ContentType = texture.Metadata.ContentType;
  233. else
  234. response.ContentType = "image/" + format;
  235. response.RawBuffer = texture.Data;
  236. response.RawBufferStart = 0;
  237. response.RawBufferLen = texture.Data.Length;
  238. }
  239. // if (response.StatusCode < 200 || response.StatusCode > 299)
  240. // m_log.WarnFormat(
  241. // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})",
  242. // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
  243. // else
  244. // m_log.DebugFormat(
  245. // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})",
  246. // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
  247. }
  248. /// <summary>
  249. /// Parse a range header.
  250. /// </summary>
  251. /// <remarks>
  252. /// As per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html,
  253. /// this obeys range headers with two values (e.g. 533-4165) and no second value (e.g. 533-).
  254. /// Where there is no value, -1 is returned.
  255. /// FIXME: Need to cover the case where only a second value is specified (e.g. -4165), probably by returning -1
  256. /// for start.</remarks>
  257. /// <returns></returns>
  258. /// <param name='header'></param>
  259. /// <param name='start'>Start of the range. Undefined if this was not a number.</param>
  260. /// <param name='end'>End of the range. Will be -1 if no end specified. Undefined if there was a raw string but this was not a number.</param>
  261. private bool TryParseRange(string header, out int start, out int end)
  262. {
  263. start = end = 0;
  264. if (header.StartsWith("bytes="))
  265. {
  266. string[] rangeValues = header.Substring(6).Split('-');
  267. if (rangeValues.Length == 2)
  268. {
  269. if (!Int32.TryParse(rangeValues[0], out start))
  270. return false;
  271. string rawEnd = rangeValues[1];
  272. if (rawEnd == "")
  273. {
  274. end = -1;
  275. return true;
  276. }
  277. else if (Int32.TryParse(rawEnd, out end))
  278. {
  279. return true;
  280. }
  281. }
  282. }
  283. start = end = 0;
  284. return false;
  285. }
  286. private byte[] ConvertTextureData(AssetBase texture, string format)
  287. {
  288. m_log.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format);
  289. byte[] data = new byte[0];
  290. MemoryStream imgstream = new MemoryStream();
  291. Bitmap mTexture = null;
  292. ManagedImage managedImage = null;
  293. Image image = null;
  294. try
  295. {
  296. // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data
  297. // Decode image to System.Drawing.Image
  298. if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image) && image != null)
  299. {
  300. // Save to bitmap
  301. mTexture = new Bitmap(image);
  302. using(EncoderParameters myEncoderParameters = new EncoderParameters())
  303. {
  304. myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality,95L);
  305. // Save bitmap to stream
  306. ImageCodecInfo codec = GetEncoderInfo("image/" + format);
  307. if (codec != null)
  308. {
  309. mTexture.Save(imgstream, codec, myEncoderParameters);
  310. // Write the stream to a byte array for output
  311. data = imgstream.ToArray();
  312. }
  313. else
  314. m_log.WarnFormat("[GETTEXTURE]: No such codec {0}", format);
  315. }
  316. }
  317. }
  318. catch (Exception e)
  319. {
  320. m_log.WarnFormat("[GETTEXTURE]: Unable to convert texture {0} to {1}: {2}", texture.ID, format, e.Message);
  321. }
  322. finally
  323. {
  324. // Reclaim memory, these are unmanaged resources
  325. // If we encountered an exception, one or more of these will be null
  326. if (mTexture != null)
  327. mTexture.Dispose();
  328. if (image != null)
  329. image.Dispose();
  330. if(managedImage != null)
  331. managedImage.Clear();
  332. if (imgstream != null)
  333. imgstream.Dispose();
  334. }
  335. return data;
  336. }
  337. // From msdn
  338. private static ImageCodecInfo GetEncoderInfo(String mimeType)
  339. {
  340. ImageCodecInfo[] encoders;
  341. encoders = ImageCodecInfo.GetImageEncoders();
  342. for (int j = 0; j < encoders.Length; ++j)
  343. {
  344. if (encoders[j].MimeType == mimeType)
  345. return encoders[j];
  346. }
  347. return null;
  348. }
  349. }
  350. }