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