aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Client/MXP/PacketHandler/MXPPacketServer.cs
blob: 26347170d01a36404127ba301ca7ecffc158705f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/* This file borrows heavily from MXPServer.cs - the reference MXPServer 
 * See http://www.bubblecloud.org for a copy of the original file and
 * implementation details. */
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using MXP;
using MXP.Messages;
using OpenMetaverse;
using OpenSim.Client.MXP.ClientStack;
using OpenSim.Region.Framework.Scenes;

namespace OpenSim.Client.MXP.PacketHandler
{
    class MXPPacketServer
    {
        internal static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private readonly List<MXPClientView> Clients = new List<MXPClientView>();
        private readonly Dictionary<UUID, Scene> Scenes;

        #region Fields

        private readonly Transmitter transmitter;

        private readonly IList<Session> sessions = new List<Session>();
        private readonly IList<Session> sessionsToClient = new List<Session>();
        private readonly IList<MXPClientView> sessionsToRemove = new List<MXPClientView>();

        private readonly String cloudUrl;
        private readonly String programName;
        private readonly byte programMajorVersion;
        private readonly byte programMinorVersion;

        #endregion

        #region Constructors

        public MXPPacketServer(string cloudUrl, int port, Dictionary<UUID, Scene> scenes)
        {
            this.cloudUrl = cloudUrl;

            Scenes = scenes;

            programMinorVersion = 63;
            programMajorVersion = 0;
            programName = "OpenSimulator";

            transmitter = new Transmitter(port);
            transmitter.Startup();
        }

        #endregion

        #region Properties

        /// <summary>
        /// Number of sessions pending. (Process() accepts pending sessions).
        /// </summary>
        public int PendingSessionCount
        {
            get
            {
                return transmitter.PendingSessionCount;
            }
        }
        /// <summary>
        /// Number of connected sessions.
        /// </summary>
        public int SessionCount
        {
            get
            {
                return sessions.Count;
            }
        }
        /// <summary>
        /// Property reflecting whether client transmitter threads are alive.
        /// </summary>
        public bool IsTransmitterAlive
        {
            get
            {
                return transmitter != null && transmitter.IsAlive;
            }
        }
        /// <summary>
        /// Number of packets sent.
        /// </summary>
        public ulong PacketsSent
        {
            get
            {
                return transmitter != null ? transmitter.PacketsSent : 0;
            }
        }
        /// <summary>
        /// Number of packets received.
        /// </summary>
        public ulong PacketsReceived
        {
            get
            {
                return transmitter != null ? transmitter.PacketsReceived : 0;
            }
        }
        /// <summary>
        /// Bytes client has received so far.
        /// </summary>
        public ulong BytesReceived
        {
            get
            {
                return transmitter != null ? transmitter.BytesReceived : 0;
            }
        }
        /// <summary>
        /// Bytes client has sent so far.
        /// </summary>
        public ulong BytesSent
        {
            get
            {
                return transmitter != null ? transmitter.BytesSent : 0;
            }
        }
        /// <summary>
        /// Number of bytes received (bytes per second) during past second.
        /// </summary>
        public double ReceiveRate
        {
            get
            {
                return transmitter != null ? transmitter.ReceiveRate : 0;
            }
        }
        /// <summary>
        /// Number of bytes sent (bytes per second) during past second.
        /// </summary>
        public double SendRate
        {
            get
            {
                return transmitter != null ? transmitter.SendRate : 0;
            }
        }

        #endregion

        #region Session Management

        public void Disconnect(Session session)
        {
            if (session.IsConnected)
            {
                Message message = MessageFactory.Current.ReserveMessage(typeof(LeaveRequestMessage));
                session.Send(message);
                MessageFactory.Current.ReleaseMessage(message);
            }
            else
            {
                throw new Exception("Not connected.");
            }
        }

        #endregion


        #region Processing

        public void PrintDebugInformation()
        {
            m_log.Info("[MXP ClientStack] Statistics report");
            m_log.Info("Pending Sessions: " + PendingSessionCount);
            m_log.Info("Sessions: " + SessionCount + " (Clients: " + Clients.Count + " )");
            m_log.Info("Transmitter Alive?: " + IsTransmitterAlive);
            m_log.Info("Packets Sent/Recieved: " + PacketsSent + " / " + PacketsReceived);
            m_log.Info("Bytes Sent/Recieved: " + BytesSent + " / " + BytesReceived);
            m_log.Info("Send/Recieve Rate (bps): " + SendRate + " / " + ReceiveRate);
        }

        public void Process()
        {
            ProcessMessages();
            Clean();
        }

        public void Clean()
        {
            foreach (MXPClientView clientView in Clients)
            {
                if (clientView.Session.SessionState == SessionState.Disconnected)
                {
                    sessionsToRemove.Add(clientView);
                }
            }

            foreach (MXPClientView clientView in sessionsToRemove)
            {
                clientView.Scene.RemoveClient(clientView.AgentId);
                Clients.Remove(clientView);
                sessions.Remove(clientView.Session);
            }

            sessionsToRemove.Clear();
        }

        public bool AuthoriseUser(string participantName, string pass, UUID scene)
        {
            if (Scenes.ContainsKey(scene))
                return true;

            return false;
        }

        public void ProcessMessages()
        {
            if (transmitter.PendingSessionCount > 0)
            {
                Session tmp = transmitter.AcceptPendingSession();
                sessions.Add(tmp);
                sessionsToClient.Add(tmp);

            }

            List<Session> tmpRemove = new List<Session>();

            foreach (Session session in sessionsToClient)
            {
                while (session.AvailableMessages > 0)
                {
                    Message message = session.Receive();

                    if (message.GetType() == typeof (JoinRequestMessage))
                    {

                        JoinRequestMessage joinRequestMessage = (JoinRequestMessage) message;

                        bool authorized = AuthoriseUser(joinRequestMessage.ParticipantName,
                                                        joinRequestMessage.ParticipantPassphrase,
                                                        new UUID(joinRequestMessage.BubbleId));

                        if (authorized)
                        {
                            Scene target = Scenes[new UUID(joinRequestMessage.BubbleId)];

                            UUID mxpSessionID = UUID.Random();

                            m_log.Info("[MXP ClientStack] Session join request success: " + session.SessionId + " (" +
                                       (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" +
                                       session.RemoteEndPoint.Port + ")");

                            AcceptConnection(session, joinRequestMessage, mxpSessionID);

                            MXPClientView client = new MXPClientView(session, mxpSessionID, target,
                                                                     joinRequestMessage.ParticipantName);
                            Clients.Add(client);

                            target.AddNewClient(client);
                        }
                        else
                        {
                            m_log.Info("[MXP ClientStack] Session join request failure: " + session.SessionId + " (" +
                                       (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" +
                                       session.RemoteEndPoint.Port + ")");

                            DeclineConnection(session, joinRequestMessage);
                        }

                        tmpRemove.Add(session);
                    }
                }
            }

            foreach (Session session in tmpRemove)
            {
                sessionsToClient.Remove(session);
            }

            foreach (MXPClientView clientView in Clients)
            {
                
                int messagesProcessedCount = 0;
                Session session = clientView.Session;

                while (session.AvailableMessages > 0)
                {
                    Message message = session.Receive();

                    if (message.GetType() == typeof(LeaveRequestMessage))
                    {

                        LeaveResponseMessage leaveResponseMessage = (LeaveResponseMessage)MessageFactory.Current.ReserveMessage(
                            typeof(LeaveResponseMessage));

                        m_log.Info("[MXP ClientStack] Session leave request: " + session.SessionId + " (" + (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" + session.RemoteEndPoint.Port + ")");

                        leaveResponseMessage.RequestMessageId = message.MessageId;
                        leaveResponseMessage.FailureCode = 0;
                        session.Send(leaveResponseMessage);

                        if (session.SessionState != SessionState.Disconnected)
                        {
                            session.SetStateDisconnected();
                        }

                        m_log.Info("[MXP ClientStack] Removing Client from Scene");
                        clientView.Scene.RemoveClient(clientView.AgentId);
                    }
                    if (message.GetType() == typeof(LeaveResponseMessage))
                    {

                        LeaveResponseMessage leaveResponseMessage = (LeaveResponseMessage)message;

                        m_log.Info("[MXP ClientStack] Session leave response: " + session.SessionId + " (" + (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" + session.RemoteEndPoint.Port + ")");

                        if (leaveResponseMessage.FailureCode == 0)
                        {
                            session.SetStateDisconnected();
                        }

                        m_log.Info("[MXP ClientStack] Removing Client from Scene");
                        clientView.Scene.RemoveClient(clientView.AgentId);
                    }
                    else
                    {
                        clientView.ProcessMXPPacket(message);
                    }

                    MessageFactory.Current.ReleaseMessage(message);
                    messagesProcessedCount++;
                    if (messagesProcessedCount > 1000)
                    {
                        break;
                    }
                }
            }
        }

        private void AcceptConnection(Session session, JoinRequestMessage joinRequestMessage, UUID mxpSessionID)
        {
            JoinResponseMessage joinResponseMessage = (JoinResponseMessage)MessageFactory.Current.ReserveMessage(
                                                                               typeof(JoinResponseMessage));

            joinResponseMessage.RequestMessageId = joinRequestMessage.MessageId;
            joinResponseMessage.FailureCode = 0;

            joinResponseMessage.ParticipantId = mxpSessionID.Guid;
            joinResponseMessage.CloudUrl = cloudUrl;

            joinResponseMessage.BubbleName = Scenes[new UUID(joinRequestMessage.BubbleId)].RegionInfo.RegionName;

            joinResponseMessage.BubbleRealTime = 0;
            joinResponseMessage.ProgramName = programName;
            joinResponseMessage.ProgramMajorVersion = programMajorVersion;
            joinResponseMessage.ProgramMinorVersion = programMinorVersion;
            joinResponseMessage.ProtocolMajorVersion = MxpConstants.ProtocolMajorVersion;
            joinResponseMessage.ProtocolMinorVersion = MxpConstants.ProtocolMinorVersion;

            session.Send(joinResponseMessage);

            session.SetStateConnected();
        }

        private void DeclineConnection(Session session, Message joinRequestMessage)
        {
            JoinResponseMessage joinResponseMessage = (JoinResponseMessage)MessageFactory.Current.ReserveMessage(typeof(JoinResponseMessage));

            joinResponseMessage.RequestMessageId = joinRequestMessage.MessageId;
            joinResponseMessage.FailureCode = 1;

            joinResponseMessage.CloudUrl = cloudUrl;

            joinResponseMessage.BubbleName = "Declined OpenSim Region"; // Dont reveal anything about the sim in the disconnect notice

            joinResponseMessage.BubbleRealTime = 0;
            joinResponseMessage.ProgramName = programName;
            joinResponseMessage.ProgramMajorVersion = programMajorVersion;
            joinResponseMessage.ProgramMinorVersion = programMinorVersion;
            joinResponseMessage.ProtocolMajorVersion = MxpConstants.ProtocolMajorVersion;
            joinResponseMessage.ProtocolMinorVersion = MxpConstants.ProtocolMinorVersion;

            session.Send(joinResponseMessage);

            session.SetStateDisconnected();
        }

        #endregion

    }
}