public async Task CreateInventory(UUID parentUuid, OSD newInventory, bool createLink, InventoryManager.ItemCreatedCallback callback) { var cap = getInventoryCap(); if (cap == null) { Logger.Log("No AIS3 Capability!", Helpers.LogLevel.Warning, Client); return; } try { UUID tid = UUID.Random(); string url = $"{cap}/category/{parentUuid}?tid={tid}"; var content = new ByteArrayContent(OSDParser.SerializeLLSDXmlBytes(newInventory)); content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/llsd+xml"); var req = httpClient.PostAsync(url, content); var reply = await req; if (reply.IsSuccessStatusCode && OSDParser.Deserialize(reply.Content.ReadAsStringAsync().Result) is OSDMap map && map["_embedded"] is OSDMap embedded) { List <InventoryItem> items = !createLink ? parseItemsFromResponse((OSDMap)embedded["items"]) : parseLinksFromResponse((OSDMap)embedded["links"]); callback(true, items.First()); } else { Logger.Log("Could not create inventory: " + reply.ReasonPhrase, Helpers.LogLevel.Warning); callback(false, null); } }
/// <summary> /// Parses a VWRAP Launch Document file /// </summary> /// <param name="path">Filename of the launch document to parse</param> /// <returns>The parsed document, or null on failure</returns> public static LaunchDocument FromFile(string path) { try { using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { OSDMap launchMap = OSDParser.Deserialize(stream) as OSDMap; if (launchMap != null) { LaunchDocument document = new LaunchDocument(); document.LoginUrl = launchMap["loginurl"].AsString(); document.WelcomeUrl = launchMap["welcomeurl"].AsString(); // --loginpage document.EconomyUrl = launchMap["economyurl"].AsString(); // --helperuri document.AboutUrl = launchMap["abouturl"].AsString(); document.RegisterUrl = launchMap["registerurl"].AsString(); document.HelpUrl = launchMap["helpurl"].AsString(); document.PasswordUrl = launchMap["passwordurl"].AsString(); // Not a valid launch doc without a loginurl if (String.IsNullOrEmpty(document.LoginUrl)) { return(null); } document.Region = launchMap["region"].AsString(); OSDMap authenticatorMap = launchMap["authenticator"] as OSDMap; if (authenticatorMap != null) { document.IsLoginUrlCapability = (authenticatorMap["type"].AsString() == "capability"); } OSDMap identifierMap = launchMap["identifier"] as OSDMap; if (identifierMap != null) { document.AccountName = identifierMap["account_name"].AsString(); document.Name = identifierMap["name"].AsString(); // Legacy support if (String.IsNullOrEmpty(document.Name)) { string first = identifierMap["first_name"].AsString(); string last = identifierMap["last_name"].AsString(); document.Name = (first + " " + last).Trim(); } } return(document); } } } catch { } return(null); }
public static bool TryGetMessage <TMessage>(System.IO.Stream stream, out TMessage message) where TMessage : class, IMessage, new() { message = null; try { // DEBUG: byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); m_log.Debug(System.Text.Encoding.UTF8.GetString(buffer)); OSDMap map = OSDParser.Deserialize(buffer) as OSDMap; //OSDMap map = OSDParser.Deserialize(request.Body) as OSDMap; if (map != null) { message = new TMessage(); message.Deserialize(map); } } catch (Exception ex) { m_log.Warn("Failed to deserialize incoming data: " + ex.Message); } return(message != null); }
private void ChildAvatarUpdateHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response) { OSDMap requestMap = null; try { requestMap = OSDParser.Deserialize(request.Body) as OSDMap; } catch { } if (requestMap != null) { IScenePresence child; if (m_scene.TryGetPresence(requestMap["agent_id"].AsUUID(), out child) && child.IsChildPresence) { child.RelativePosition = requestMap["position"].AsVector3(); child.RelativeRotation = requestMap["rotation"].AsQuaternion(); if (child is LLAgent) { LLAgent childAgent = (LLAgent)child; childAgent.CameraPosition = requestMap["camera_center"].AsVector3(); childAgent.CameraAtAxis = requestMap["camera_at"].AsVector3(); childAgent.CameraLeftAxis = requestMap["camera_left"].AsVector3(); childAgent.CameraUpAxis = requestMap["camera_up"].AsVector3(); childAgent.DrawDistance = (float)requestMap["draw_distance"].AsReal(); } } } }
public override string ToPrettyString(Direction direction) { if (direction == this.Direction) { IMessage message = null; OSD osd = OSDParser.Deserialize(this.ResponseBytes); OSDMap data = (OSDMap)osd; if (data.ContainsKey("body")) { message = MessageUtils.DecodeEvent(this.Name, (OSDMap)data["body"]); } else { message = MessageUtils.DecodeEvent(this.Name, data); } if (message != null) { return(PacketDecoder.MessageToString(message, 0)); } else { return("No Decoder for " + this.Name + Environment.NewLine + osd.ToString()); } } else { return(String.Empty); } }
private void RegionOnlineHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response) { OSDMap requestMap = null; try { requestMap = OSDParser.Deserialize(request.Body) as OSDMap; } catch { } if (requestMap != null) { Vector3d minPosition = new Vector3d(requestMap["region_x"].AsReal(), requestMap["region_y"].AsReal(), 0.0d); Vector3d maxPosition = new Vector3d(minPosition.X + 256.0d, minPosition.Y + 256.0d, 4096.0d); SceneInfo scene = new SceneInfo { ID = requestMap["region_id"].AsUUID(), Name = requestMap["region_name"].AsString(), MinPosition = minPosition, MaxPosition = maxPosition, PublicSeedCapability = requestMap["public_region_seed_capability"].AsUri() }; //m_log.Debug(m_scene.Name + " adding neighbor " + scene.Name); m_scene.AddNeighbor(scene); } else { m_log.Warn("Failed to parse region/online request"); } }
/// <summary> /// POST URL-encoded form data to a web service that returns LLSD or /// JSON data /// </summary> public static OSDMap PostToService(string url, NameValueCollection data) { string errorMessage; try { string queryString = BuildQueryString(data); byte[] requestData = System.Text.Encoding.UTF8.GetBytes(queryString); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "POST"; request.ContentLength = requestData.Length; request.ContentType = "application/x-www-form-urlencoded"; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(requestData, 0, requestData.Length); using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { string responseStr = null; try { responseStr = responseStream.GetStreamString(); OSD responseOSD = OSDParser.Deserialize(responseStr); if (responseOSD.Type == OSDType.Map) { return((OSDMap)responseOSD); } else { errorMessage = "Response format was invalid."; } } catch (Exception ex) { if (!String.IsNullOrEmpty(responseStr)) { errorMessage = "Failed to parse the response:\n" + responseStr; } else { errorMessage = "Failed to retrieve the response: " + ex.Message; } } } } } catch (Exception ex) { m_log.Warn("POST to URL " + url + " failed: " + ex.Message); errorMessage = ex.Message; } return(new OSDMap { { "Message", OSD.FromString("Service request failed. " + errorMessage) } }); }
private bool SendRezAvatarRequest(LLAgent agent, SceneInfo neighbor, bool isChild, out IPAddress simHost, out int simPort, out Uri seedCapability) { simHost = null; simPort = 0; seedCapability = null; Uri rezAvatarRequestCap; if (neighbor.TryGetCapability("rez_avatar/request", out rezAvatarRequestCap)) { string firstName, lastName; Util.GetFirstLastName(agent.Name, out firstName, out lastName); // Find the presence position relative to this neighbor Vector3 relativePosition = agent.ScenePosition - new Vector3(neighbor.MinPosition - m_scene.MinPosition); // Calculate the direction this agent is currently facing Vector3 lookAt = Vector3.UnitY * agent.RelativeRotation; // Create the template rez_avatar/request message OSDMap rezAvatarRequest = new OSDMap { { "agent_id", OSD.FromUUID(agent.ID) }, { "session_id", OSD.FromUUID(agent.SessionID) }, { "position", OSD.FromVector3(relativePosition) }, { "look_at", OSD.FromVector3(lookAt) }, { "velocity", OSD.FromVector3(agent.Velocity) }, { "child", OSD.FromBoolean(isChild) } }; OSDMap rezAvatarResponse = null; try { // Send the message and get a response rezAvatarResponse = OSDParser.Deserialize(UntrustedHttpWebRequest.PostToUntrustedUrl( rezAvatarRequestCap, OSDParser.SerializeJsonString(rezAvatarRequest))) as OSDMap; } catch { } if (rezAvatarResponse != null) { return(RezChildAgentReplyHandler(agent, rezAvatarResponse, out simHost, out simPort, out seedCapability)); } else { m_log.Warn(m_scene.Name + " failed to create a child agent on " + neighbor.Name + ", rez_avatar/request failed"); } } else { m_log.Warn(neighbor.Name + " does not have a rez_avatar/request capability"); } return(false); }
private void RezAvatarRequestHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response) { OSDMap requestMap = null; try { requestMap = OSDParser.Deserialize(request.Body) as OSDMap; } catch (Exception ex) { m_log.Warn("Failed to decode rez_avatar/request message: " + ex.Message); response.Status = HttpStatusCode.BadRequest; return; } UUID userID = requestMap["agent_id"].AsUUID(); UUID sessionID = requestMap["session_id"].AsUUID(); bool childAgent = requestMap["child"].AsBoolean(); Vector3 startPosition = requestMap["position"].AsVector3(); Vector3 velocity = requestMap["velocity"].AsVector3(); Vector3 lookAt = requestMap["look_at"].AsVector3(); OSDMap responseMap = new OSDMap(); UserSession session; if (m_userClient.TryGetSession(sessionID, out session)) { session.CurrentSceneID = m_scene.ID; session.CurrentPosition = startPosition; session.CurrentLookAt = lookAt; if (!childAgent) { // Set the agent velocity in case this is a child->root upgrade (border cross) IScenePresence presence; if (m_scene.TryGetPresence(session.User.ID, out presence) && presence is IPhysicalPresence) { ((IPhysicalPresence)presence).Velocity = velocity; } RezRootAgent(session, startPosition, lookAt, ref responseMap); } else { RezChildAgent(session, startPosition, lookAt, ref responseMap); } } else { m_log.Error("Received a rez_avatar/request for agent " + userID + " with missing sessionID " + sessionID); responseMap["message"] = OSD.FromString("Session does not exist"); } WebUtil.SendJSONResponse(response, responseMap); }
private void TextureStatsHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response) { try { OSD osd = OSDParser.Deserialize(request.Body); m_log.Info("Received a TextureStats message: " + osd.ToString()); } catch (Exception) { m_log.Warn("Failed to decode TextureStats message"); } }
/// <summary> /// Since there are no consistencies in the way web requests are /// formed, we need to do a little guessing about the result format. /// Keys: /// Success|success == the success fail of the request /// _RawResult == the raw string that came back /// _Result == the OSD unpacked string /// </summary> private static OSDMap CanonicalizeResults(string response, bool deserializeResponse, bool returnRawResult) { OSDMap result = new OSDMap(); if (returnRawResult) { OSD responseOSD = OSDParser.Deserialize(response); if (responseOSD.Type == OSDType.Map) { result = (OSDMap)responseOSD; } return(result); } // Default values result["Success"] = OSD.FromBoolean(true); result["success"] = OSD.FromBoolean(true); result["_RawResult"] = OSD.FromString(response); result["_Result"] = new OSDMap(); if (response.Equals("true", StringComparison.OrdinalIgnoreCase)) { return(result); } if (response.Equals("false", StringComparison.OrdinalIgnoreCase)) { result["Success"] = OSD.FromBoolean(false); result["success"] = OSD.FromBoolean(false); return(result); } if (deserializeResponse) { try { OSD responseOSD = OSDParser.Deserialize(response); if (responseOSD.Type == OSDType.Map) { result["_Result"] = responseOSD; return(result); } } catch (Exception e) { // don't need to treat this as an error... we're just guessing anyway MainConsole.Instance.InfoFormat("[WebUtils] couldn't decode <{0}>: {1}", response, e.Message); } } return(result); }
public virtual void Handle(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { RequestsReceived++; if (httpRequest.HttpMethod != m_httMethod) { httpResponse.StatusCode = (int)HttpStatusCode.NotFound; return; } OSDMap args; try { args = (OSDMap)OSDParser.Deserialize(httpRequest.InputStream); } catch { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; return; } if (args == null) { 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, args); } else { ProcessRequest(httpRequest, httpResponse, args); } } catch { httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError; } RequestsHandled++; }
void RequestCompletedHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error) { _Request = request; OSD result = null; if (responseData != null) { try { result = OSDParser.Deserialize(responseData); } catch (Exception ex) { error = ex; } } FireCompleteCallback(result, error); }
public static ViewerEnvironment FromOSDString(string s) { try { OSD eosd = OSDParser.Deserialize(s); ViewerEnvironment VEnv = new ViewerEnvironment(); VEnv.FromOSD(eosd); return(VEnv); } catch { } return(null); }
private void RegionOfflineHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response) { OSDMap requestMap = null; try { requestMap = OSDParser.Deserialize(request.Body) as OSDMap; } catch { } if (requestMap != null) { UUID regionID = requestMap["region_id"].AsUUID(); m_log.Debug(m_scene.Name + " removing neighbor " + regionID); m_scene.RemoveNeighbor(regionID); } }
/// <summary> /// Check to see if the client has baked textures that belong to banned clients /// </summary> /// <param name="avatarID"></param> /// <param name="textureEntry"></param> public void CheckForBannedViewer(UUID avatarID, Primitive.TextureEntry textureEntry) { try { //Read the website once! if (m_map == null) { m_map = OSDParser.Deserialize(Utilities.ReadExternalWebsite(m_viewerTagURL)) as OSDMap; } if (m_map == null) { m_map = OSDParser.Deserialize(System.IO.File.ReadAllText(m_viewerTagFile)) as OSDMap; } if (m_map == null) { return; //Can't find it } //This is the givaway texture! for (int i = 0; i < textureEntry.FaceTextures.Length; i++) { if (textureEntry.FaceTextures[i] != null) { if (m_map.ContainsKey(textureEntry.FaceTextures[i].TextureID.ToString())) { OSDMap viewerMap = (OSDMap)m_map[textureEntry.FaceTextures[i].TextureID.ToString()]; //Check the names if (IsViewerBanned(viewerMap["name"].ToString())) { IGridWideMessageModule messageModule = m_registry.RequestModuleInterface <IGridWideMessageModule>(); if (messageModule != null) { messageModule.KickUser(avatarID, "You cannot use " + viewerMap["name"] + " in this grid."); } break; } break; } } } } catch { } }
public bool Start(Simian simian) { m_simian = simian; m_userClient = m_simian.GetAppModule <IUserClient>(); // Library user and inventory creation string libraryOwnerName = "Library Owner"; IConfig config = simian.Config.Configs["StandaloneInventoryClient"]; if (config != null) { libraryOwnerName = config.GetString("LibraryOwnerName", "Library Owner"); } CreateLibrary(libraryOwnerName); // Deserialize inventories from disk m_fileDataStore = m_simian.GetAppModule <FileDataStore>(); if (m_fileDataStore != null) { IList <SerializedData> inventories = m_fileDataStore.Deserialize(UUID.Zero, "Inventory"); for (int i = 0; i < inventories.Count; i++) { string name = inventories[i].Name; UUID ownerID; if (UUID.TryParse(name, out ownerID)) { OSDMap map = null; try { map = OSDParser.Deserialize(inventories[i].Data) as OSDMap; } catch (Exception) { } if (map != null) { DeserializeInventory(ownerID, map); } else { m_log.Warn("Failed to deserialize inventory file " + name); } } } } return(true); }
/// <summary> /// Make a GET or GET-like request to a web service that returns LLSD /// or JSON data /// </summary> public static OSDMap ServiceRequest(string url, string httpVerb) { string errorMessage; try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = httpVerb; using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { try { string responseStr = responseStream.GetStreamString(); OSD responseOSD = OSDParser.Deserialize(responseStr); if (responseOSD.Type == OSDType.Map) { return((OSDMap)responseOSD); } else { errorMessage = "Response format was invalid."; } } catch { errorMessage = "Failed to parse the response."; } } } } catch (Exception ex) { m_log.Warn(httpVerb + " on URL " + url + " failed: " + ex.Message); errorMessage = ex.Message; } return(new OSDMap { { "Message", OSD.FromString("Service request failed. " + errorMessage) } }); }
/// <summary> /// Retrieves a web service using HTTP GET and returns it as an OSDMap /// </summary> /// <param name="url">URL to fetch</param> /// <returns>An OSDMap containing the response. If an error occurred, the map will contain /// a key/value pair named Message</returns> public static OSDMap GetService(string url) { string errorMessage; try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "GET"; using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { try { string responseStr = responseStream.GetStreamString(); OSD responseOSD = OSDParser.Deserialize(responseStr); if (responseOSD.Type == OSDType.Map) { return((OSDMap)responseOSD); } else { errorMessage = "Response format was invalid (" + responseOSD.Type + ")"; } } catch { errorMessage = "Failed to parse the response (" + responseStream.Length + " bytes of " + response.ContentType + ")"; } } } } catch (Exception ex) { m_log.Warn("GET from URL " + url + " failed: " + ex); errorMessage = ex.Message; } return(new OSDMap { { "Message", OSD.FromString("Service request failed. " + errorMessage) } }); }
/// <summary> /// Check to see if the client has baked textures that belong to banned clients /// </summary> /// <param name="client"></param> /// <param name="textureEntry"></param> public void CheckForBannedViewer(IClientAPI client, Primitive.TextureEntry textureEntry) { try { //Read the website once! if (m_map == null) { m_map = (OSDMap)OSDParser.Deserialize(Utilities.ReadExternalWebsite("http://auroraserver.ath.cx:8080/client_tags.xml")); } //This is the givaway texture! for (int i = 0; i < textureEntry.FaceTextures.Length; i++) { if (textureEntry.FaceTextures[i] != null) { if (m_map.ContainsKey(textureEntry.FaceTextures[i].TextureID.ToString())) { OSDMap viewerMap = (OSDMap)m_map[textureEntry.FaceTextures[i].TextureID.ToString()]; //Check the names if (BannedViewers.Contains(viewerMap["name"].ToString())) { client.Kick("You cannot use " + viewerMap["name"] + " in this sim."); IEntityTransferModule transferModule = client.Scene.RequestModuleInterface <IEntityTransferModule> (); if (transferModule != null) { transferModule.IncomingCloseAgent(((Scene)client.Scene), client.AgentId); } } else if (m_banEvilViewersByDefault && viewerMap.ContainsKey("evil") && (viewerMap["evil"].AsBoolean() == true)) { client.Kick("You cannot use " + viewerMap["name"] + " in this sim."); IEntityTransferModule transferModule = client.Scene.RequestModuleInterface <IEntityTransferModule> (); if (transferModule != null) { transferModule.IncomingCloseAgent(((Scene)client.Scene), client.AgentId); } } } } } } catch { } }
public bool Start(Simian simian) { m_fileDataStore = simian.GetAppModule <FileDataStore>(); if (m_fileDataStore != null) { IList <SerializedData> users = m_fileDataStore.Deserialize(UUID.Zero, "Users"); for (int i = 0; i < users.Count; i++) { string name = users[i].Name; UUID ownerID; OSDMap map = null; try { map = OSDParser.Deserialize(users[i].Data) as OSDMap; } catch (Exception) { } if (name == "identities") { if (map != null) { DeserializeIdentities(map); } else { m_log.Warn("Failed to deserialize user identity file"); } } else if (UUID.TryParse(name, out ownerID)) { if (map != null) { DeserializeUser(map); } else { m_log.Warn("Failed to deserialize user file " + name); } } } } return(true); }
public static bool TryGetOSDMap(System.IO.Stream stream, out OSDMap map) { try { // DEBUG: byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); m_log.Debug(System.Text.Encoding.UTF8.GetString(buffer)); map = OSDParser.Deserialize(buffer) as OSDMap; //map = OSDParser.Deserialize(request.Body) as OSDMap; } catch (Exception ex) { m_log.Warn("Failed to deserialize incoming data: " + ex.Message); map = null; } return(map != null); }
/// <summary> /// Since there are no consistencies in the way web requests are /// formed, we need to do a little guessing about the result format. /// Keys: /// Success|success == the success fail of the request /// _RawResult == the raw string that came back /// _Result == the OSD unpacked string /// </summary> private static OSDMap CanonicalizeResults(string response) { OSDMap result = new OSDMap(); // Default values result["Success"] = OSD.FromBoolean(true); result["success"] = OSD.FromBoolean(true); result["_RawResult"] = OSD.FromString(response); result["_Result"] = new OSDMap(); if (response.Equals("true", System.StringComparison.OrdinalIgnoreCase)) { return(result); } if (response.Equals("false", System.StringComparison.OrdinalIgnoreCase)) { result["Success"] = OSD.FromBoolean(false); result["success"] = OSD.FromBoolean(false); return(result); } try { OSD responseOSD = OSDParser.Deserialize(response); if (responseOSD.Type == OSDType.Map) { result["_Result"] = (OSDMap)responseOSD; return(result); } } catch { // don't need to treat this as an error... we're just guessing anyway // m_log.DebugFormat("[WEB UTIL] couldn't decode <{0}>: {1}",response,e.Message); } return(result); }
/// <summary> /// Check to see if the client has baked textures that belong to banned clients /// </summary> /// <param name="client"></param> /// <param name="textureEntry"></param> public void CheckForBannedViewer(IClientAPI client, Primitive.TextureEntry textureEntry) { try { //Read the website once! if (m_map == null) { m_map = (OSDMap)OSDParser.Deserialize(Utilities.ReadExternalWebsite(m_viewerTagURL)); } //This is the givaway texture! for (int i = 0; i < textureEntry.FaceTextures.Length; i++) { if (textureEntry.FaceTextures[i] != null) { if (m_map.ContainsKey(textureEntry.FaceTextures[i].TextureID.ToString())) { OSDMap viewerMap = (OSDMap)m_map[textureEntry.FaceTextures[i].TextureID.ToString()]; //Check the names if (IsViewerBanned(viewerMap["name"].ToString(), viewerMap["evil"].AsBoolean())) { client.Kick("You cannot use " + viewerMap["name"] + " in this sim."); IEntityTransferModule transferModule = client.Scene.RequestModuleInterface <IEntityTransferModule> (); if (transferModule != null) { transferModule.IncomingCloseAgent(((Scene)client.Scene), client.AgentId); } break; } break; } } } } catch { } }
private Color4 GetFaceColor(Primitive.TextureEntryFace face) { Color4 color; if (face.TextureID == UUID.Zero) { return(face.RGBA); } if (!m_colors.TryGetValue(face.TextureID, out color)) { bool fetched = false; // Attempt to fetch the texture metadata UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC); AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString()); if (metadata != null) { OSDMap map = null; try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { } if (map != null) { color = map["X-JPEG2000-RGBA"].AsColor4(); fetched = true; } } if (!fetched) { // Fetch the texture, decode and get the average color, // then save it to a temporary metadata asset AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString()); if (textureAsset != null) { int width, height; color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height); OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } }; metadata = new AssetBase { Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)), Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(), Flags = AssetFlags.Collectable, FullID = metadataID, ID = metadataID.ToString(), Local = true, Temporary = true, Name = String.Empty, Type = (sbyte)AssetType.Unknown }; m_scene.AssetService.Store(metadata); } else { color = new Color4(0.5f, 0.5f, 0.5f, 1.0f); } } m_colors[face.TextureID] = color; } return(color * face.RGBA); }
///<summary> /// ///</summary> private void UploadMapTile(IScene scene) { m_log.DebugFormat("[SIMIAN MAPTILE]: upload maptile for {0}", scene.RegionInfo.RegionName); // Create a PNG map tile and upload it to the AddMapTile API byte[] pngData = Utils.EmptyBytes; IMapImageGenerator tileGenerator = scene.RequestModuleInterface <IMapImageGenerator>(); if (tileGenerator == null) { m_log.Warn("[SIMIAN MAPTILE]: Cannot upload PNG map tile without an ImageGenerator"); return; } using (Image mapTile = tileGenerator.CreateMapTile()) { using (MemoryStream stream = new MemoryStream()) { mapTile.Save(stream, ImageFormat.Png); pngData = stream.ToArray(); } } List <MultipartForm.Element> postParameters = new List <MultipartForm.Element>() { new MultipartForm.Parameter("X", scene.RegionInfo.RegionLocX.ToString()), new MultipartForm.Parameter("Y", scene.RegionInfo.RegionLocY.ToString()), new MultipartForm.File("Tile", "tile.png", "image/png", pngData) }; string errorMessage = null; int tickstart = Util.EnvironmentTickCount(); // Make the remote storage request try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(m_serverUrl); request.Timeout = 20000; request.ReadWriteTimeout = 5000; using (HttpWebResponse response = MultipartForm.Post(request, postParameters)) { using (Stream responseStream = response.GetResponseStream()) { string responseStr = responseStream.GetStreamString(); OSD responseOSD = OSDParser.Deserialize(responseStr); if (responseOSD.Type == OSDType.Map) { OSDMap responseMap = (OSDMap)responseOSD; if (responseMap["Success"].AsBoolean()) { return; } errorMessage = "Upload failed: " + responseMap["Message"].AsString(); } else { errorMessage = "Response format was invalid:\n" + responseStr; } } } } catch (WebException we) { errorMessage = we.Message; if (we.Status == WebExceptionStatus.ProtocolError) { HttpWebResponse webResponse = (HttpWebResponse)we.Response; errorMessage = String.Format("[{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription); } } catch (Exception ex) { errorMessage = ex.Message; } finally { // This just dumps a warning for any operation that takes more than 100 ms int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); m_log.DebugFormat("[SIMIAN MAPTILE]: map tile uploaded in {0}ms", tickdiff); } m_log.WarnFormat("[SIMIAN MAPTILE]: Failed to store {0} byte tile for {1}: {2}", pngData.Length, scene.RegionInfo.RegionName, errorMessage); }
private int GetFaceColor(Primitive.TextureEntryFace face) { int color; Color4 ctmp = Color4.White; if (face.TextureID == UUID.Zero) { return(warp_Color.White); } if (!m_colors.TryGetValue(face.TextureID, out color)) { bool fetched = false; // Attempt to fetch the texture metadata string cacheName = "MAPCLR" + face.TextureID.ToString(); AssetBase metadata = m_scene.AssetService.GetCached(cacheName); if (metadata != null) { OSDMap map = null; try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { } if (map != null) { ctmp = map["X-RGBA"].AsColor4(); fetched = true; } } if (!fetched) { // Fetch the texture, decode and get the average color, // then save it to a temporary metadata asset AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString()); if (textureAsset != null) { int width, height; ctmp = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height); OSDMap data = new OSDMap { { "X-RGBA", OSD.FromColor4(ctmp) } }; metadata = new AssetBase { Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)), Description = "Metadata for texture color" + face.TextureID.ToString(), Flags = AssetFlags.Collectable, FullID = UUID.Zero, ID = cacheName, Local = true, Temporary = true, Name = String.Empty, Type = (sbyte)AssetType.Unknown }; m_scene.AssetService.Store(metadata); } else { ctmp = new Color4(0.5f, 0.5f, 0.5f, 1.0f); } } color = ConvertColor(ctmp); m_colors[face.TextureID] = color; } return(color); }
private static OSDMap ServiceFormRequestWorker(string url, NameValueCollection data, int timeout) { int reqnum = RequestNumber++; string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown"; if (DebugLevel >= 3) { m_log.DebugFormat( "[WEB UTIL]: HTTP OUT {0} ServiceForm {1} {2} (timeout {3})", reqnum, method, url, timeout); } string errorMessage = "unknown error"; int tickstart = Util.EnvironmentTickCount(); int tickdata = 0; string queryString = null; try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "POST"; request.Timeout = timeout; request.KeepAlive = false; request.MaximumAutomaticRedirections = 10; request.ReadWriteTimeout = timeout / 4; request.Headers[OSHeaderRequestID] = reqnum.ToString(); if (data != null) { queryString = BuildQueryString(data); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(queryString); request.ContentLength = buffer.Length; request.ContentType = "application/x-www-form-urlencoded"; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buffer, 0, buffer.Length); } // capture how much time was spent writing, this may seem silly // but with the number concurrent requests, this often blocks tickdata = Util.EnvironmentTickCountSubtract(tickstart); using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { string responseStr = null; responseStr = responseStream.GetStreamString(); OSD responseOSD = OSDParser.Deserialize(responseStr); if (responseOSD.Type == OSDType.Map) { return((OSDMap)responseOSD); } } } } catch (WebException we) { errorMessage = we.Message; if (we.Status == WebExceptionStatus.ProtocolError) { HttpWebResponse webResponse = (HttpWebResponse)we.Response; errorMessage = String.Format("[{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription); } } catch (Exception ex) { errorMessage = ex.Message; } finally { int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > LongCallTime) { m_log.InfoFormat( "[WEB UTIL]: Slow ServiceForm request {0} {1} {2} took {3}ms, {4}ms writing, {5}", reqnum, method, url, tickdiff, tickdata, queryString != null ? (queryString.Length > MaxRequestDiagLength) ? queryString.Remove(MaxRequestDiagLength) : queryString : ""); } else if (DebugLevel >= 4) { m_log.DebugFormat( "[WEB UTIL]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } m_log.WarnFormat("[WEB UTIL]: ServiceForm request {0} {1} {2} failed: {2}", reqnum, method, url, errorMessage); return(ErrorResponseMap(errorMessage)); }
private void SeedCapabilityHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response) { OSDArray seedCapRequest = null; try { seedCapRequest = OSDParser.Deserialize(request.Body) as OSDArray; } catch (Exception ex) { m_log.Warn("Failed to deserialize incoming seed capability request: " + ex.Message); response.Status = HttpStatusCode.BadRequest; return; } if (seedCapRequest != null) { User user; if (m_userClient.TryGetUser(cap.OwnerID, out user)) { //m_log.Debug("Received a seed capability request from " + user.Name + ": " + OSDParser.SerializeJsonString(seedCapRequest)); // Put all of the requested capabilities into a dictionary Dictionary <string, Uri> capabilities = new Dictionary <string, Uri>(seedCapRequest.Count); for (int i = 0; i < seedCapRequest.Count; i++) { capabilities[seedCapRequest[i].AsString()] = null; } // Special handling for EventQueueGet since we set "sendResponseAfterCallback=false" for it m_scene.Capabilities.TryAssignCapability(user.ID, capabilities, false, m_scene.ID, "EventQueueGet"); // Create all of the capabilities we support, if they were requested List <string> capNames = new List <string>(capabilities.Keys); foreach (string capName in capNames) { m_scene.Capabilities.TryAssignCapability(user.ID, capabilities, true, m_scene.ID, capName); } // Build the response OSDMap responseMap = new OSDMap(capabilities.Count); foreach (KeyValuePair <string, Uri> kvp in capabilities) { if (kvp.Value != null) { responseMap[kvp.Key] = OSD.FromUri(kvp.Value); } } m_log.Debug("Returning " + responseMap.Count + " capabilities to " + user.Name + " from the seed capability"); // Send the response WebUtil.SendXMLResponse(response, responseMap); } else { m_log.Warn("Received a seed capability request from an unknown agent " + cap.OwnerID); response.Status = HttpStatusCode.NotFound; } } else { m_log.Warn("Failed to deserialize incoming seed capability request"); response.Status = HttpStatusCode.BadRequest; } }
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; }