GetTextureRobustHandler.cs 19 KB

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