/// <summary> /// Get the Asset data for an item, must be used when requesting a Notecard /// </summary> /// <param name="item"></param> public void GetInventoryAsset(InventoryItem item) { LLUUID TransferID = LLUUID.Random(); AssetRequestDownload request = new AssetRequestDownload(TransferID); request.Size = int.MaxValue; // Number of bytes expected request.Received = 0; // Number of bytes received request.UpdateLastPacketTime(); // last time we recevied a packet for this request htDownloadRequests[TransferID] = request; // prep packet based on asset type Packet packet; switch (item.Type) { case 5: //Shirt case 13: //Bodyshape packet = AssetPacketHelpers.TransferRequestDirect(slClient.Network.SessionID, slClient.Network.AgentID, TransferID, item.AssetID, item.Type); break; default: packet = AssetPacketHelpers.TransferRequest(slClient.Network.SessionID, slClient.Network.AgentID, TransferID, item); break; } // Send packet slClient.Network.SendPacket(packet); #if DEBUG_PACKETS slClient.DebugLog(packet); #endif request.Completed.WaitOne(); item.SetAssetData(request.AssetData); }
/// <summary> /// Upload an asset to Second Life /// </summary> /// <param name="asset">The asset to be uploaded</param> /// <returns>The Asset ID of the completed upload</returns> public LLUUID UploadAsset(Asset asset) { if (curUploadRequest != null) { throw new Exception("An existing asset upload is currently in-progress."); } try { curUploadRequest = new AssetRequestUpload(slClient, LLUUID.Random(), asset); LLUUID assetID = curUploadRequest.DoUpload(); if (asset.Type == Asset.ASSET_TYPE_IMAGE) { SinkFee(SINK_FEE_IMAGE); } return(assetID); } finally { curUploadRequest = null; } }
/// <summary> /// Get Asset data, works with BodyShapes (type 13) but does not work with Notecards(type 7) /// </summary> /// <param name="asset"></param> public void GetInventoryAsset(Asset asset) { LLUUID TransferID = LLUUID.Random(); AssetRequestDownload request = new AssetRequestDownload(TransferID); request.Size = int.MaxValue; // Number of bytes expected request.Received = 0; // Number of bytes received request.UpdateLastPacketTime(); // last time we recevied a packet for this request htDownloadRequests[TransferID] = request; Packet packet = AssetPacketHelpers.TransferRequestDirect(slClient.Network.SessionID, slClient.Network.AgentID, TransferID, asset.AssetID, asset.Type); slClient.Network.SendPacket(packet); #if DEBUG_PACKETS slClient.DebugLog(packet); #endif request.Completed.WaitOne(); asset.SetAssetData(request.AssetData); }
public bool isAvatarOnline(String firstName, String lastName) { LLUUID avatarKey = LLUUID.Zero; lock (toAvatarName) { toAvatarName = firstName + " " + lastName; if (!name2Key.ContainsKey(toAvatarName.ToLower())) { // Send the Query Avatars.RequestAvatarNameSearch(toAvatarName, LLUUID.Random()); nameSearchEvent.WaitOne(6000, false); } if (name2Key.ContainsKey(toAvatarName.ToLower())) { avatarKey = name2Key[toAvatarName.ToLower()]; Avatars.RequestAvatarProperties(avatarKey); ReceivedAvatarPropertiesEvent.Reset(); ReceivedAvatarPropertiesEvent.WaitOne(5000, false); return(avatarProperties.Online); } else { #if DEBUG Console.Out.WriteLine("Name lookup for {0} failed", toAvatarName); #endif return(false); } } }
public bool DeRezObject(SimClient simClient, Packet packet) { DeRezObjectPacket DeRezPacket = (DeRezObjectPacket)packet; //Needs to delete object from physics at a later date if (DeRezPacket.AgentBlock.DestinationID == LLUUID.Zero) { //currently following code not used (or don't know of any case of destination being zero libsecondlife.LLUUID[] DeRezEnts; DeRezEnts = new libsecondlife.LLUUID[DeRezPacket.ObjectData.Length]; int i = 0; foreach (DeRezObjectPacket.ObjectDataBlock Data in DeRezPacket.ObjectData) { //OpenSim.Framework.Console.MainConsole.Instance.WriteLine("LocalID:" + Data.ObjectLocalID.ToString()); foreach (Entity ent in this.Entities.Values) { if (ent.localid == Data.ObjectLocalID) { DeRezEnts[i++] = ent.uuid; this.localStorage.RemovePrim(ent.uuid); KillObjectPacket kill = new KillObjectPacket(); kill.ObjectData = new KillObjectPacket.ObjectDataBlock[1]; kill.ObjectData[0] = new KillObjectPacket.ObjectDataBlock(); kill.ObjectData[0].ID = ent.localid; foreach (SimClient client in m_clientThreads.Values) { client.OutPacket(kill); } //Uncommenting this means an old UUID will be re-used, thus crashing the asset server //Uncomment when prim/object UUIDs are random or such //2007-03-22 - Randomskk //this._primCount--; OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Deleted UUID " + ent.uuid); } } } foreach (libsecondlife.LLUUID uuid in DeRezEnts) { lock (Entities) { Entities.Remove(uuid); } } } else { foreach (DeRezObjectPacket.ObjectDataBlock Data in DeRezPacket.ObjectData) { Entity selectedEnt = null; //OpenSim.Framework.Console.MainConsole.Instance.WriteLine("LocalID:" + Data.ObjectLocalID.ToString()); foreach (Entity ent in this.Entities.Values) { if (ent.localid == Data.ObjectLocalID) { AssetBase primAsset = new AssetBase(); primAsset.FullID = LLUUID.Random();//DeRezPacket.AgentBlock.TransactionID.Combine(LLUUID.Zero); //should be combining with securesessionid primAsset.InvType = 6; primAsset.Type = 6; primAsset.Name = "Prim"; primAsset.Description = ""; primAsset.Data = ((Primitive)ent).GetByteArray(); this._assetCache.AddAsset(primAsset); this._inventoryCache.AddNewInventoryItem(simClient, DeRezPacket.AgentBlock.DestinationID, primAsset); selectedEnt = ent; break; } } if (selectedEnt != null) { this.localStorage.RemovePrim(selectedEnt.uuid); KillObjectPacket kill = new KillObjectPacket(); kill.ObjectData = new KillObjectPacket.ObjectDataBlock[1]; kill.ObjectData[0] = new KillObjectPacket.ObjectDataBlock(); kill.ObjectData[0].ID = selectedEnt.localid; foreach (SimClient client in m_clientThreads.Values) { client.OutPacket(kill); } lock (Entities) { Entities.Remove(selectedEnt.uuid); } } } } return(true); }
// CmdInject: handle an /inject command private static void CmdInject(string[] words) { if (words.Length < 2) { SayToUser("Usage: /inject <packet file> [value]"); } else { string[] valueArray = new string[words.Length - 2]; Array.Copy(words, 2, valueArray, 0, words.Length - 2); string value = String.Join(" ", valueArray); FileStream fs = null; StreamReader sr = null; Direction direction = Direction.Incoming; string name = null; //Hashtable blocks = new Hashtable(); string block = null; object blockObj = null; //Hashtable fields = new Hashtable(); Type packetClass = null; Packet packet = null; try { fs = File.OpenRead(words[1] + ".packet"); sr = new StreamReader(fs); string line; while ((line = sr.ReadLine()) != null) { Match match; if (name == null) { match = (new Regex(@"^\s*(in|out)\s+(\w+)\s*$")).Match(line); if (!match.Success) { SayToUser("expecting direction and packet name, got: " + line); return; } string lineDir = match.Groups[1].Captures[0].ToString(); string lineName = match.Groups[2].Captures[0].ToString(); if (lineDir == "in") { direction = Direction.Incoming; } else if (lineDir == "out") { direction = Direction.Outgoing; } else { SayToUser("expecting 'in' or 'out', got: " + line); return; } name = lineName; packetClass = libslAssembly.GetType("libsecondlife.Packets." + name + "Packet"); if (packetClass == null) { throw new Exception("Couldn't get class " + name + "Packet"); } ConstructorInfo ctr = packetClass.GetConstructor(new Type[] { }); if (ctr == null) { throw new Exception("Couldn't get suitable constructor for " + name + "Packet"); } packet = (Packet)ctr.Invoke(new object[] { }); //Console.WriteLine("Created new " + name + "Packet"); } else { match = (new Regex(@"^\s*\[(\w+)\]\s*$")).Match(line); if (match.Success) { block = match.Groups[1].Captures[0].ToString(); FieldInfo blockField = packetClass.GetField(block); if (blockField == null) { throw new Exception("Couldn't get " + name + "Packet." + block); } Type blockClass = blockField.FieldType; if (blockClass.IsArray) { blockClass = blockClass.GetElementType(); ConstructorInfo ctr = blockClass.GetConstructor(new Type[] { }); if (ctr == null) { throw new Exception("Couldn't get suitable constructor for " + blockClass.Name); } blockObj = ctr.Invoke(new object[] { }); object[] arr = (object[])blockField.GetValue(packet); object[] narr = (object[])Array.CreateInstance(blockClass, arr.Length + 1); Array.Copy(arr, narr, arr.Length); narr[arr.Length] = blockObj; blockField.SetValue(packet, narr); //Console.WriteLine("Added block "+block); } else { blockObj = blockField.GetValue(packet); } if (blockObj == null) { throw new Exception("Got " + name + "Packet." + block + " == null"); } //Console.WriteLine("Got block " + name + "Packet." + block); continue; } if (block == null) { SayToUser("expecting block name, got: " + line); return; } match = (new Regex(@"^\s*(\w+)\s*=\s*(.*)$")).Match(line); if (match.Success) { string lineField = match.Groups[1].Captures[0].ToString(); string lineValue = match.Groups[2].Captures[0].ToString(); object fval; //FIXME: use of MagicCast inefficient if (lineValue == "$Value") { fval = MagicCast(name, block, lineField, value); } else if (lineValue == "$UUID") { fval = LLUUID.Random(); } else if (lineValue == "$AgentID") { fval = agentID; } else if (lineValue == "$SessionID") { fval = sessionID; } else { fval = MagicCast(name, block, lineField, lineValue); } MagicSetField(blockObj, lineField, fval); continue; } SayToUser("expecting block name or field, got: " + line); return; } } if (name == null) { SayToUser("expecting direction and packet name, got EOF"); return; } packet.Header.Flags |= Helpers.MSG_RELIABLE; //if (protocolManager.Command(name).Encoded) // packet.Header.Flags |= Helpers.MSG_ZEROCODED; proxy.InjectPacket(packet, direction); SayToUser("injected " + words[1]); } catch (Exception e) { SayToUser("failed to inject " + words[1] + ": " + e.Message); Console.WriteLine("failed to inject " + words[1] + ": " + e.Message + "\n" + e.StackTrace); } finally { if (fs != null) { fs.Close(); } if (sr != null) { sr.Close(); } } } }
// ProxyLogin: proxy a login request private void ProxyLogin(StreamReader reader, StreamWriter writer) { lock (this) { string line; int contentLength = 0; // read HTTP header do { // read one line of the header line = reader.ReadLine(); // check for premature EOF if (line == null) { throw new Exception("EOF in client HTTP header"); } // look for Content-Length Match match = (new Regex(@"Content-Length: (\d+)$")).Match(line); if (match.Success) { contentLength = Convert.ToInt32(match.Groups[1].Captures[0].ToString()); } } while (line != ""); // read the HTTP body into a buffer char[] content = new char[contentLength]; reader.Read(content, 0, contentLength); XmlRpcRequest request = (XmlRpcRequest)(new XmlRpcRequestDeserializer()).Deserialize(new String(content)); if (request.MethodName == "login_to_simulator") { Hashtable requestData = (Hashtable)request.Params[0]; string first; string last; string passwd; LLUUID Agent; LLUUID Session; //get login name if (requestData.Contains("first")) { first = (string)requestData["first"]; } else { first = "test"; } if (requestData.Contains("last")) { last = (string)requestData["last"]; } else { last = "User" + NumClients.ToString(); } if (requestData.Contains("passwd")) { passwd = (string)requestData["passwd"]; } else { passwd = "notfound"; } if (!Authenticate(first, last, passwd)) { // Fail miserably writer.WriteLine("HTTP/1.0 403 Authentication Forbidden"); writer.WriteLine(); return; } NumClients++; //create a agent and session LLUUID Agent = GetAgentId(first, last); int SessionRand = this.RandomClass.Next(1, 999); Session = new LLUUID("aaaabbbb-0200-" + SessionRand.ToString("0000") + "-8664-58f53e442797"); XmlRpcResponse response = (XmlRpcResponse)(new XmlRpcResponseDeserializer()).Deserialize(this._defaultResponse); Hashtable responseData = (Hashtable)response.Value; responseData["sim_port"] = Globals.Instance.SimPort; responseData["sim_ip"] = Globals.Instance.SimIPAddress; responseData["agent_id"] = Agent.ToStringHyphenated(); responseData["session_id"] = Session.ToStringHyphenated(); ArrayList InventoryList = (ArrayList)responseData["inventory-skeleton"]; Hashtable Inventory1 = (Hashtable)InventoryList[0]; Hashtable Inventory2 = (Hashtable)InventoryList[1]; LLUUID BaseFolderID = LLUUID.Random(); LLUUID InventoryFolderID = LLUUID.Random(); Inventory2["name"] = "Base"; Inventory2["folder_id"] = BaseFolderID.ToStringHyphenated(); Inventory2["type_default"] = 6; Inventory1["folder_id"] = InventoryFolderID.ToStringHyphenated(); ArrayList InventoryRoot = (ArrayList)responseData["inventory-root"]; Hashtable Inventoryroot = (Hashtable)InventoryRoot[0]; Inventoryroot["folder_id"] = InventoryFolderID.ToStringHyphenated(); CustomiseLoginResponse(responseData, first, last); this._login = new Logon(); //copy data to login object _login.First = first; _login.Last = last; _login.Agent = Agent; _login.Session = Session; _login.BaseFolder = BaseFolderID; _login.InventoryFolder = InventoryFolderID; lock (Globals.Instance.IncomingLogins) { Globals.Instance.IncomingLogins.Add(_login); } // forward the XML-RPC response to the client writer.WriteLine("HTTP/1.0 200 OK"); writer.WriteLine("Content-type: text/xml"); writer.WriteLine(); XmlTextWriter responseWriter = new XmlTextWriter(writer); XmlRpcResponseSerializer.Singleton.Serialize(responseWriter, response); responseWriter.Close(); } else { writer.WriteLine("HTTP/1.0 403 Authentication Forbidden"); writer.WriteLine(); } } }
// synchronous // Only works with non-LUUID-recipients if these recipients are logged in!! // if recipientLastName == "LLUUID", recipientFirstName is expected to contain a valid LLUUID // for instant messagin while avatar isn't online public bool sendIM(string message, string recipientFirstName, string recipientLastName) { LLUUID id = LLUUID.Zero; // passed LLUUID directly if (recipientLastName.Equals("LLUUID")) { if (!LLUUID.TryParse(recipientFirstName, out id)) { #if DEBUG Console.Out.WriteLine("LLUUID parsing for {0} failed", recipientFirstName); #endif return(false); } } // get LLUUID by friedship list lookup else if (Friends.FriendList.Count > 0) { Friends.FriendList.ForEach(delegate(FriendInfo friend) { #if DEBUG Console.Out.WriteLine(friend.Name); #endif String tmpAvatarName = recipientFirstName + " " + recipientLastName; if (friend.Name.ToLower() == tmpAvatarName.ToLower()) { id = friend.UUID; } }); } // lookup LLUUID through system, only works if recipients are logged in!! if (id == LLUUID.Zero) { lock (toAvatarName) { toAvatarName = recipientFirstName + " " + recipientLastName; if (!name2Key.ContainsKey(toAvatarName.ToLower())) { // Send the Query Avatars.RequestAvatarNameSearch(toAvatarName, LLUUID.Random()); nameSearchEvent.WaitOne(6000, false); } if (name2Key.ContainsKey(toAvatarName.ToLower())) { id = name2Key[toAvatarName.ToLower()]; } else { #if DEBUG Console.Out.WriteLine("Name lookup for {0} failed", toAvatarName); #endif return(false); } } } // Build the message message = message.TrimEnd(); if (message.Length > 1023) { message = message.Remove(1023); } Self.InstantMessage(id, message); #if DEBUG Console.Out.WriteLine("Instant Messaged {0} with message: {1}", id.ToString(), message); #endif return(true); }
public XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request) { Console.WriteLine("login attempt"); Hashtable requestData = (Hashtable)request.Params[0]; string first; string last; string passwd; LLUUID Agent; LLUUID Session; LoginResponse loginResponse = new LoginResponse(regionX, regionY); //get login name if (requestData.Contains("first")) { first = (string)requestData["first"]; } else { first = "test"; } if (requestData.Contains("last")) { last = (string)requestData["last"]; } else { last = "User" + NumClients.ToString(); } if (requestData.Contains("passwd")) { passwd = (string)requestData["passwd"]; } else { passwd = "notfound"; } if (!Authenticate(first, last, passwd)) { return(loginResponse.LoginFailedResponse()); } NumClients++; // Create a agent and session LLUUID Agent = GetAgentId(first, last); int SessionRand = Util.RandomClass.Next(1, 999); Session = new LLUUID("aaaabbbb-0200-" + SessionRand.ToString("0000") + "-8664-58f53e442797"); LLUUID secureSess = LLUUID.Random(); loginResponse.SimPort = m_simPort.ToString(); loginResponse.SimAddress = m_simAddr.ToString(); loginResponse.AgentID = Agent.ToStringHyphenated(); loginResponse.SessionID = Session.ToStringHyphenated(); loginResponse.SecureSessionID = secureSess.ToStringHyphenated(); loginResponse.CircuitCode = (Int32)(Util.RandomClass.Next()); XmlRpcResponse response = loginResponse.ToXmlRpcResponse(); Hashtable responseData = (Hashtable)response.Value; // inventory ArrayList InventoryList = (ArrayList)responseData["inventory-skeleton"]; Hashtable Inventory1 = (Hashtable)InventoryList[0]; Hashtable Inventory2 = (Hashtable)InventoryList[1]; LLUUID BaseFolderID = LLUUID.Random(); LLUUID InventoryFolderID = LLUUID.Random(); Inventory2["name"] = "Textures"; Inventory2["folder_id"] = BaseFolderID.ToStringHyphenated(); Inventory2["type_default"] = 0; Inventory1["folder_id"] = InventoryFolderID.ToStringHyphenated(); ArrayList InventoryRoot = (ArrayList)responseData["inventory-root"]; Hashtable Inventoryroot = (Hashtable)InventoryRoot[0]; Inventoryroot["folder_id"] = InventoryFolderID.ToStringHyphenated(); CustomiseLoginResponse(responseData, first, last); Login _login = new Login(); //copy data to login object _login.First = first; _login.Last = last; _login.Agent = Agent; _login.Session = Session; _login.SecureSession = secureSess; _login.BaseFolder = BaseFolderID; _login.InventoryFolder = InventoryFolderID; //working on local computer if so lets add to the gridserver's list of sessions? if (m_gridServer.GetName() == "Local") { ((LocalGridBase)m_gridServer).AddNewSession(_login); } return(response); }
public void InitSessionData() { CurrentSessionID = LLUUID.Random(); CurrentSecureSessionID = LLUUID.Random(); }
public void OnFileRequested(HttpRequest request, IDirectory directory) { //request.Response.SetHeader("Content-Type", "text/plain; charset=utf-8"); request.Response.ResponseContent = new MemoryStream(); StreamWriter textwriter = new StreamWriter(request.Response.ResponseContent); SecondLife client; AvatarTracker avatars; Events events; StreamReader reader = new StreamReader(request.PostData); string qstring = reader.ReadToEnd(); reader.Dispose(); Dictionary <string, string> POST = AjaxLife.PostDecode(qstring); // Pull out the session. if (!POST.ContainsKey("sid")) { textwriter.WriteLine("Need an SID."); textwriter.Flush(); return; } Guid guid = new Guid(POST["sid"]); User user = new User(); lock (this.users) { if (!this.users.ContainsKey(guid)) { textwriter.WriteLine("Error: invalid SID"); textwriter.Flush(); return; } user = this.users[guid]; client = user.Client; avatars = user.Avatars; events = user.Events; user.LastRequest = DateTime.Now; } // Get the message type. string messagetype = POST["MessageType"]; // Check that the message is signed if it should be. if (Array.IndexOf(REQUIRED_SIGNATURES, messagetype) > -1) { if (!VerifySignature(user, qstring)) { textwriter.WriteLine("Error: Received hash and expected hash do not match."); textwriter.Flush(); return; } } // Right. This file is fun. It takes information in POST paramaters and sends them to // the server in the appropriate format. Some will return data immediately, some will return // keys to data that will arrive in the message queue, some return nothing but you get // something in the message queue later, and some return nother ever. // // The joys of dealing with multiple bizarre message types. switch (messagetype) { case "SpatialChat": client.Self.Chat(POST["Message"], int.Parse(POST["Channel"]), (ChatType)((byte)int.Parse(POST["Type"]))); break; case "SimpleInstantMessage": if (POST.ContainsKey("IMSessionID")) { client.Self.InstantMessage(new LLUUID(POST["Target"]), POST["Message"], new LLUUID(POST["IMSessionID"])); } else { client.Self.InstantMessage(new LLUUID(POST["Target"]), POST["Message"]); } break; case "GenericInstantMessage": client.Self.InstantMessage( client.Self.FirstName + " " + client.Self.LastName, new LLUUID(POST["Target"]), POST["Message"], new LLUUID(POST["IMSessionID"]), (InstantMessageDialog)((byte)int.Parse(POST["Dialog"])), (InstantMessageOnline)int.Parse(POST["Online"]), client.Self.SimPosition, client.Network.CurrentSim.ID, new byte[0]); break; case "NameLookup": client.Avatars.RequestAvatarName(new LLUUID(POST["ID"])); break; case "Teleport": { Hashtable hash = new Hashtable(); bool status; if (POST.ContainsKey("Landmark")) { status = client.Self.Teleport(new LLUUID(POST["Landmark"])); } else { status = client.Self.Teleport(POST["Sim"], new LLVector3(float.Parse(POST["X"]), float.Parse(POST["Y"]), float.Parse(POST["Z"]))); } if (status) { hash.Add("Success", true); hash.Add("Sim", client.Network.CurrentSim.Name); hash.Add("Position", client.Self.SimPosition); } else { hash.Add("Success", false); hash.Add("Reason", client.Self.TeleportMessage); } textwriter.WriteLine(MakeJson.FromHashtable(hash)); } break; case "GoHome": client.Self.GoHome(); break; case "GetPosition": { Hashtable hash = new Hashtable(); hash.Add("Sim", client.Network.CurrentSim.Name); hash.Add("Position", client.Self.SimPosition); textwriter.WriteLine(JavaScriptConvert.SerializeObject(hash)); } break; case "RequestBalance": client.Self.RequestBalance(); break; case "GetStats": { Hashtable hash = new Hashtable(); hash.Add("FPS", client.Network.CurrentSim.Stats.FPS); hash.Add("TimeDilation", client.Network.CurrentSim.Stats.Dilation); hash.Add("LSLIPS", client.Network.CurrentSim.Stats.LSLIPS); hash.Add("Objects", client.Network.CurrentSim.Stats.Objects); hash.Add("ActiveScripts", client.Network.CurrentSim.Stats.ActiveScripts); hash.Add("Agents", client.Network.CurrentSim.Stats.Agents); hash.Add("ChildAgents", client.Network.CurrentSim.Stats.ChildAgents); hash.Add("AjaxLifeSessions", users.Count); hash.Add("TextureCacheCount", AjaxLife.TextureCacheCount); hash.Add("TextureCacheSize", AjaxLife.TextureCacheSize); textwriter.WriteLine(MakeJson.FromHashtable(hash)); } break; case "TeleportLureRespond": client.Self.TeleportLureRespond(new LLUUID(POST["RequesterID"]), bool.Parse(POST["Accept"])); break; case "GodlikeTeleportLureRespond": { LLUUID lurer = new LLUUID(POST["RequesterID"]); LLUUID session = new LLUUID(POST["SessionID"]); client.Self.InstantMessage(client.Self.Name, lurer, "", LLUUID.Random(), InstantMessageDialog.AcceptTeleport, InstantMessageOnline.Offline, client.Self.SimPosition, LLUUID.Zero, new byte[0]); TeleportLureRequestPacket lure = new TeleportLureRequestPacket(); lure.Info.AgentID = client.Self.AgentID; lure.Info.SessionID = client.Self.SessionID; lure.Info.LureID = session; lure.Info.TeleportFlags = (uint)AgentManager.TeleportFlags.ViaGodlikeLure; client.Network.SendPacket(lure); } break; case "FindPeople": { Hashtable hash = new Hashtable(); hash.Add("QueryID", client.Directory.StartPeopleSearch(DirectoryManager.DirFindFlags.People, POST["Search"], int.Parse(POST["Start"]))); textwriter.WriteLine(MakeJson.FromHashtable(hash)); } break; case "FindGroups": { Hashtable hash = new Hashtable(); hash.Add("QueryID", client.Directory.StartGroupSearch(DirectoryManager.DirFindFlags.Groups, POST["Search"], int.Parse(POST["Start"]))); textwriter.WriteLine(MakeJson.FromHashtable(hash)); } break; case "GetAgentData": client.Avatars.RequestAvatarProperties(new LLUUID(POST["AgentID"])); break; case "StartAnimation": client.Self.AnimationStart(new LLUUID(POST["Animation"]), false); break; case "StopAnimation": client.Self.AnimationStop(new LLUUID(POST["Animation"]), true); break; case "SendAppearance": client.Appearance.SetPreviousAppearance(false); break; case "GetMapItems": { MapItemRequestPacket req = new MapItemRequestPacket(); req.AgentData.AgentID = client.Self.AgentID; req.AgentData.SessionID = client.Self.SessionID; GridRegion region; client.Grid.GetGridRegion(POST["Region"], GridLayerType.Objects, out region); req.RequestData.RegionHandle = region.RegionHandle; req.RequestData.ItemType = uint.Parse(POST["ItemType"]); client.Network.SendPacket((Packet)req); } break; case "GetMapBlocks": { MapBlockRequestPacket req = new MapBlockRequestPacket(); req.AgentData.AgentID = client.Self.AgentID; req.AgentData.SessionID = client.Self.SessionID; req.PositionData.MinX = 0; req.PositionData.MinY = 0; req.PositionData.MaxX = ushort.MaxValue; req.PositionData.MaxY = ushort.MaxValue; client.Network.SendPacket((Packet)req); } break; case "GetMapBlock": { ushort x = ushort.Parse(POST["X"]); ushort y = ushort.Parse(POST["Y"]); MapBlockRequestPacket req = new MapBlockRequestPacket(); req.AgentData.AgentID = client.Self.AgentID; req.AgentData.SessionID = client.Self.SessionID; req.PositionData.MinX = x; req.PositionData.MinY = y; req.PositionData.MaxX = x; req.PositionData.MaxY = y; client.Network.SendPacket((Packet)req); } break; case "GetOfflineMessages": { RetrieveInstantMessagesPacket req = new RetrieveInstantMessagesPacket(); req.AgentData.AgentID = client.Self.AgentID; req.AgentData.SessionID = client.Self.SessionID; client.Network.SendPacket((Packet)req); } break; case "GetFriendList": { InternalDictionary <LLUUID, FriendInfo> friends = client.Friends.FriendList; List <Hashtable> friendlist = new List <Hashtable>(); friends.ForEach(delegate(FriendInfo friend) { Hashtable friendhash = new Hashtable(); friendhash.Add("ID", friend.UUID.ToString()); friendhash.Add("Name", friend.Name); friendhash.Add("Online", friend.IsOnline); friendhash.Add("MyRights", friend.MyFriendRights); friendhash.Add("TheirRights", friend.TheirFriendRights); friendlist.Add(friendhash); }); textwriter.Write(MakeJson.FromObject(friendlist)); } break; case "ChangeRights": { LLUUID uuid = new LLUUID(POST["Friend"]); client.Friends.GrantRights(uuid, (FriendRights)int.Parse(POST["Rights"])); } break; case "RequestLocation": client.Friends.MapFriend(new LLUUID(POST["Friend"])); break; case "RequestTexture": { // This one's confusing, so it gets some comments. // First, we get the image's UUID. LLUUID image = new LLUUID(POST["ID"]); // We prepare a query to ask if S3 has it. HEAD only to avoid wasting // GET requests and bandwidth. bool exists = false; // If we already know we have it, note this. if (AjaxLife.CachedTextures.Contains(image)) { exists = true; } else { // If we're using S3, check the S3 bucket if (AjaxLife.USE_S3) { // Otherwise, make that HEAD request and find out. try { IThreeSharp query = new ThreeSharpQuery(AjaxLife.S3Config); Affirma.ThreeSharp.Model.ObjectGetRequest s3request = new Affirma.ThreeSharp.Model.ObjectGetRequest(AjaxLife.TEXTURE_BUCKET, image.ToString() + ".png"); s3request.Method = "HEAD"; Affirma.ThreeSharp.Model.ObjectGetResponse s3response = query.ObjectGet(s3request); if (s3response.StatusCode == System.Net.HttpStatusCode.OK) { exists = true; } s3response.DataStream.Close(); } catch { } } // If we aren't using S3, just check the texture cache. else { exists = File.Exists(AjaxLife.TEXTURE_CACHE + image.ToString() + ".png"); } } // If it exists, reply with Ready = true and the URL to find it at. if (exists) { textwriter.Write("{Ready: true, URL: \"" + AjaxLife.TEXTURE_ROOT + image + ".png\"}"); } // If it doesn't, request the image from SL and note its lack of readiness. // Notification will arrive later in the message queue. else { client.Assets.RequestImage(image, ImageType.Normal, 125000.0f, 0); textwriter.Write("{Ready: false}"); } } break; case "AcceptFriendship": client.Friends.AcceptFriendship(client.Self.AgentID, POST["IMSessionID"]); break; case "DeclineFriendship": client.Friends.DeclineFriendship(client.Self.AgentID, POST["IMSessionID"]); break; case "OfferFriendship": client.Friends.OfferFriendship(new LLUUID(POST["Target"])); break; case "TerminateFriendship": client.Friends.TerminateFriendship(new LLUUID(POST["Target"])); break; case "SendAgentMoney": client.Self.GiveAvatarMoney(new LLUUID(POST["Target"]), int.Parse(POST["Amount"])); break; case "RequestAvatarList": { List <Hashtable> list = new List <Hashtable>(); foreach (KeyValuePair <uint, Avatar> pair in avatars.Avatars) { Avatar avatar = pair.Value; Hashtable hash = new Hashtable(); hash.Add("Name", avatar.Name); hash.Add("ID", avatar.ID); hash.Add("LocalID", avatar.LocalID); hash.Add("Position", avatar.Position); //hash.Add("Rotation", avatar.Rotation); hash.Add("Scale", avatar.Scale); hash.Add("GroupName", avatar.GroupName); list.Add(hash); } textwriter.Write(MakeJson.FromObject(list)); } break; case "LoadInventoryFolder": client.Inventory.RequestFolderContents(new LLUUID(POST["UUID"]), client.Self.AgentID, true, true, InventorySortOrder.ByDate | InventorySortOrder.SystemFoldersToTop); break; case "RequestAsset": { try { LLUUID transferid = client.Assets.RequestInventoryAsset(new LLUUID(POST["AssetID"]), new LLUUID(POST["InventoryID"]), LLUUID.Zero, new LLUUID(POST["OwnerID"]), (AssetType)int.Parse(POST["AssetType"]), false); textwriter.Write("{TransferID: \"" + transferid + "\"}"); } catch // Try catching the error that sometimes gets thrown... but sometimes doesn't. { } } break; case "SendTeleportLure": client.Self.SendTeleportLure(new LLUUID(POST["Target"]), POST["Message"]); break; case "ScriptPermissionResponse": client.Self.ScriptQuestionReply(client.Network.CurrentSim, new LLUUID(POST["ItemID"]), new LLUUID(POST["TaskID"]), (ScriptPermission)int.Parse(POST["Permissions"])); break; case "ScriptDialogReply": { ScriptDialogReplyPacket packet = new ScriptDialogReplyPacket(); packet.AgentData.AgentID = client.Self.AgentID; packet.AgentData.SessionID = client.Self.SessionID; packet.Data.ButtonIndex = int.Parse(POST["ButtonIndex"]); packet.Data.ButtonLabel = Helpers.StringToField(POST["ButtonLabel"]); packet.Data.ChatChannel = int.Parse(POST["ChatChannel"]); packet.Data.ObjectID = new LLUUID(POST["ObjectID"]); client.Network.SendPacket((Packet)packet); } break; case "SaveNotecard": client.Inventory.RequestUploadNotecardAsset(Helpers.StringToField(POST["AssetData"]), new LLUUID(POST["ItemID"]), new InventoryManager.NotecardUploadedAssetCallback(events.Inventory_OnNoteUploaded)); break; case "CreateInventory": client.Inventory.RequestCreateItem(new LLUUID(POST["Folder"]), POST["Name"], POST["Description"], (AssetType)int.Parse(POST["AssetType"]), LLUUID.Random(), (InventoryType)int.Parse(POST["InventoryType"]), PermissionMask.All, new InventoryManager.ItemCreatedCallback(events.Inventory_OnItemCreated)); break; case "CreateFolder": { LLUUID folder = client.Inventory.CreateFolder(new LLUUID(POST["Parent"]), POST["Name"]); textwriter.Write("{FolderID: \"" + folder + "\"}"); } break; case "EmptyTrash": client.Inventory.EmptyTrash(); break; case "MoveItem": client.Inventory.MoveItem(new LLUUID(POST["Item"]), new LLUUID(POST["TargetFolder"]), POST["NewName"]); break; case "MoveFolder": client.Inventory.MoveFolder(new LLUUID(POST["Folder"]), new LLUUID(POST["NewParent"])); break; case "MoveItems": case "MoveFolders": { Dictionary <LLUUID, LLUUID> dict = new Dictionary <LLUUID, LLUUID>(); string[] moves = POST["ToMove"].Split(','); for (int i = 0; i < moves.Length; ++i) { string[] move = moves[i].Split(' '); dict.Add(new LLUUID(move[0]), new LLUUID(move[1])); } if (messagetype == "MoveItems") { client.Inventory.MoveItems(dict); } else if (messagetype == "MoveFolders") { client.Inventory.MoveFolders(dict); } } break; case "DeleteItem": client.Inventory.RemoveItem(new LLUUID(POST["Item"])); break; case "DeleteFolder": client.Inventory.RemoveFolder(new LLUUID(POST["Folder"])); break; case "DeleteMultiple": { string[] items = POST["Items"].Split(','); List <LLUUID> itemlist = new List <LLUUID>(); for (int i = 0; i < items.Length; ++i) { itemlist.Add(new LLUUID(items[i])); } string[] folders = POST["Folders"].Split(','); List <LLUUID> folderlist = new List <LLUUID>(); for (int i = 0; i < items.Length; ++i) { folderlist.Add(new LLUUID(folders[i])); } client.Inventory.Remove(itemlist, folderlist); } break; case "GiveInventory": { client.Inventory.GiveItem(new LLUUID(POST["ItemID"]), POST["ItemName"], (AssetType)int.Parse(POST["AssetType"]), new LLUUID(POST["Recipient"]), true); } break; case "UpdateItem": { InventoryItem item = client.Inventory.FetchItem(new LLUUID(POST["ItemID"]), new LLUUID(POST["OwnerID"]), 1000); if (POST.ContainsKey("Name")) { item.Name = POST["Name"]; } if (POST.ContainsKey("Description")) { item.Description = POST["Description"]; } if (POST.ContainsKey("NextOwnerMask")) { item.Permissions.NextOwnerMask = (PermissionMask)uint.Parse(POST["NextOwnerMask"]); } if (POST.ContainsKey("SalePrice")) { item.SalePrice = int.Parse(POST["SalePrice"]); } if (POST.ContainsKey("SaleType")) { item.SaleType = (SaleType)int.Parse(POST["SaleType"]); // This should be byte.Parse, but this upsets mono's compiler (CS1002) } client.Inventory.RequestUpdateItem(item); } break; case "UpdateFolder": { UpdateInventoryFolderPacket packet = new UpdateInventoryFolderPacket(); packet.AgentData.AgentID = client.Self.AgentID; packet.AgentData.SessionID = client.Self.SessionID; packet.FolderData = new UpdateInventoryFolderPacket.FolderDataBlock[1]; packet.FolderData[0] = new UpdateInventoryFolderPacket.FolderDataBlock(); packet.FolderData[0].FolderID = new LLUUID(POST["FolderID"]); packet.FolderData[0].ParentID = new LLUUID(POST["ParentID"]); packet.FolderData[0].Type = sbyte.Parse(POST["Type"]); packet.FolderData[0].Name = Helpers.StringToField(POST["Name"]); client.Network.SendPacket((Packet)packet); } break; case "FetchItem": client.Inventory.FetchItem(new LLUUID(POST["Item"]), new LLUUID(POST["Owner"]), 5000); break; case "ReRotate": user.Rotation = -Math.PI; break; case "StartGroupIM": AjaxLife.Debug("SendMessage", "RequestJoinGroupChat(" + POST["Group"] + ")"); client.Self.RequestJoinGroupChat(new LLUUID(POST["Group"])); break; case "GroupInstantMessage": client.Self.InstantMessageGroup(new LLUUID(POST["Group"]), POST["Message"]); break; case "RequestGroupProfile": client.Groups.RequestGroupProfile(new LLUUID(POST["Group"])); break; case "RequestGroupMembers": client.Groups.RequestGroupMembers(new LLUUID(POST["Group"])); break; case "RequestGroupName": client.Groups.RequestGroupName(new LLUUID(POST["ID"])); break; case "JoinGroup": client.Groups.RequestJoinGroup(new LLUUID(POST["Group"])); break; case "LeaveGroup": client.Groups.LeaveGroup(new LLUUID(POST["Group"])); break; case "RequestCurrentGroups": client.Groups.RequestCurrentGroups(); break; case "GetParcelID": textwriter.Write("{LocalID: " + client.Parcels.GetParcelLocalID(client.Network.CurrentSim, new LLVector3(float.Parse(POST["X"]), float.Parse(POST["Y"]), float.Parse(POST["Z"]))) + "}"); break; case "RequestParcelProperties": client.Parcels.PropertiesRequest(client.Network.CurrentSim, int.Parse(POST["LocalID"]), int.Parse(POST["SequenceID"])); break; } textwriter.Flush(); }
public override string Execute(string[] args, LLUUID fromAgentID) { if (args.Length < 1) { return("Usage: searchevents [search text]"); } string searchText = string.Empty; for (int i = 0; i < args.Length; i++) { searchText += args[i] + " "; } searchText = searchText.TrimEnd(); waitQuery.Reset(); Client.Directory.OnEventsReply += new DirectoryManager.EventReplyCallback(Directory_OnEventsReply); Client.Directory.StartEventsSearch(searchText, true, "u", 0, DirectoryManager.EventCategories.All, LLUUID.Random()); string result; if (waitQuery.WaitOne(20000, false) && Client.Network.Connected) { result = "Your query '" + searchText + "' matched " + resultCount + " Events. "; } else { result = "Timeout waiting for simulator to respond."; } Client.Directory.OnEventsReply -= new DirectoryManager.EventReplyCallback(Directory_OnEventsReply); return(result); }
public void InitConfig(bool sandboxMode, IGenericConfig configData) { this.isSandbox = sandboxMode; try { // Sim UUID string attri = ""; attri = configData.GetAttribute("SimUUID"); if (attri == "") { this.SimUUID = LLUUID.Random(); configData.SetAttribute("SimUUID", this.SimUUID.ToString()); } else { this.SimUUID = new LLUUID(attri); } // Sim name attri = ""; attri = configData.GetAttribute("SimName"); if (attri == "") { this.RegionName = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("Name", "OpenSim test"); configData.SetAttribute("SimName", this.RegionName); } else { this.RegionName = attri; } // Sim/Grid location X attri = ""; attri = configData.GetAttribute("SimLocationX"); if (attri == "") { string location = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("Grid Location X", "997"); configData.SetAttribute("SimLocationX", location); this.RegionLocX = (uint)Convert.ToUInt32(location); } else { this.RegionLocX = (uint)Convert.ToUInt32(attri); } // Sim/Grid location Y attri = ""; attri = configData.GetAttribute("SimLocationY"); if (attri == "") { string location = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("Grid Location Y", "996"); configData.SetAttribute("SimLocationY", location); this.RegionLocY = (uint)Convert.ToUInt32(location); } else { this.RegionLocY = (uint)Convert.ToUInt32(attri); } // Local storage datastore attri = ""; attri = configData.GetAttribute("Datastore"); if (attri == "") { string datastore = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("Filename for local storage", "localworld.yap"); configData.SetAttribute("Datastore", datastore); this.DataStore = datastore; } else { this.DataStore = attri; } //Sim Listen Port attri = ""; attri = configData.GetAttribute("SimListenPort"); if (attri == "") { string port = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("UDP port for client connections", "9000"); configData.SetAttribute("SimListenPort", port); this.IPListenPort = Convert.ToInt32(port); } else { this.IPListenPort = Convert.ToInt32(attri); } //Sim Listen Address attri = ""; attri = configData.GetAttribute("SimListenAddress"); if (attri == "") { this.IPListenAddr = OpenSim.Framework.Console.MainConsole.Instance.CmdPrompt("IP Address to listen on for client connections", "127.0.0.1"); configData.SetAttribute("SimListenAddress", this.IPListenAddr); } else { this.IPListenAddr = attri; } this.RegionHandle = Util.UIntsToLong((RegionLocX * 256), (RegionLocY * 256)); configData.Commit(); } catch (Exception e) { OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Config.cs:InitConfig() - Exception occured"); OpenSim.Framework.Console.MainConsole.Instance.WriteLine(e.ToString()); } OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Sim settings loaded:"); OpenSim.Framework.Console.MainConsole.Instance.WriteLine("UUID: " + this.SimUUID.ToStringHyphenated()); OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Name: " + this.RegionName); OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Region Location: [" + this.RegionLocX.ToString() + "," + this.RegionLocY + "]"); OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Region Handle: " + this.RegionHandle.ToString()); OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Listening on IP: " + this.IPListenAddr + ":" + this.IPListenPort); }
public FollowRandomAvatar() : base(LLUUID.Random()) { OnFrame += MyOnFrame; }
private void cmdUpload_Click(object sender, EventArgs e) { SendToID = LLUUID.Zero; string sendTo = txtSendtoName.Text.Trim(); if (sendTo.Length > 0) { AutoResetEvent lookupEvent = new AutoResetEvent(false); LLUUID thisQueryID = LLUUID.Random(); bool lookupSuccess = false; DirectoryManager.DirPeopleReplyCallback callback = delegate(LLUUID queryID, List <DirectoryManager.AgentSearchData> matchedPeople) { if (queryID == thisQueryID) { if (matchedPeople.Count > 0) { SendToID = matchedPeople[0].AgentID; lookupSuccess = true; } lookupEvent.Set(); } }; Client.Directory.OnDirPeopleReply += callback; Client.Directory.StartPeopleSearch(DirectoryManager.DirFindFlags.People, sendTo, 0, thisQueryID); bool eventSuccess = lookupEvent.WaitOne(10 * 1000, false); Client.Directory.OnDirPeopleReply -= callback; if (eventSuccess && lookupSuccess) { Client.Log("Will send uploaded image to avatar " + SendToID.ToString(), Helpers.LogLevel.Info); } else { MessageBox.Show("Could not find avatar \"" + sendTo + "\", upload cancelled"); return; } } if (UploadData != null) { prgUpload.Value = 0; cmdLoad.Enabled = false; cmdUpload.Enabled = false; grpLogin.Enabled = false; string name = System.IO.Path.GetFileNameWithoutExtension(FileName); Client.Inventory.RequestCreateItemFromAsset(UploadData, name, "Uploaded with SL Image Upload", AssetType.Texture, InventoryType.Texture, Client.Inventory.FindFolderForType(AssetType.Texture), delegate(bool success, string status, LLUUID itemID, LLUUID assetID) { if (this.InvokeRequired) { BeginInvoke(new MethodInvoker(EnableControls)); } else { EnableControls(); } if (success) { AssetID = assetID; UpdateAssetID(); // Fix the permissions on the new upload since they are fscked by default InventoryItem item = Client.Inventory.FetchItem(itemID, Client.Self.AgentID, 1000 * 15); if (item != null) { item.Permissions.EveryoneMask = PermissionMask.All; item.Permissions.NextOwnerMask = PermissionMask.All; Client.Inventory.RequestUpdateItem(item); Client.Log("Created inventory item " + itemID.ToString(), Helpers.LogLevel.Info); MessageBox.Show("Created inventory item " + itemID.ToString()); // FIXME: We should be watching the callback for RequestUpdateItem instead of a dumb sleep System.Threading.Thread.Sleep(2000); if (SendToID != LLUUID.Zero) { Client.Log("Sending item to " + SendToID.ToString(), Helpers.LogLevel.Info); Client.Inventory.GiveItem(itemID, name, AssetType.Texture, SendToID, true); MessageBox.Show("Sent item to " + SendToID.ToString()); } } else { Client.DebugLog("Created inventory item " + itemID.ToString() + " but failed to fetch it," + " cannot update permissions or send to another avatar"); MessageBox.Show("Created inventory item " + itemID.ToString() + " but failed to fetch it," + " cannot update permissions or send to another avatar"); } } else { MessageBox.Show("Asset upload failed: " + status); } } ); } }