public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // path = /wifi/... //m_log.DebugFormat("[Wifi]: path = {0}", path); //m_log.DebugFormat("[Wifi]: ip address = {0}", httpRequest.RemoteIPEndPoint); //foreach (object o in httpRequest.Query.Keys) // m_log.DebugFormat(" >> {0}={1}", o, httpRequest.Query[o]); string result = string.Empty; try { Request request = RequestFactory.CreateRequest(string.Empty, httpRequest, Localization.GetLanguageInfo(httpRequest.Headers.Get("accept-language"))); Environment env = new Environment(request); result = m_WebApp.Services.LogoutRequest(env); httpResponse.ContentType = "text/html"; } catch (Exception e) { m_log.DebugFormat("[LOGOUT HANDLER]: Exception {0}: {1}", e.Message, e.StackTrace); } return WebAppUtils.StringToBytes(result); }
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { bool result = false; string[] p = SplitParams(path); if (p.Length > 0) { if (m_allowedTypes != AllowedRemoteDeleteTypes.None) { string assetID = p[0]; AssetBase asset = m_AssetService.Get(assetID); if (asset != null) { if (m_allowedTypes == AllowedRemoteDeleteTypes.All || (int)(asset.Flags & AssetFlags.Maptile) != 0) { result = m_AssetService.Delete(assetID); } else { m_log.DebugFormat( "[ASSET SERVER DELETE HANDLER]: Request to delete asset {0}, but type is {1} and allowed remote delete types are {2}", assetID, (AssetFlags)asset.Flags, m_allowedTypes); } } } } XmlSerializer xs = new XmlSerializer(typeof(bool)); return ServerUtils.SerializeResult(xs, result); }
protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { httpResponse.ContentType = "image/jpeg"; // StreamReader sr = new StreamReader(requestData); // string body = sr.ReadToEnd(); // sr.Close(); // body = body.Trim(); try { Dictionary<string, object> request = new Dictionary<string, object>(); foreach (string name in httpRequest.QueryString) request[name] = httpRequest.QueryString[name]; return SendWorldView(request); } catch (Exception e) { m_log.Debug("[WORLDVIEW]: Exception: " + e.ToString()); } return new Byte[0]; }
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { string[] p = SplitParams(path); if (p.Length > 0) { switch (p[0]) { case "plain": StreamReader sr = new StreamReader(request); string body = sr.ReadToEnd(); sr.Close(); return DoPlainMethods(body); case "crypt": byte[] buffer = new byte[request.Length]; long length = request.Length; if (length > 16384) length = 16384; request.Read(buffer, 0, (int)length); return DoEncryptedMethods(buffer); } } return new byte[0]; }
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // Try to parse the texture ID from the request URL NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); string names = query.GetOne("names"); string psize = query.GetOne("page_size"); string pnumber = query.GetOne("page"); if (m_PeopleService == null) return FailureResponse(names, (int)System.Net.HttpStatusCode.InternalServerError, httpResponse); if (string.IsNullOrEmpty(names) || names.Length < 3) return FailureResponse(names, (int)System.Net.HttpStatusCode.BadRequest, httpResponse); m_log.DebugFormat("[AVATAR PICKER SEARCH]: search for {0}", names); int page_size = (string.IsNullOrEmpty(psize) ? 500 : Int32.Parse(psize)); int page_number = (string.IsNullOrEmpty(pnumber) ? 1 : Int32.Parse(pnumber)); // Full content request httpResponse.StatusCode = (int)System.Net.HttpStatusCode.OK; //httpResponse.ContentLength = ??; httpResponse.ContentType = "application/llsd+xml"; List<UserData> users = m_PeopleService.GetUserData(names, page_size, page_number); LLSDAvatarPicker osdReply = new LLSDAvatarPicker(); osdReply.next_page_url = httpRequest.RawUrl; foreach (UserData u in users) osdReply.agents.Array.Add(ConvertUserData(u)); string reply = LLSDHelpers.SerialiseLLSDReply(osdReply); return System.Text.Encoding.UTF8.GetBytes(reply); }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { m_log.Info("-"); Dictionary<string, object> request = Werkzeuge.createDictionaryFromHttpRequest(httpRequest); string data = Werkzeuge.createPOSTDataFromHttpRequest(httpRequest); httpResponse.StatusCode = (int)HttpStatusCode.OK; httpResponse.StatusDescription = "OK"; httpResponse.ContentType = "test/plain"; if (Werkzeuge.getValueFromDictionary(request, "methode").ToLower() == "stop") { m_log.Info("[WakeUpService] Region " + Werkzeuge.getValueFromDictionary(request, "uuid") + " wants to be stopped."); restData restDataObject = new restData(); restDataObject.regionUUID = UUID.Parse(Werkzeuge.getValueFromDictionary(request, "uuid")); restDataObject.postDaten = Encoding.ASCII.GetBytes(data); restDataObject.startURI = Werkzeuge.getValueFromDictionary(request, "starturl"); restDataObject.stoptURI = Werkzeuge.getValueFromDictionary(request, "stopurl"); restDataObject.daten = data; restDataManager.add(restDataObject); Werkzeuge.makeHTTPCall(restDataObject.stoptURI, restDataObject.postDaten); } StreamWriter sw = new StreamWriter(httpResponse.OutputStream); sw.Write("ok"); return new byte[0]; }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // path = /wifi/... //m_log.DebugFormat("[Wifi]: path = {0}", path); //m_log.DebugFormat("[Wifi]: ip address = {0}", httpRequest.RemoteIPEndPoint); //foreach (object o in httpRequest.Query.Keys) // m_log.DebugFormat(" >> {0}={1}", o, httpRequest.Query[o]); httpResponse.ContentType = "text/html"; string resource = GetParam(path); //m_log.DebugFormat("[USER ACCOUNT HANDLER GET]: resource {0}", resource); Request request = WifiUtils.CreateRequest(string.Empty, httpRequest); Diva.Wifi.Environment env = new Diva.Wifi.Environment(request); string result = string.Empty; UUID userID = UUID.Zero; if (resource == string.Empty || resource == "/") { result = m_WebApp.Services.NewAccountGetRequest(env); } else { //UUID.TryParse(resource.Trim(new char[] {'/'}), out userID); if (resource.Trim(new char[] {'/'}).StartsWith("edit")) result = m_WebApp.Services.UserAccountGetRequest(env, userID); } return WifiUtils.StringToBytes(result); }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { string resource = GetParam(path); resource = resource.Trim(WebAppUtils.DirectorySeparatorChars); string resourcePath = System.IO.Path.Combine(m_LocalPath, resource); resourcePath = Uri.UnescapeDataString(resourcePath); m_log.DebugFormat("[Wifi]: resourcePath {0}", resourcePath); string type = WebAppUtils.GetContentType(resource); httpResponse.ContentType = type; //m_log.DebugFormat("[Wifi]: ContentType {0}", type); if (type.StartsWith("image")) return WebAppUtils.ReadBinaryResource(new string[] {resourcePath}); if (type.StartsWith("application") || type.StartsWith("text")) { string res = WebAppUtils.ReadTextResource(new string[] {resourcePath}, WebApp.MissingPage, true); return WebAppUtils.StringToBytes(res); } m_log.WarnFormat("[Wifi]: Could not find resource {0} in local path {1}", resource, m_LocalPath); httpResponse.ContentType = "text/plain"; string result = "Boo!"; return WebAppUtils.StringToBytes(result); }
public string FetchInventoryRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[FETCH INVENTORY HANDLER]: Received FetchInventory capabilty request"); OSDMap requestmap = (OSDMap)OSDParser.DeserializeLLSDXml(Utils.StringToBytes(request)); OSDArray itemsRequested = (OSDArray)requestmap["items"]; string reply; LLSDFetchInventory llsdReply = new LLSDFetchInventory(); foreach (OSDMap osdItemId in itemsRequested) { UUID itemId = osdItemId["item_id"].AsUUID(); InventoryItemBase item = m_inventoryService.GetItem(new InventoryItemBase(itemId, m_agentID)); if (item != null) { // We don't know the agent that this request belongs to so we'll use the agent id of the item // which will be the same for all items. llsdReply.agent_id = item.Owner; llsdReply.items.Array.Add(ConvertInventoryItem(item)); } } reply = LLSDHelpers.SerialiseLLSDReply(llsdReply); return reply; }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { string result = string.Empty; try { Request request = RequestFactory.CreateRequest(string.Empty, httpRequest); Diva.Wifi.Environment env = new Diva.Wifi.Environment(request); string resource = GetParam(path); //m_log.DebugFormat("[XXX]: resource {0}", resource); if (resource.StartsWith("/data/simulators")) { result = m_WebApp.Services.ConsoleSimulatorsRequest(env); httpResponse.ContentType = "application/xml"; } else if (resource.StartsWith("/heartbeat")) { result = m_WebApp.Services.ConsoleHeartbeat(env); httpResponse.ContentType = "application/xml"; } else { result = m_WebApp.Services.ConsoleRequest(env); httpResponse.ContentType = "text/html"; } } catch (Exception e) { m_log.DebugFormat("[CONSOLE HANDLER]: Exception {0}: {1}", e.Message, e.StackTrace); } return WebAppUtils.StringToBytes(result); }
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { AssetBase asset; XmlSerializer xs = new XmlSerializer(typeof(AssetBase)); try { asset = (AssetBase)xs.Deserialize(request); } catch (Exception) { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; return null; } string[] p = SplitParams(path); if (p.Length > 0) { string id = p[0]; bool result = m_AssetService.UpdateContent(id, asset.Data); xs = new XmlSerializer(typeof(bool)); return ServerUtils.SerializeResult(xs, result); } else { string id = m_AssetService.Store(asset); xs = new XmlSerializer(typeof(string)); return ServerUtils.SerializeResult(xs, id); } }
public override byte[] Handle(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // Not implemented yet Console.WriteLine("--- Get region --- " + path); httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented; return new byte[] { }; }
private string GetRemoteAddr(IOSHttpRequest httpRequest) { string remoteaddr = string.Empty; if (httpRequest.Headers["remote_addr"] != null) remoteaddr = httpRequest.Headers["remote_addr"]; return remoteaddr; }
public override byte[] Handle(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { byte[] data = ReadFully(request); string param = GetParam(path); string responseString = m_method(data, path, param); return Encoding.UTF8.GetBytes(responseString); }
public virtual void Handle( string path, Stream request, Stream response, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { RequestsReceived++; ProcessRequest(path, request, response, httpRequest, httpResponse); RequestsHandled++; }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // path = /wifi/... //m_log.DebugFormat("[Wifi]: path = {0}", path); //m_log.DebugFormat("[Wifi]: ip address = {0}", httpRequest.RemoteIPEndPoint); //foreach (object o in httpRequest.Query.Keys) // m_log.DebugFormat(" >> {0}={1}", o, httpRequest.Query[o]); string resource = GetParam(path); //m_log.DebugFormat("[Wifi]: resource {0}", resource); resource = Uri.UnescapeDataString(resource).Trim(WebAppUtils.DirectorySeparatorChars); Request request = RequestFactory.CreateRequest(resource, httpRequest); Diva.Wifi.Environment env = new Diva.Wifi.Environment(request); if (resource == string.Empty || resource.StartsWith("index.")) { if (m_WebApp.StatisticsUpdateInterval != TimeSpan.Zero) m_WebApp.Services.ComputeStatistics(); httpResponse.ContentType = "text/html"; return WebAppUtils.StringToBytes(m_WebApp.Services.DefaultRequest(env)); } else { string resourcePath = System.IO.Path.Combine(WebApp.DocsPath, resource); string type = WebAppUtils.GetContentType(resource); httpResponse.ContentType = type; //m_log.DebugFormat("[Wifi]: ContentType {0}", type); if (type.StartsWith("image")) return WebAppUtils.ReadBinaryResource(resourcePath); if (type.StartsWith("application")) { string res = WebAppUtils.ReadTextResource(resourcePath, true); return WebAppUtils.StringToBytes(res); } if (type.StartsWith("text")) { if (m_WebApp.StatisticsUpdateInterval != TimeSpan.Zero) m_WebApp.Services.ComputeStatistics(); resourcePath = Localization.LocalizePath(env, resource); Processor p = new Processor(m_WebApp.WifiScriptFace, env); string res = p.Process(WebAppUtils.ReadTextResource(resourcePath)); if (res == string.Empty) res = m_WebApp.Services.DefaultRequest(env); return WebAppUtils.StringToBytes(res); } } httpResponse.ContentType = "text/plain"; string result = "Boo!"; return WebAppUtils.StringToBytes(result); }
protected override byte[] ProcessRequest( string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { string[] p = SplitParams(path); if (p.Length == 0) return new byte[0]; return utf8.GetBytes(m_BakesService.Get(p[0])); }
public string FetchInventoryRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { //m_log.DebugFormat("[FETCH INVENTORY HANDLER]: Received FetchInventory capability request {0}", request); OSDMap requestmap = (OSDMap)OSDParser.DeserializeLLSDXml(Utils.StringToBytes(request)); OSDArray itemsRequested = (OSDArray)requestmap["items"]; string reply; LLSDFetchInventory llsdReply = new LLSDFetchInventory(); UUID[] itemIDs = new UUID[itemsRequested.Count]; int i = 0; foreach (OSDMap osdItemId in itemsRequested) { itemIDs[i++] = osdItemId["item_id"].AsUUID(); } InventoryItemBase[] items = null; if (m_agentID != UUID.Zero) { items = m_inventoryService.GetMultipleItems(m_agentID, itemIDs); if (items == null) { // OMG!!! One by one!!! This is fallback code, in case the backend isn't updated m_log.WarnFormat("[FETCH INVENTORY HANDLER]: GetMultipleItems failed. Falling back to fetching inventory items one by one."); items = new InventoryItemBase[itemsRequested.Count]; foreach (UUID id in itemIDs) items[i++] = m_inventoryService.GetItem(m_agentID, id); } } else { items = new InventoryItemBase[itemsRequested.Count]; foreach (UUID id in itemIDs) items[i++] = m_inventoryService.GetItem(UUID.Zero, id); } foreach (InventoryItemBase item in items) { if (item != null) { // We don't know the agent that this request belongs to so we'll use the agent id of the item // which will be the same for all items. llsdReply.agent_id = item.Owner; llsdReply.items.Array.Add(ConvertInventoryItem(item)); } } reply = LLSDHelpers.SerialiseLLSDReply(llsdReply); return reply; }
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[GET_DISPLAY_NAMES]: called {0}", httpRequest.Url.Query); NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); string[] ids = query.GetValues("ids"); if (m_UserManagement == null) { m_log.Error("[GET_DISPLAY_NAMES]: Cannot fetch display names without a user management component"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; return new byte[0]; } OSDMap osdReply = new OSDMap(); OSDArray agents = new OSDArray(); osdReply["agents"] = agents; foreach (string id in ids) { UUID uuid = UUID.Zero; if (UUID.TryParse(id, out uuid)) { string name = m_UserManagement.GetUserName(uuid); if (!string.IsNullOrEmpty(name)) { string[] parts = name.Split(new char[] {' '}); OSDMap osdname = new OSDMap(); // a date that is valid // osdname["display_name_next_update"] = OSD.FromDate(new DateTime(1970,1,1)); // but send one that blocks edition, since we actually don't suport this osdname["display_name_next_update"] = OSD.FromDate(DateTime.UtcNow.AddDays(8)); osdname["display_name_expires"] = OSD.FromDate(DateTime.UtcNow.AddMonths(1)); osdname["display_name"] = OSD.FromString(name); osdname["legacy_first_name"] = parts[0]; osdname["legacy_last_name"] = parts[1]; osdname["username"] = OSD.FromString(name); osdname["id"] = OSD.FromUUID(uuid); osdname["is_display_name_default"] = OSD.FromBoolean(true); agents.Add(osdname); } } } // Full content request httpResponse.StatusCode = (int)System.Net.HttpStatusCode.OK; //httpResponse.ContentLength = ??; httpResponse.ContentType = "application/llsd+xml"; string reply = OSDParser.SerializeLLSDXmlString(osdReply); return System.Text.Encoding.UTF8.GetBytes(reply); }
public static Request CreateRequest(string resource, IOSHttpRequest httpRequest, CultureInfo[] cinfo) { Request request = new Request(); request.Resource = resource; request.Cookies = httpRequest.Cookies; request.IPEndPoint = httpRequest.RemoteIPEndPoint; request.Query = httpRequest.Query; request.LanguageInfo = cinfo; return request; }
public static Request CreateRequest(string resource, IOSHttpRequest httpRequest) { Request request = new Request(); request.Resource = resource; request.Cookies = httpRequest.Cookies; request.IPEndPoint = httpRequest.RemoteIPEndPoint; request.Query = httpRequest.Query; request.LanguageInfo = Localization.GetLanguageInfo(httpRequest.Headers.Get("accept-language")); return request; }
public override byte[] Handle(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // Try to parse the texture ID from the request URL NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); string textureStr = query.GetOne("texture_id"); string format = query.GetOne("format"); //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr); if (m_assetService == null) { m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return null; } UUID textureID; if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID)) { // m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID); string[] formats; if (format != null && format != string.Empty) { formats = new string[1] { format.ToLower() }; } else { formats = WebUtil.GetPreferredImageTypes(httpRequest.Headers.Get("Accept")); if (formats.Length == 0) formats = new string[1] { DefaultFormat }; // default } // OK, we have an array with preferred formats, possibly with only one entry httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; foreach (string f in formats) { if (FetchTexture(httpRequest, httpResponse, textureID, f)) break; } } else { m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url); } // m_log.DebugFormat( // "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}", // textureID, httpResponse.StatusCode, httpResponse.ContentLength); httpResponse.Send(); return null; }
public virtual byte[] Handle( string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { RequestsReceived++; byte[] result = ProcessRequest(path, request, httpRequest, httpResponse); RequestsHandled++; return result; }
public static Dictionary<string, object> createDictionaryFromHttpRequest(IOSHttpRequest request) { Dictionary<string, object> dd = new Dictionary<string, object>(); foreach (string name in request.QueryString) { dd[name.ToLower()] = request.QueryString[name]; m_log.Info(name.ToLower() + " " + request.QueryString[name]); } return dd; }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { httpResponse.ContentType = "text/html"; Request request = WifiUtils.CreateRequest(string.Empty, httpRequest); Diva.Wifi.Environment env = new Diva.Wifi.Environment(request); string result = m_WebApp.Services.ForgotPasswordGetRequest(env); return WifiUtils.StringToBytes(result); }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { Dictionary<string, object> request = Werkzeuge.createDictionaryFromHttpRequest(httpRequest); if (Werkzeuge.getValueFromDictionary(request, "methode").ToLower() == "start") { m_log.Info("[WakeUpService] Region " + Werkzeuge.getValueFromDictionary(request, "uuid") + " will starts now."); startRegion(UUID.Parse(Werkzeuge.getValueFromDictionary(request, "uuid"))); } return Werkzeuge.StringToByteArray("ok"); }
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // Try to parse the texture ID from the request URL NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); string meshStr = query.GetOne("mesh_id"); // m_log.DebugFormat("Fetching mesh {0}", meshStr); UUID meshID = UUID.Zero; if (!String.IsNullOrEmpty(meshStr) && UUID.TryParse(meshStr, out meshID)) { if (m_assetService == null) { httpResponse.StatusCode = 404; httpResponse.ContentType = "text/plain"; byte[] data = Encoding.UTF8.GetBytes("The asset service is unavailable. So is your mesh."); httpResponse.Body.Write(data, 0, data.Length); return null; } AssetBase mesh = m_assetService.Get(meshID.ToString()); if (mesh != null) { if (mesh.Type == (SByte)AssetType.Mesh) { byte[] data = mesh.Data; httpResponse.Body.Write(data, 0, data.Length); httpResponse.ContentType = "application/vnd.ll.mesh"; httpResponse.StatusCode = 200; } // Optionally add additional mesh types here else { httpResponse.StatusCode = 404; httpResponse.ContentType = "text/plain"; byte[] data = Encoding.UTF8.GetBytes("Unfortunately, this asset isn't a mesh."); httpResponse.Body.Write(data, 0, data.Length); httpResponse.KeepAlive = false; } } else { httpResponse.StatusCode = 404; httpResponse.ContentType = "text/plain"; byte[] data = Encoding.UTF8.GetBytes("Your Mesh wasn't found. Sorry!"); httpResponse.Body.Write(data, 0, data.Length); httpResponse.KeepAlive = false; } } return null; }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { httpResponse.ContentType = "text/html"; Request request = RequestFactory.CreateRequest(string.Empty, httpRequest, Localization.GetLanguageInfo(httpRequest.Headers.Get("accept-language"))); Environment env = new Environment(request); string result = m_WebApp.Services.ForgotPasswordGetRequest(env); return WebAppUtils.StringToBytes(result); }
public void FetchInventoryDescendentsRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, ExpiringKey <UUID> BadRequests) { //m_log.DebugFormat("[XXX]: FetchInventoryDescendentsRequest in {0}, {1}", (m_Scene == null) ? "none" : m_Scene.Name, request); List <LLSDFetchInventoryDescendents> folders = null; List <UUID> bad_folders = new List <UUID>(); try { OSDArray foldersrequested = null; OSD tmp = OSDParser.DeserializeLLSDXml(httpRequest.InputStream); httpRequest.InputStream.Dispose(); OSDMap map = (OSDMap)tmp; if (map.TryGetValue("folders", out tmp) && tmp is OSDArray) { foldersrequested = tmp as OSDArray; } if (foldersrequested == null || foldersrequested.Count == 0) { httpResponse.RawBuffer = EmptyResponse; return; } folders = new List <LLSDFetchInventoryDescendents>(foldersrequested.Count); for (int i = 0; i < foldersrequested.Count; i++) { OSDMap mfolder = foldersrequested[i] as OSDMap; UUID id = mfolder["folder_id"].AsUUID(); if (BadRequests.ContainsKey(id)) { bad_folders.Add(id); } else { LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents(); try { llsdRequest.folder_id = id; llsdRequest.owner_id = mfolder["owner_id"].AsUUID(); llsdRequest.sort_order = mfolder["sort_order"].AsInteger(); llsdRequest.fetch_folders = mfolder["fetch_folders"].AsBoolean(); llsdRequest.fetch_items = mfolder["fetch_items"].AsBoolean(); } catch (Exception e) { m_log.Debug("[WEB FETCH INV DESC HANDLER]: caught exception doing OSD deserialize" + e.Message); continue; } folders.Add(llsdRequest); } } foldersrequested = null; map.Clear(); map = null; } catch (Exception e) { m_log.ErrorFormat("[FETCH INV DESC]: fail parsing request: {0}", e.Message); httpResponse.RawBuffer = EmptyResponse; return; } if (folders == null || folders.Count == 0) { if (bad_folders.Count == 0) { httpResponse.RawBuffer = EmptyResponse; return; } osUTF8 osu = OSUTF8Cached.Acquire(); osu.AppendASCII("[WEB FETCH INV DESC HANDLER]: Unable to fetch folders owned by Unknown user:"******" ..."); } m_log.Warn(osu.ToString()); } osu.Clear(); osu.AppendASCII("<llsd><map><key>folders</key><array /></map><map><key>bad_folders</key><array>"); foreach (UUID bad in bad_folders) { osu.AppendASCII("<map><key>folder_id</key><uuid>"); osu.AppendASCII(bad.ToString()); osu.AppendASCII("</uuid><key>error</key><string>Unknown</string></map>"); } osu.AppendASCII("</array></map></llsd>"); httpResponse.RawBuffer = OSUTF8Cached.GetArrayAndRelease(osu); return; } int total_folders = 0; int total_items = 0; UUID requester = folders[0].owner_id; List <InventoryCollection> invcollSet = Fetch(folders, bad_folders, ref total_folders, ref total_items); //m_log.DebugFormat("[XXX]: Got {0} folders from a request of {1}", invcollSet.Count, folders.Count); int invcollSetCount = 0; if (invcollSet != null) { invcollSetCount = invcollSet.Count; } int mem = 8192 + ((256 * invcollSetCount + 384 * total_folders + 1024 * total_items + 128 * bad_folders.Count) & 0x7ffff000); osUTF8 lastresponse = LLSDxmlEncode2.Start(mem); if (invcollSetCount > 0) { lastresponse.AppendASCII("<map><key>folders</key><array>"); int i = 0; InventoryCollection thiscoll; for (i = 0; i < invcollSetCount; i++) { thiscoll = invcollSet[i]; invcollSet[i] = null; LLSDxmlEncode2.AddMap(lastresponse); LLSDxmlEncode2.AddElem_agent_id(thiscoll.OwnerID, lastresponse); LLSDxmlEncode2.AddElem("descendents", thiscoll.Descendents, lastresponse); LLSDxmlEncode2.AddElem_folder_id(thiscoll.FolderID, lastresponse); if (thiscoll.Folders == null || thiscoll.Folders.Count == 0) { LLSDxmlEncode2.AddEmptyArray("categories", lastresponse); } else { LLSDxmlEncode2.AddArray("categories", lastresponse); foreach (InventoryFolderBase invFolder in thiscoll.Folders) { LLSDxmlEncode2.AddMap(lastresponse); LLSDxmlEncode2.AddElem_folder_id(invFolder.ID, lastresponse); LLSDxmlEncode2.AddElem_parent_id(invFolder.ParentID, lastresponse); LLSDxmlEncode2.AddElem_name(invFolder.Name, lastresponse); LLSDxmlEncode2.AddElem("type", invFolder.Type, lastresponse); LLSDxmlEncode2.AddElem("preferred_type", (int)-1, lastresponse); LLSDxmlEncode2.AddElem("version", invFolder.Version, lastresponse); LLSDxmlEncode2.AddEndMap(lastresponse); } LLSDxmlEncode2.AddEndArray(lastresponse); } if (thiscoll.Items == null || thiscoll.Items.Count == 0) { LLSDxmlEncode2.AddEmptyArray("items", lastresponse); } else { LLSDxmlEncode2.AddArray("items", lastresponse); foreach (InventoryItemBase invItem in thiscoll.Items) { invItem.ToLLSDxml(lastresponse); } LLSDxmlEncode2.AddEndArray(lastresponse); } LLSDxmlEncode2.AddElem_owner_id(thiscoll.OwnerID, lastresponse); LLSDxmlEncode2.AddElem("version", thiscoll.Version, lastresponse); LLSDxmlEncode2.AddEndMap(lastresponse); invcollSet[i] = null; } LLSDxmlEncode2.AddEndArrayAndMap(lastresponse); thiscoll = null; } else { lastresponse.AppendASCII("<map><key>folders</key><array /></map>"); } if (bad_folders.Count > 0) { lastresponse.AppendASCII("<map><key>bad_folders</key><array>"); foreach (UUID bad in bad_folders) { BadRequests.Add(bad); lastresponse.AppendASCII("<map><key>folder_id</key><uuid>"); lastresponse.AppendASCII(bad.ToString()); lastresponse.AppendASCII("</uuid><key>error</key><string>Unknown</string></map>"); } lastresponse.AppendASCII("</array></map>"); StringBuilder sb = osStringBuilderCache.Acquire(); sb.Append("[WEB FETCH INV DESC HANDLER]: Unable to fetch folders owned by "); sb.Append(requester.ToString()); sb.Append(" :"); int limit = 9; foreach (UUID bad in bad_folders) { sb.Append(" "); sb.Append(bad.ToString()); if (--limit < 0) { break; } } if (limit < 0) { sb.Append(" ..."); } m_log.Warn(osStringBuilderCache.GetStringAndRelease(sb)); } httpResponse.RawBuffer = LLSDxmlEncode2.EndToBytes(lastresponse); }
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[SIMULATION]: Stream handler called"); Hashtable keysvals = new Hashtable(); Hashtable headervals = new Hashtable(); string[] querystringkeys = httpRequest.QueryString.AllKeys; string[] rHeaders = httpRequest.Headers.AllKeys; keysvals.Add("uri", httpRequest.RawUrl); keysvals.Add("content-type", httpRequest.ContentType); keysvals.Add("http-method", httpRequest.HttpMethod); foreach (string queryname in querystringkeys) { keysvals.Add(queryname, httpRequest.QueryString[queryname]); } foreach (string headername in rHeaders) { headervals[headername] = httpRequest.Headers[headername]; } keysvals.Add("headers", headervals); keysvals.Add("querystringkeys", querystringkeys); Stream inputStream; if (httpRequest.ContentType == "application/x-gzip") { inputStream = new GZipStream(request, CompressionMode.Decompress); } else { inputStream = request; } Encoding encoding = Encoding.UTF8; StreamReader reader = new StreamReader(inputStream, encoding); string requestBody = reader.ReadToEnd(); reader.Close(); keysvals.Add("body", requestBody); httpResponse.StatusCode = 200; httpResponse.ContentType = "text/html"; httpResponse.KeepAlive = false; Hashtable responsedata = new Hashtable(); UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]); httpResponse.StatusCode = 404; return(encoding.GetBytes("false")); } DoAgentPut(keysvals, responsedata); httpResponse.StatusCode = (int)responsedata["int_response_code"]; return(encoding.GetBytes((string)responsedata["str_response_string"])); }
protected virtual byte[] ProcessRequest( string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { return(null); }
protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { httpResponse.KeepAlive = false; httpResponse.ContentType = "application/json"; if (m_SimulationService == null) { httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError; httpResponse.RawBuffer = Utils.falseStrBytes; return; } if (!Utils.GetParams(httpRequest.UriPath, out UUID agentID, out UUID regionID, out string action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", httpRequest.UriPath); httpResponse.StatusCode = (int)HttpStatusCode.NotFound; httpResponse.RawBuffer = Utils.falseStrBytes; return; } switch (httpRequest.HttpMethod) { case "QUERYACCESS": { if (agentID == UUID.Zero || regionID == UUID.Zero) { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; httpResponse.RawBuffer = Utils.falseStrBytes; return; } OSDMap args = Utils.DeserializeJSONOSMap(httpRequest); if (args == null) { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; httpResponse.RawBuffer = Utils.falseStrBytes; return; } DoQueryAccess(args, httpResponse, agentID, regionID); break; } case "PUT": { OSDMap args = Utils.DeserializeJSONOSMap(httpRequest); if (args == null) { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; httpResponse.RawBuffer = Utils.falseStrBytes; return; } DoAgentPut(args, httpResponse); break; } case "POST": { if (agentID == UUID.Zero) { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; httpResponse.RawBuffer = Utils.falseStrBytes; return; } OSDMap args = Utils.DeserializeJSONOSMap(httpRequest); if (args == null) { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; httpResponse.RawBuffer = Utils.falseStrBytes; return; } DoAgentPost(args, httpRequest, httpResponse, agentID); break; } case "DELETE": { if (agentID == UUID.Zero || regionID == UUID.Zero) { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; httpResponse.RawBuffer = Utils.falseStrBytes; return; } httpRequest.QueryAsDictionary.TryGetValue("auth", out string auth_token); DoAgentDelete(httpRequest, httpResponse, agentID, action, regionID, auth_token); break; } default: { httpResponse.StatusCode = (int)HttpStatusCode.MethodNotAllowed; httpResponse.RawBuffer = Utils.falseStrBytes; return; } } }
protected virtual byte[] ThrottledRequest( string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { return(new byte[0]); }
public string FetchInventoryDescendentsRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // lock (m_fetchLock) // { // m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Received request {0}", request); // nasty temporary hack here, the linden client falsely // identifies the uuid 00000000-0000-0000-0000-000000000000 // as a string which breaks us // // correctly mark it as a uuid // request = request.Replace("<string>00000000-0000-0000-0000-000000000000</string>", "<uuid>00000000-0000-0000-0000-000000000000</uuid>"); // another hack <integer>1</integer> results in a // System.ArgumentException: Object type System.Int32 cannot // be converted to target type: System.Boolean // request = request.Replace("<key>fetch_folders</key><integer>0</integer>", "<key>fetch_folders</key><boolean>0</boolean>"); request = request.Replace("<key>fetch_folders</key><integer>1</integer>", "<key>fetch_folders</key><boolean>1</boolean>"); Hashtable hash = new Hashtable(); try { hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request)); } catch (LLSD.LLSDParseException e) { m_log.ErrorFormat("[WEB FETCH INV DESC HANDLER]: Fetch error: {0}{1}" + e.Message, e.StackTrace); m_log.Error("Request: " + request); } ArrayList foldersrequested = (ArrayList)hash["folders"]; string response = ""; string bad_folders_response = ""; for (int i = 0; i < foldersrequested.Count; i++) { string inventoryitemstr = ""; Hashtable inventoryhash = (Hashtable)foldersrequested[i]; LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents(); try { LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest); } catch (Exception e) { m_log.Debug("[WEB FETCH INV DESC HANDLER]: caught exception doing OSD deserialize" + e); } LLSDInventoryDescendents reply = FetchInventoryReply(llsdRequest); if (null == reply) { bad_folders_response += "<uuid>" + llsdRequest.folder_id.ToString() + "</uuid>"; } else { inventoryitemstr = LLSDHelpers.SerialiseLLSDReply(reply); inventoryitemstr = inventoryitemstr.Replace("<llsd><map><key>folders</key><array>", ""); inventoryitemstr = inventoryitemstr.Replace("</array></map></llsd>", ""); } response += inventoryitemstr; } if (response.Length == 0) { /* Viewers expect a bad_folders array when not available */ if (bad_folders_response.Length != 0) { response = "<llsd><map><key>bad_folders</key><array>" + bad_folders_response + "</array></map></llsd>"; } else { response = "<llsd><map><key>folders</key><array /></map></llsd>"; } } else { if (bad_folders_response.Length != 0) { response = "<llsd><map><key>folders</key><array>" + response + "</array><key>bad_folders</key><array>" + bad_folders_response + "</array></map></llsd>"; } else { response = "<llsd><map><key>folders</key><array>" + response + "</array></map></llsd>"; } } // m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Replying to CAPS fetch inventory request"); //m_log.Debug("[WEB FETCH INV DESC HANDLER] "+response); return(response); // } }
protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { Dictionary <string, object> request = new Dictionary <string, object>(); foreach (string name in httpRequest.QueryString) { request[name] = httpRequest.QueryString[name]; } httpResponse.ContentType = "application/json"; mainDataSet _dataSet = new mainDataSet(); foreach (Scene _scene in m_scenes) { try { if (_scene != null) { regionDataSet _regionData = new regionDataSet(); _regionData.RegionName = ToUTF8(_scene.Name); _regionData.RegionEstate = ToUTF8(_scene.RegionInfo.EstateSettings.EstateName); _regionData.RegionImageUUID = _scene.RegionInfo.lastMapUUID.ToString(); _regionData.RegionPosition = _scene.RegionInfo.WorldLocX + "/" + _scene.RegionInfo.WorldLocY; _regionData.RegionPublicAccess = _scene.RegionInfo.EstateSettings.PublicAccess; _regionData.RegionSize = _scene.RegionInfo.RegionSizeX.ToString(); _regionData.RegionUUID = _scene.RegionInfo.RegionID.ToString(); _regionData.RegionIsVisibleInSearch = true; if (m_config.Configs["Hypergrid"] != null) { _regionData.RegionHomeURI = m_config.Configs["Hypergrid"].GetString("HomeURI", string.Empty); } _dataSet.RegionData.Add(_regionData); List <ILandObject> _landData = _scene.LandChannel.AllParcels(); foreach (ILandObject _parcel in _landData) { try { parcelDataSet _parcelSet = new parcelDataSet(); if (_parcel.LandData != null) { _parcelSet.ParcelName = ToUTF8(_parcel.LandData.Name); _parcelSet.ParcelDescription = ToUTF8(_parcel.LandData.Description); _parcelSet.ImageUUID = _parcel.LandData.SnapshotID.ToString(); _parcelSet.ParcelDwell = (int)_parcel.LandData.Dwell; _parcelSet.ParcelGroup = _parcel.LandData.GroupID.ToString(); _parcelSet.ParcelOwner.OwnerUUID = _parcel.LandData.OwnerID.ToString(); if (_parcelSet.ParcelOwner.OwnerUUID != _parcelSet.ParcelGroup) { if (m_userManager != null) { _parcelSet.ParcelOwner.OwnerName = m_userManager.GetUserName(_parcel.LandData.OwnerID); _parcelSet.ParcelOwner.OwnerHomeURI = m_userManager.GetUserHomeURL(_parcel.LandData.OwnerID); if (_parcelSet.ParcelOwner.OwnerHomeURI == String.Empty) { _parcelSet.ParcelOwner.OwnerHomeURI = _regionData.RegionHomeURI; } } } else { if (_parcelSet.ParcelOwner.OwnerUUID == _parcelSet.ParcelGroup) { IGroupsModule groups = _scene.RequestModuleInterface <IGroupsModule>(); if (groups != null) { GroupRecord _group = groups.GetGroupRecord(_parcel.LandData.GroupID); if (_group != null) { _parcelSet.ParcelOwner.OwnerName = _group.GroupName; _parcelSet.ParcelOwner.OwnerHomeURI = _regionData.RegionHomeURI; if (_dataSet.GroupData.Find(x => x.GroupUUID == _group.GroupID.ToString()) == null) { GroupDataSet _groupData = new GroupDataSet(); _groupData.GroupName = _group.GroupName; _groupData.GroupHomeURI = _regionData.RegionHomeURI; _groupData.GroupUUID = _group.GroupID.ToString(); _groupData.GroupImage = _group.GroupPicture.ToString(); _groupData.GroupShowInList = _group.ShowInList; _groupData.GroupAllowPublish = _group.AllowPublish; _groupData.GroupFounder = _group.FounderID.ToString(); _dataSet.GroupData.Add(_groupData); } } } } } _parcelSet.ParcelPosition = _parcel.CenterPoint.X + "/" + _parcel.CenterPoint.Y; if (_parcel.LandData.LandingType == (byte)LandingType.LandingPoint) { if (_parcel.LandData.UserLocation.X != 0 && _parcel.LandData.UserLocation.X != 0 && _parcel.LandData.UserLocation.X != 0) { _parcelSet.ParcelPosition = _parcel.LandData.UserLocation.X + "/" + _parcel.LandData.UserLocation.Y + "/" + _parcel.LandData.UserLocation.Z; } } _parcelSet.ParcelPrims = _parcel.GetParcelMaxPrimCount(); _parcelSet.ParcelSize = _parcel.LandData.Area; _parcelSet.ParcelBitmap = Convert.ToBase64String(_parcel.LandData.Bitmap); _parcelSet.ParcelPrice = _parcel.LandData.SalePrice; _parcelSet.ParcelIsVisibleInSearch = getStatusForSearch(_parcel); _parcelSet.ParcelIsForSale = getStatusForSale(_parcel); _parcelSet.ParentUUID = _scene.RegionInfo.RegionID.ToString(); _parcelSet.ParcelUUID = _parcel.LandData.GlobalID.ToString(); if ((request.ContainsKey("onlyVisibleInSearch") && _parcelSet.ParcelIsVisibleInSearch == true) || !request.ContainsKey("onlyVisibleInSearch")) { _dataSet.ParcelData.Add(_parcelSet); } } } catch { m_log.Error("Error while fetching land data."); } } foreach (SceneObjectGroup _cog in _scene.GetSceneObjectGroups()) { try { if (_cog != null) { if (_cog.IsTemporary == false && _cog.IsAttachment == false) { objectDataSet _objectData = new objectDataSet(); _objectData.ObjectName = ToUTF8(_cog.Name); _objectData.ObjectDescription = ToUTF8(_cog.Description); _objectData.ObjectUUID = _cog.RootPart.UUID.ToString(); _objectData.ParentUUID = _scene.LandChannel.GetLandObject(_cog.RootPart.AbsolutePosition.X, _cog.RootPart.AbsolutePosition.Y).LandData.GlobalID.ToString(); _objectData.ObjectIsForSale = false; _objectData.ObjectSalePrice = _cog.RootPart.SalePrice; if (_cog.RootPart.ObjectSaleType != (byte)0) { _objectData.ObjectIsForSale = true; } _objectData.ObjectIsForCopy = getStatusForCopy(_cog); _objectData.ObjectGroupUUID = _cog.GroupID.ToString(); _objectData.ObjectItemUUID = _cog.FromItemID.ToString(); _objectData.ObjectOwner.OwnerUUID = _cog.OwnerID.ToString(); if (_objectData.ObjectOwner.OwnerUUID != _objectData.ObjectGroupUUID) { if (m_userManager != null) { _objectData.ObjectOwner.OwnerName = m_userManager.GetUserName(_cog.OwnerID); _objectData.ObjectOwner.OwnerHomeURI = m_userManager.GetUserHomeURL(_cog.OwnerID); if (_objectData.ObjectOwner.OwnerHomeURI == String.Empty) { _objectData.ObjectOwner.OwnerHomeURI = _regionData.RegionHomeURI; } } } else { if (_objectData.ObjectOwner.OwnerUUID == _objectData.ObjectGroupUUID) { IGroupsModule groups = _scene.RequestModuleInterface <IGroupsModule>(); if (groups != null) { GroupRecord _group = groups.GetGroupRecord(_cog.RootPart.GroupID); if (_group != null) { _objectData.ObjectOwner.OwnerName = _group.GroupName; _objectData.ObjectOwner.OwnerHomeURI = _regionData.RegionHomeURI; if (_dataSet.GroupData.Find(x => x.GroupUUID == _group.GroupID.ToString()) == null) { GroupDataSet _groupData = new GroupDataSet(); _groupData.GroupName = _group.GroupName; _groupData.GroupHomeURI = _regionData.RegionHomeURI; _groupData.GroupUUID = _group.GroupID.ToString(); _groupData.GroupImage = _group.GroupPicture.ToString(); _groupData.GroupShowInList = _group.ShowInList; _groupData.GroupAllowPublish = _group.AllowPublish; _groupData.GroupFounder = _group.FounderID.ToString(); _dataSet.GroupData.Add(_groupData); } } } } } _objectData.ObjectPosition = _cog.RootPart.AbsolutePosition.X + "/" + _cog.RootPart.AbsolutePosition.Y + "/" + _cog.RootPart.AbsolutePosition.Z; _objectData.ObjectImageUUID = GuessImage(_cog); _objectData.ObjectIsVisibleInSearch = getStatusForSearch(_cog); if ((request.ContainsKey("onlyVisibleInSearch") && _objectData.ObjectIsVisibleInSearch == true) || !request.ContainsKey("onlyVisibleInSearch") || (request.ContainsKey("showFreeToCopy") && _objectData.ObjectIsForCopy == true)) { _dataSet.ObjectData.Add(_objectData); } } } } catch { m_log.Error("Error while fetching scene object groups."); } } foreach (ScenePresence _presence in _scene.GetScenePresences()) { try { if (_presence.PresenceType == PresenceType.User) { agentDataSet _agentData = new agentDataSet(); _agentData.AgentName = _presence.Name; if (_presence.AbsolutePosition != null) { _agentData.AgentPosition = _presence.AbsolutePosition.X + "/" + _presence.AbsolutePosition.Y + "/" + _presence.AbsolutePosition.Z; } _agentData.AgentUUID = _presence.UUID.ToString(); _agentData.AgentHomeURI = _scene.GetAgentHomeURI(_presence.UUID); if (_scene.LandChannel != null && _presence.AbsolutePosition != null) { _agentData.ParentUUID = _scene.LandChannel.GetLandObject(_presence.AbsolutePosition.X, _presence.AbsolutePosition.Y).LandData.GlobalID.ToString(); } _dataSet.AvatarData.Add(_agentData); } } catch { m_log.Error("Error while fetching presence data."); } } } }catch { m_log.Error("Error while fetching scene data."); } } return(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(_dataSet, Formatting.Indented))); }
public void RenderMaterialsPostCap(IOSHttpRequest request, IOSHttpResponse response, UUID agentID) { OSDMap req; try { req = (OSDMap)OSDParser.DeserializeLLSDXml(request.InputStream); } catch { response.StatusCode = (int)HttpStatusCode.BadRequest; return; } OSDArray respArr = new OSDArray(); OSD tmpOSD; if (req.TryGetValue("Zipped", out tmpOSD)) { OSD osd = null; byte[] inBytes = tmpOSD.AsBinary(); try { osd = ZDecompressBytesToOsd(inBytes); if (osd != null && osd is OSDArray) { foreach (OSD elem in (OSDArray)osd) { try { UUID id = new UUID(elem.AsBinary(), 0); lock (materialslock) { if (m_Materials.ContainsKey(id)) { OSDMap matMap = new OSDMap(); matMap["ID"] = OSD.FromBinary(id.GetBytes()); matMap["Material"] = m_Materials[id].toOSD(); respArr.Add(matMap); } else { m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString()); // Theoretically we could try to load the material from the assets service, // but that shouldn't be necessary because the viewer should only request // materials that exist in a prim on the region, and all of these materials // are already stored in m_regionMaterials. } } } catch (Exception e) { m_log.Error("Error getting materials in response to viewer request", e); continue; } } } } catch (Exception e) { m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e); response.StatusCode = (int)HttpStatusCode.BadRequest; return; } } OSDMap resp = new OSDMap(); resp["Zipped"] = ZCompressOSD(respArr, false); response.RawBuffer = Encoding.UTF8.GetBytes(OSDParser.SerializeLLSDXmlString(resp)); //m_log.Debug("[Materials]: cap request: " + request); //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary())); //m_log.Debug("[Materials]: cap response: " + response); }
protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { //m_log.DebugFormat("[MAP SERVICE IMAGE HANDLER]: Received {0}", path); string body; using (StreamReader sr = new StreamReader(httpRequest.InputStream)) body = sr.ReadToEnd(); body = body.Trim(); httpRequest.InputStream.Dispose(); try { Dictionary <string, object> request = ServerUtils.ParseQueryString(body); httpResponse.StatusCode = (int)HttpStatusCode.OK; if (!request.ContainsKey("X") || !request.ContainsKey("Y") || !request.ContainsKey("DATA")) { httpResponse.RawBuffer = Util.ResultFailureMessage("Bad request."); return; } int x = 0, y = 0; //UUID scopeID = new UUID("07f8d88e-cd5e-4239-a0ed-843f75d09992"); UUID scopeID = UUID.Zero; Int32.TryParse(request["X"].ToString(), out x); Int32.TryParse(request["Y"].ToString(), out y); if (request.ContainsKey("SCOPE")) { UUID.TryParse(request["SCOPE"].ToString(), out scopeID); } m_log.DebugFormat("[MAP ADD SERVER CONNECTOR]: Received map data for region at {0}-{1}", x, y); //string type = "image/jpeg"; //if (request.ContainsKey("TYPE")) // type = request["TYPE"].ToString(); if (m_GridService != null) { IPAddress ipAddr = httpRequest.RemoteIPEndPoint.Address; GridRegion r = m_GridService.GetRegionByPosition(scopeID, (int)Util.RegionToWorldLoc((uint)x), (int)Util.RegionToWorldLoc((uint)y)); if (r != null) { if (r.ExternalEndPoint.Address.ToString() != ipAddr.ToString()) { m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be trying to impersonate region in IP {1}", ipAddr, r.ExternalEndPoint.Address); httpResponse.RawBuffer = Util.ResultFailureMessage("IP address of caller does not match IP address of registered region"); //return; } } else { m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be rogue. Region not found at coordinates {1}-{2}", ipAddr, x, y); httpResponse.RawBuffer = Util.ResultFailureMessage("Region not found at given coordinates"); //return; } } byte[] data = Convert.FromBase64String(request["DATA"].ToString()); bool result = m_MapService.AddMapTile(x, y, data, scopeID, out string reason); if (result) { httpResponse.RawBuffer = Util.sucessResultSuccess; } else { httpResponse.RawBuffer = Util.ResultFailureMessage(reason); } return; } catch (Exception e) { m_log.ErrorFormat("[MAP SERVICE IMAGE HANDLER]: Exception {0} {1}", e.Message, e.StackTrace); } httpResponse.RawBuffer = Util.ResultFailureMessage("Unexpected server error"); }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { return(Service.ServeMessage()); }
protected virtual void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, byte[] data) { }
public virtual void Handle(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { RequestsReceived++; if (httpRequest.HttpMethod != m_httMethod) { httpResponse.StatusCode = (int)HttpStatusCode.NotFound; return; } if (httpRequest.InputStream == null || httpRequest.InputStream.Length == 0) { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; return; } if (m_maxDatasize > 0 && httpRequest.InputStream.Length > m_maxDatasize) { httpResponse.StatusCode = (int)HttpStatusCode.RequestEntityTooLarge; return; } byte[] data; try { Stream request = httpRequest.InputStream; if (request is MemoryStream) { data = ((MemoryStream)request).ToArray(); } else { request.Seek(0, SeekOrigin.Begin); using (MemoryStream ms = new MemoryStream((int)request.Length)) { request.CopyTo(ms); data = ms.ToArray(); } } request.Dispose(); } catch { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; return; } if (m_Auth != null) { if (!m_Auth.Authenticate(httpRequest.Headers, httpResponse.AddHeader, out HttpStatusCode statusCode)) { httpResponse.StatusCode = (int)statusCode; return; } } try { if (m_processRequest != null) { m_processRequest(httpRequest, httpResponse, data); } else { ProcessRequest(httpRequest, httpResponse, data); } } catch { httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError; } RequestsHandled++; }
private void WriteTextureData(IOSHttpRequest request, IOSHttpResponse response, AssetBase texture, string format) { string range = request.Headers.GetOne("Range"); if (!String.IsNullOrEmpty(range)) // JP2's only { // Range request int start, end; if (TryParseRange(range, out start, out end)) { // Before clamping start make sure we can satisfy it in order to avoid // sending back the last byte instead of an error status if (start >= texture.Data.Length) { // m_log.DebugFormat( // "[GETTEXTURE]: Client requested range for texture {0} starting at {1} but texture has end of {2}", // texture.ID, start, texture.Data.Length); // Stricly speaking, as per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, we should be sending back // Requested Range Not Satisfiable (416) here. However, it appears that at least recent implementations // of the Linden Lab viewer (3.2.1 and 3.3.4 and probably earlier), a viewer that has previously // received a very small texture may attempt to fetch bytes from the server past the // range of data that it received originally. Whether this happens appears to depend on whether // the viewer's estimation of how large a request it needs to make for certain discard levels // (http://wiki.secondlife.com/wiki/Image_System#Discard_Level_and_Mip_Mapping), chiefly discard // level 2. If this estimate is greater than the total texture size, returning a RequestedRangeNotSatisfiable // here will cause the viewer to treat the texture as bad and never display the full resolution // However, if we return PartialContent (or OK) instead, the viewer will display that resolution. // response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable; // response.AddHeader("Content-Range", String.Format("bytes */{0}", texture.Data.Length)); // response.StatusCode = (int)System.Net.HttpStatusCode.OK; response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; response.ContentType = texture.Metadata.ContentType; } else { // Handle the case where no second range value was given. This is equivalent to requesting // the rest of the entity. if (end == -1) { end = int.MaxValue; } end = Utils.Clamp(end, 0, texture.Data.Length - 1); start = Utils.Clamp(start, 0, end); int len = end - start + 1; // m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID); // Always return PartialContent, even if the range covered the entire data length // We were accidentally sending back 404 before in this situation // https://issues.apache.org/bugzilla/show_bug.cgi?id=51878 supports sending 206 even if the // entire range is requested, and viewer 3.2.2 (and very probably earlier) seems fine with this. // // We also do not want to send back OK even if the whole range was satisfiable since this causes // HTTP textures on at least Imprudence 1.4.0-beta2 to never display the final texture quality. // if (end > maxEnd) // response.StatusCode = (int)System.Net.HttpStatusCode.OK; // else response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; response.ContentLength = len; response.ContentType = texture.Metadata.ContentType; response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length)); response.RawBuffer = texture.Data; response.RawBufferStart = start; response.RawBufferLen = len; } } else { m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range); response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; } } else // JP2's or other formats { // Full content request response.StatusCode = (int)System.Net.HttpStatusCode.OK; response.ContentLength = texture.Data.Length; if (format == DefaultFormat) { response.ContentType = texture.Metadata.ContentType; } else { response.ContentType = "image/" + format; } response.RawBuffer = texture.Data; response.RawBufferStart = 0; response.RawBufferLen = texture.Data.Length; } // if (response.StatusCode < 200 || response.StatusCode > 299) // m_log.WarnFormat( // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); // else // m_log.DebugFormat( // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); }
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // Try to parse the texture ID from the request URL NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); string textureStr = query.GetOne("texture_id"); string format = query.GetOne("format"); //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr); if (m_assetService == null) { m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return(null); } UUID textureID; if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID)) { // m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID); string[] formats; if (!string.IsNullOrEmpty(format)) { formats = new string[1] { format.ToLower() }; } else { formats = WebUtil.GetPreferredImageTypes(httpRequest.Headers.Get("Accept")); if (formats.Length == 0) { formats = new string[1] { DefaultFormat } } ; // default } // OK, we have an array with preferred formats, possibly with only one entry httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; foreach (string f in formats) { if (FetchTexture(httpRequest, httpResponse, textureID, f)) { break; } } } else { m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url); } // m_log.DebugFormat( // "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}", // textureID, httpResponse.StatusCode, httpResponse.ContentLength); return(null); }
public void ProcessRequest(IOSHttpRequest request, IOSHttpResponse response, UUID AgentId, Caps cap) { if (request.HttpMethod != "POST") { response.StatusCode = (int)HttpStatusCode.NotFound; return; } ScenePresence avatar; if (!m_scene.TryGetScenePresence(AgentId, out avatar) || !m_scene.Permissions.CanIssueEstateCommand(AgentId, false)) { response.StatusCode = (int)HttpStatusCode.Unauthorized; return; } if (m_scene.RegionInfo == null || m_scene.RegionInfo.EstateSettings == null) { response.StatusCode = (int)HttpStatusCode.NotImplemented; return; } OSDMap r; try { r = (OSDMap)OSDParser.Deserialize(request.InputStream); } catch (Exception ex) { m_log.Error("[UPLOAD OBJECT ASSET MODULE]: Error deserializing message " + ex.ToString()); response.StatusCode = (int)HttpStatusCode.BadRequest; return; } bool ok = true; try { string estateName = r["estate_name"].AsString(); UUID invoice = r["invoice"].AsUUID(); //int sunHour = r["sun_hour"].AsInteger(); //bool sunFixed = r["is_sun_fixed"].AsBoolean(); bool externallyVisible = r["is_externally_visible"].AsBoolean(); bool allowDirectTeleport = r["allow_direct_teleport"].AsBoolean(); bool denyAnonymous = r["deny_anonymous"].AsBoolean(); bool denyAgeUnverified = r["deny_age_unverified"].AsBoolean(); bool alloVoiceChat = r["allow_voice_chat"].AsBoolean(); // taxfree is now !AllowAccessOverride bool overridePublicAccess = !m_scene.RegionInfo.EstateSettings.TaxFree; if (r.ContainsKey("override_public_access")) { overridePublicAccess = !r["override_public_access"].AsBoolean(); } bool allowEnvironmentOverride = m_scene.RegionInfo.EstateSettings.AllowEnvironmentOverride; if (r.ContainsKey("override_environment")) { allowEnvironmentOverride = !r["override_environment"].AsBoolean(); } ok = m_EstateModule.handleEstateChangeInfoCap(estateName, invoice, externallyVisible, allowDirectTeleport, denyAnonymous, denyAgeUnverified, alloVoiceChat, overridePublicAccess, allowEnvironmentOverride); } catch { ok = false; } response.StatusCode = ok ? (int)HttpStatusCode.OK : (int)HttpStatusCode.BadRequest; }
protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); m_log.DebugFormat("[XESTATE HANDLER]: query String: {0}", body); try { lock (m_RequestLock) { Dictionary <string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) { return(FailureResult()); } string method = request["METHOD"].ToString(); request.Remove("METHOD"); try { m_EstateModule.InInfoUpdate = false; switch (method) { case "update_covenant": return(UpdateCovenant(request)); case "update_estate": return(UpdateEstate(request)); case "estate_message": return(EstateMessage(request)); case "teleport_home_one_user": return(TeleportHomeOneUser(request)); case "teleport_home_all_users": return(TeleportHomeAllUsers(request)); } } finally { m_EstateModule.InInfoUpdate = false; } } } catch (Exception e) { m_log.Debug("[XESTATE]: Exception {0}" + e.ToString()); } return(FailureResult()); }
protected void DoAgentPost(OSDMap args, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID agentID) { OSD tmpOSD; EntityTransferContext ctx = new EntityTransferContext(); if (args.TryGetValue("context", out tmpOSD) && tmpOSD is OSDMap) { ctx.Unpack((OSDMap)tmpOSD); } AgentDestinationData data = CreateAgentDestinationData(); UnpackData(args, data); GridRegion destination = new GridRegion(); destination.RegionID = data.uuid; destination.RegionLocX = data.x; destination.RegionLocY = data.y; destination.RegionName = data.name; GridRegion gatekeeper = ExtractGatekeeper(data); AgentCircuitData aCircuit = new AgentCircuitData(); try { aCircuit.UnpackAgentCircuitData(args); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message); httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; httpResponse.RawBuffer = Util.UTF8.GetBytes("false"); return; } GridRegion source = null; if (args.TryGetValue("source_uuid", out tmpOSD)) { source = new GridRegion(); source.RegionID = UUID.Parse(tmpOSD.AsString()); source.RegionLocX = Int32.Parse(args["source_x"].AsString()); source.RegionLocY = Int32.Parse(args["source_y"].AsString()); source.RegionName = args["source_name"].AsString(); if (args.TryGetValue("source_server_uri", out tmpOSD)) { source.RawServerURI = tmpOSD.AsString(); } else { source.RawServerURI = null; } } OSDMap resp = new OSDMap(2); string reason = string.Empty; bool result = CreateAgent(source, gatekeeper, destination, aCircuit, data.flags, ctx, out reason); resp["reason"] = OSD.FromString(reason); resp["success"] = OSD.FromBoolean(result); // Let's also send out the IP address of the caller back to the caller (HG 1.5) resp["your_ip"] = OSD.FromString(httpRequest.RemoteIPEndPoint.Address.ToString()); httpResponse.StatusCode = (int)HttpStatusCode.OK; httpResponse.RawBuffer = Util.UTF8.GetBytes(OSDParser.SerializeJsonString(resp)); httpResponse.KeepAlive = (data.flags & (uint)(TeleportFlags.ViaLogin | TeleportFlags.ViaHGLogin)) != (uint)TeleportFlags.ViaLogin; }
public void RenderMaterialsPutCap(IOSHttpRequest request, IOSHttpResponse response, UUID agentID) { OSDMap req; try { req = (OSDMap)OSDParser.DeserializeLLSDXml(request.InputStream); } catch { response.StatusCode = (int)HttpStatusCode.BadRequest; return; } OSDMap materialsFromViewer = null; OSDArray respArr = new OSDArray(); OSD tmpOSD; HashSet <SceneObjectPart> parts = new HashSet <SceneObjectPart>(); if (req.TryGetValue("Zipped", out tmpOSD)) { OSD osd = null; byte[] inBytes = tmpOSD.AsBinary(); try { osd = ZDecompressBytesToOsd(inBytes); if (osd != null && osd is OSDMap) { materialsFromViewer = osd as OSDMap; if (materialsFromViewer.TryGetValue("FullMaterialsPerFace", out tmpOSD) && (tmpOSD is OSDArray)) { OSDArray matsArr = tmpOSD as OSDArray; try { foreach (OSDMap matsMap in matsArr) { uint primLocalID = 0; try { primLocalID = matsMap["ID"].AsUInteger(); } catch (Exception e) { m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message); continue; } SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID); if (sop == null) { m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString()); continue; } if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID)) { m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID); continue; } OSDMap mat = null; try { mat = matsMap["Material"] as OSDMap; } catch (Exception e) { m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message); continue; } Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length); if (te == null) { m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID); continue; } int face = -1; UUID oldid = UUID.Zero; Primitive.TextureEntryFace faceEntry = null; if (matsMap.TryGetValue("Face", out tmpOSD)) { face = tmpOSD.AsInteger(); faceEntry = te.CreateFace((uint)face); } else { faceEntry = te.DefaultTexture; } if (faceEntry == null) { continue; } UUID id; FaceMaterial newFaceMat = null; if (mat == null) { // This happens then the user removes a material from a prim id = UUID.Zero; } else { newFaceMat = new FaceMaterial(mat); if (newFaceMat.DiffuseAlphaMode == 1 && newFaceMat.NormalMapID == UUID.Zero && newFaceMat.SpecularMapID == UUID.Zero ) { id = UUID.Zero; } else { newFaceMat.genID(); id = newFaceMat.ID; } } oldid = faceEntry.MaterialID; if (oldid == id) { continue; } if (faceEntry != null) { faceEntry.MaterialID = id; //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id); // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually sop.Shape.TextureEntry = te.GetBytes(9); } if (oldid != UUID.Zero) { RemoveMaterial(oldid); } lock (materialslock) { if (id != UUID.Zero) { if (m_Materials.ContainsKey(id)) { m_MaterialsRefCount[id]++; } else { m_Materials[id] = newFaceMat; m_MaterialsRefCount[id] = 1; m_changed[newFaceMat] = Util.GetTimeStamp(); } } } if (!parts.Contains(sop)) { parts.Add(sop); } } foreach (SceneObjectPart sop in parts) { if (sop.ParentGroup != null && !sop.ParentGroup.IsDeleted) { sop.TriggerScriptChangedEvent(Changed.TEXTURE); sop.ScheduleFullUpdate(); sop.ParentGroup.HasGroupChanged = true; } } } catch (Exception e) { m_log.Warn("[Materials]: exception processing received material ", e); response.StatusCode = (int)HttpStatusCode.BadRequest; return; } } } } catch (Exception e) { m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e); response.StatusCode = (int)HttpStatusCode.BadRequest; return; } } OSDMap resp = new OSDMap(); resp["Zipped"] = ZCompressOSD(respArr, false); response.RawBuffer = Encoding.UTF8.GetBytes(OSDParser.SerializeLLSDXmlString(resp)); //m_log.Debug("[Materials]: cap request: " + request); //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary())); //m_log.Debug("[Materials]: cap response: " + response); }
protected override byte[] ProcessRequest( string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { return(Util.UTF8.GetBytes(Report())); }
protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary <string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) { return(FailureResult()); } string method = request["METHOD"].ToString(); switch (method) { case "register": return(Register(request)); case "deregister": return(Deregister(request)); case "get_neighbours": return(GetNeighbours(request)); case "get_region_by_uuid": return(GetRegionByUUID(request)); case "get_region_by_position": return(GetRegionByPosition(request)); case "get_region_by_name": return(GetRegionByName(request)); case "get_regions_by_name": return(GetRegionsByName(request)); case "get_region_range": return(GetRegionRange(request)); case "get_default_regions": return(GetDefaultRegions(request)); case "get_default_hypergrid_regions": return(GetDefaultHypergridRegions(request)); case "get_fallback_regions": return(GetFallbackRegions(request)); case "get_hyperlinks": return(GetHyperlinks(request)); case "get_region_flags": return(GetRegionFlags(request)); case "get_grid_extra_features": return(GetGridExtraFeatures(request)); } m_log.DebugFormat("[GRID HANDLER]: unknown method request {0}", method); } catch (Exception e) { m_log.ErrorFormat("[GRID HANDLER]: Exception {0} {1}", e.Message, e.StackTrace); } return(FailureResult()); }
public string FetchInventoryDescendentsRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { //m_log.DebugFormat("[XXX]: FetchInventoryDescendentsRequest in {0}, {1}", (m_Scene == null) ? "none" : m_Scene.Name, request); Hashtable hash = new Hashtable(); try { hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request)); } catch (LLSD.LLSDParseException e) { m_log.ErrorFormat("[WEB FETCH INV DESC HANDLER]: Fetch error: {0}{1}" + e.Message, e.StackTrace); m_log.Error("Request: " + request); } ArrayList foldersrequested = (ArrayList)hash["folders"]; hash.Clear(); List <LLSDFetchInventoryDescendents> folders = new List <LLSDFetchInventoryDescendents>(); for (int i = 0; i < foldersrequested.Count; i++) { Hashtable inventoryhash = (Hashtable)foldersrequested[i]; LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents(); try { LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest); } catch (Exception e) { m_log.Debug("[WEB FETCH INV DESC HANDLER]: caught exception doing OSD deserialize" + e); continue; } folders.Add(llsdRequest); } foldersrequested.Clear(); if (folders.Count == 0) { return("<llsd><map><key>folders</key><array /></map></llsd>"); } List <UUID> bad_folders = new List <UUID>(); int total_folders = 0; int total_items = 0; List <InventoryCollection> invcollSet = Fetch(folders, bad_folders, ref total_folders, ref total_items); //m_log.DebugFormat("[XXX]: Got {0} folders from a request of {1}", invcollSet.Count, folders.Count); int invcollSetCount = 0; if (invcollSet != null) { invcollSetCount = invcollSet.Count; } int mem = 8192 + ((256 * invcollSetCount + 384 * total_folders + 1024 * total_items + 128 * bad_folders.Count) & 0x7ffff000); StringBuilder lastresponse = new StringBuilder(mem); lastresponse.Append("<llsd>"); if (invcollSetCount > 0) { lastresponse.Append("<map><key>folders</key><array>"); int i = 0; InventoryCollection thiscoll; for (i = 0; i < invcollSetCount; i++) { thiscoll = invcollSet[i]; invcollSet[i] = null; LLSDxmlEncode.AddMap(lastresponse); LLSDxmlEncode.AddElem("agent_id", thiscoll.OwnerID, lastresponse); LLSDxmlEncode.AddElem("descendents", thiscoll.Descendents, lastresponse); LLSDxmlEncode.AddElem("folder_id", thiscoll.FolderID, lastresponse); if (thiscoll.Folders == null || thiscoll.Folders.Count == 0) { LLSDxmlEncode.AddEmptyArray("categories", lastresponse); } else { LLSDxmlEncode.AddArray("categories", lastresponse); foreach (InventoryFolderBase invFolder in thiscoll.Folders) { LLSDxmlEncode.AddMap(lastresponse); LLSDxmlEncode.AddElem("folder_id", invFolder.ID, lastresponse); LLSDxmlEncode.AddElem("parent_id", invFolder.ParentID, lastresponse); LLSDxmlEncode.AddElem("name", invFolder.Name, lastresponse); LLSDxmlEncode.AddElem("type", invFolder.Type, lastresponse); LLSDxmlEncode.AddElem("preferred_type", (int)-1, lastresponse); LLSDxmlEncode.AddElem("version", invFolder.Version, lastresponse); LLSDxmlEncode.AddEndMap(lastresponse); } LLSDxmlEncode.AddEndArray(lastresponse); } if (thiscoll.Items == null || thiscoll.Items.Count == 0) { LLSDxmlEncode.AddEmptyArray("items", lastresponse); } else { LLSDxmlEncode.AddArray("items", lastresponse); foreach (InventoryItemBase invItem in thiscoll.Items) { invItem.ToLLSDxml(lastresponse); } LLSDxmlEncode.AddEndArray(lastresponse); } LLSDxmlEncode.AddElem("owner_id", thiscoll.OwnerID, lastresponse); LLSDxmlEncode.AddElem("version", thiscoll.Version, lastresponse); LLSDxmlEncode.AddEndMap(lastresponse); invcollSet[i] = null; } lastresponse.Append("</array></map>"); thiscoll = null; } else { lastresponse.Append("<map><key>folders</key><array /></map>"); } //m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Bad folders {0}", string.Join(", ", bad_folders)); if (bad_folders.Count > 0) { lastresponse.Append("<map><key>bad_folders</key><array>"); foreach (UUID bad in bad_folders) { lastresponse.Append("<map><key>folder_id</key><uuid>"); lastresponse.Append(bad.ToString()); lastresponse.Append("</uuid><key>error</key><string>Unknown</string></map>"); } lastresponse.Append("</array></map>"); } lastresponse.Append("</llsd>"); return(lastresponse.ToString()); }
protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); // We need to check the authorization header //httpRequest.Headers["authorization"] ... //m_log.DebugFormat("[XXX]: query String: {0}", body); string method = string.Empty; try { Dictionary <string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) { return(FailureResult()); } method = request["METHOD"].ToString(); switch (method) { case "createuser": if (m_AllowCreateUser) { return(CreateUser(request)); } else { break; } case "getaccount": return(GetAccount(request)); case "getaccounts": return(GetAccounts(request)); case "setaccount": if (m_AllowSetAccount) { return(StoreAccount(request)); } else { break; } } m_log.DebugFormat("[USER SERVICE HANDLER]: unknown method request: {0}", method); } catch (Exception e) { m_log.DebugFormat("[USER SERVICE HANDLER]: Exception in method {0}: {1}", method, e); } return(FailureResult()); }
public byte[] Handle(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { return(Util.UTF8.GetBytes(Report())); }