opensim – Blame information for rev 1

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