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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
|
/*
* Copyright (c) OpenSim project, http://sim.opensecondlife.org/
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY <copyright holder> ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using libsecondlife;
using System.Collections;
using libsecondlife.Packets;
using libsecondlife.AssetSystem;
using System.Net;
using System.Net.Sockets;
using System.Timers;
//really hacked , messy code
namespace OpenSim
{
/// <summary>
/// Description of Server.
/// </summary>
public interface ServerCallback
{
//should replace with delegates
void MainCallback(Packet pack, User_Agent_info User_info);
void NewUserCallback(User_Agent_info User_info);
void ErrorCallback(string text);
}
public class Server
{
/// <summary>A public reference to the client that this Simulator object
/// is attached to</summary>
//public SecondLife Client;
/// <summary>The Region class that this Simulator wraps</summary>
// public Region Region;
/// <summary>
/// Used internally to track sim disconnections, do not modify this
/// variable
/// </summary>
public bool DisconnectCandidate = false;
/// <summary>
/// The ID number associated with this particular connection to the
/// simulator, used to emulate TCP connections. This is used
/// internally for packets that have a CircuitCode field
/// </summary>
public uint CircuitCode
{
get { return circuitCode; }
set { circuitCode = value; }
}
/// <summary>
/// The IP address and port of the server
/// </summary>
public IPEndPoint IPEndPoint
{
get { return ipEndPoint; }
}
/// <summary>
/// A boolean representing whether there is a working connection to the
/// simulator or not
/// </summary>
public bool Connected
{
get { return connected; }
}
private ServerCallback CallbackObject;
private uint Sequence = 0;
private object SequenceLock = new object();
private byte[] RecvBuffer = new byte[4096];
private byte[] ZeroBuffer = new byte[8192];
private byte[] ZeroOutBuffer = new byte[4096];
private Socket Connection = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private AsyncCallback ReceivedData;
private bool connected = false;
private uint circuitCode;
private IPEndPoint ipEndPoint;
private EndPoint endPoint;
private IPEndPoint ipeSender;
private EndPoint epSender;
private System.Timers.Timer AckTimer;
private Server_Settings Settings=new Server_Settings();
public ArrayList User_agents=new ArrayList();
/// <summary>
/// Constructor for Simulator
/// </summary>
/// <param name="client"></param>
/// <param name="callbacks"></param>
/// <param name="circuit"></param>
/// <param name="ip"></param>
/// <param name="port"></param>
public Server(ServerCallback s_callback)
{
this.CallbackObject=s_callback; //should be using delegate
AckTimer = new System.Timers.Timer(Settings.NETWORK_TICK_LENGTH);
AckTimer.Elapsed += new ElapsedEventHandler(AckTimer_Elapsed);
// Initialize the callback for receiving a new packet
ReceivedData = new AsyncCallback(this.OnReceivedData);
// Client.Log("Connecting to " + ip.ToString() + ":" + port, Helpers.LogLevel.Info);
try
{
// Create an endpoint that we will be communicating with (need it in two
// types due to .NET weirdness)
// ipEndPoint = new IPEndPoint(ip, port);
ipEndPoint = new IPEndPoint(IPAddress.Any, Globals.Instance.IpPort);
endPoint = (EndPoint)ipEndPoint;
// Associate this simulator's socket with the given ip/port and start listening
Connection.Bind(endPoint);
ipeSender = new IPEndPoint(IPAddress.Any, 0);
//The epSender identifies the incoming clients
epSender = (EndPoint) ipeSender;
Connection.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null);
// Start the ACK timer
AckTimer.Start();
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
}
}
/// <summary>
/// Disconnect a Simulator
/// </summary>
public void Disconnect()
{
if (connected)
{
connected = false;
AckTimer.Stop();
// Send the CloseCircuit notice
CloseCircuitPacket close = new CloseCircuitPacket();
if (Connection.Connected)
{
try
{
// Connection.Send(close.ToBytes());
}
catch (SocketException)
{
// There's a high probability of this failing if the network is
// disconnecting, so don't even bother logging the error
}
}
try
{
// Shut the socket communication down
// Connection.Shutdown(SocketShutdown.Both);
}
catch (SocketException)
{
}
}
}
/// <summary>
/// Sends a packet
/// </summary>
/// <param name="packet">Packet to be sent</param>
/// <param name="incrementSequence">Increment sequence number?</param>
public void SendPacket(Packet packet, bool incrementSequence, User_Agent_info User_info)
{
byte[] buffer;
int bytes;
if (!connected && packet.Type != PacketType.UseCircuitCode)
{
// Client.Log("Trying to send a " + packet.Type.ToString() + " packet when the socket is closed",
// Helpers.LogLevel.Info);
return;
}
if (packet.Header.AckList.Length > 0)
{
// Scrub any appended ACKs since all of the ACK handling is done here
packet.Header.AckList = new uint[0];
}
packet.Header.AppendedAcks = false;
// Keep track of when this packet was sent out
packet.TickCount = Environment.TickCount;
if (incrementSequence)
{
// Set the sequence number
lock (SequenceLock)
{
if (Sequence > Settings.MAX_SEQUENCE)
Sequence = 1;
else
Sequence++;
packet.Header.Sequence = Sequence;
}
if (packet.Header.Reliable)
{
lock (User_info.NeedAck)
{
if (!User_info.NeedAck.ContainsKey(packet.Header.Sequence))
{
User_info.NeedAck.Add(packet.Header.Sequence, packet);
}
else
{
// Client.Log("Attempted to add a duplicate sequence number (" +
// packet.Header.Sequence + ") to the NeedAck dictionary for packet type " +
// packet.Type.ToString(), Helpers.LogLevel.Warning);
}
}
// Don't append ACKs to resent packets, in case that's what was causing the
// delivery to fail
if (!packet.Header.Resent)
{
// Append any ACKs that need to be sent out to this packet
lock (User_info.PendingAcks)
{
if (User_info.PendingAcks.Count > 0 && User_info.PendingAcks.Count < Settings.MAX_APPENDED_ACKS &&
packet.Type != PacketType.PacketAck &&
packet.Type != PacketType.LogoutRequest)
{
packet.Header.AckList = new uint[User_info.PendingAcks.Count];
int i = 0;
foreach (uint ack in User_info.PendingAcks.Values)
{
packet.Header.AckList[i] = ack;
i++;
}
User_info.PendingAcks.Clear();
packet.Header.AppendedAcks = true;
}
}
}
}
}
// Serialize the packet
buffer = packet.ToBytes();
bytes = buffer.Length;
try
{
// Zerocode if needed
if (packet.Header.Zerocoded)
{
lock (ZeroOutBuffer)
{
bytes = Helpers.ZeroEncode(buffer, bytes, ZeroOutBuffer);
Connection.SendTo(ZeroOutBuffer, bytes, SocketFlags.None,User_info.endpoint);
}
}
else
{
Connection.SendTo(buffer, bytes, SocketFlags.None,User_info.endpoint);
}
}
catch (SocketException)
{
//Client.Log("Tried to send a " + packet.Type.ToString() + " on a closed socket",
// Helpers.LogLevel.Warning);
Disconnect();
}
}
/// <summary>
/// Send a raw byte array payload as a packet
/// </summary>
/// <param name="payload">The packet payload</param>
/// <param name="setSequence">Whether the second, third, and fourth bytes
/// should be modified to the current stream sequence number</param>
/// <summary>
/// Returns Simulator Name as a String
/// </summary>
/// <returns></returns>
public override string ToString()
{
return( " (" + ipEndPoint.ToString() + ")");
}
/// <summary>
/// Sends out pending acknowledgements
/// </summary>
private void SendAcks(User_Agent_info User_info)
{
lock (User_info.PendingAcks)
{
if (connected && User_info.PendingAcks.Count > 0)
{
if (User_info.PendingAcks.Count > 250)
{
// FIXME: Handle the odd case where we have too many pending ACKs queued up
//Client.Log("Too many ACKs queued up!", Helpers.LogLevel.Error);
return;
}
int i = 0;
PacketAckPacket acks = new PacketAckPacket();
acks.Packets = new PacketAckPacket.PacketsBlock[User_info.PendingAcks.Count];
foreach (uint ack in User_info.PendingAcks.Values)
{
acks.Packets[i] = new PacketAckPacket.PacketsBlock();
acks.Packets[i].ID = ack;
i++;
}
acks.Header.Reliable = false;
SendPacket(acks, true,User_info);
User_info.PendingAcks.Clear();
}
}
}
/// <summary>
/// Resend unacknowledged packets
/// </summary>
private void ResendUnacked(User_Agent_info User_info)
{
if (connected)
{
int now = Environment.TickCount;
lock (User_info.NeedAck)
{
foreach (Packet packet in User_info.NeedAck.Values)
{
if (now - packet.TickCount > Settings.RESEND_TIMEOUT)
{
// Client.Log("Resending " + packet.Type.ToString() + " packet, " +
// (now - packet.TickCount) + "ms have passed", Helpers.LogLevel.Info);
packet.Header.Resent = true;
SendPacket(packet, false,User_info);
}
}
}
}
}
/// <summary>
/// Callback handler for incomming data
/// </summary>
/// <param name="result"></param>
private void OnReceivedData(IAsyncResult result)
{
ipeSender = new IPEndPoint(IPAddress.Any, 0);
epSender = (EndPoint)ipeSender;
Packet packet = null;
int numBytes;
// If we're receiving data the sim connection is open
connected = true;
// Update the disconnect flag so this sim doesn't time out
DisconnectCandidate = false;
User_Agent_info User_info=null;
lock (RecvBuffer)
{
// Retrieve the incoming packet
try
{
numBytes = Connection.EndReceiveFrom(result, ref epSender);
//find user_agent_info
int packetEnd = numBytes - 1;
packet = Packet.BuildPacket(RecvBuffer, ref packetEnd, ZeroBuffer);
//should check if login/useconnection packet first
if (packet.Type == PacketType.UseCircuitCode)
{
UseCircuitCodePacket cir_pack=(UseCircuitCodePacket)packet;
User_Agent_info new_user=new User_Agent_info();
new_user.circuitCode=cir_pack.CircuitCode.Code;
new_user.AgentID=cir_pack.CircuitCode.ID;
new_user.SessionID=cir_pack.CircuitCode.SessionID;
new_user.endpoint=epSender;
new_user.Inbox = new Queue<uint>(Settings.INBOX_SIZE);
this.CallbackObject.NewUserCallback(new_user);
this.User_agents.Add(new_user);
}
User_Agent_info temp_agent=null;
IPEndPoint send_ip=(IPEndPoint)epSender;
// this.callback_object.error("incoming: address is "+send_ip.Address +"port number is: "+send_ip.Port.ToString());
for(int ii=0; ii<this.User_agents.Count ; ii++)
{
temp_agent=(User_Agent_info)this.User_agents[ii];
IPEndPoint ag_ip=(IPEndPoint)temp_agent.endpoint;
//this.callback_object.error("searching: address is "+ag_ip.Address +"port number is: "+ag_ip.Port.ToString());
if((ag_ip.Address.ToString()==send_ip.Address.ToString()) && (ag_ip.Port.ToString()==send_ip.Port.ToString()))
{
//this.callback_object.error("found user");
User_info=temp_agent;
break;
}
}
Connection.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null);
}
catch (SocketException)
{
// Client.Log(endPoint.ToString() + " socket is closed, shutting down " + this.Region.Name,
// Helpers.LogLevel.Info);
connected = false;
//Network.DisconnectSim(this);
return;
}
}
if(User_info==null)
{
//error finding agent
this.CallbackObject.ErrorCallback("no user found");
return;
}
// Fail-safe check
if (packet == null)
{
this.CallbackObject.ErrorCallback("couldn't build packet");
// Client.Log("Couldn't build a message from the incoming data", Helpers.LogLevel.Warning);
return;
}
//this.callback_object.error("past tests");
// Track the sequence number for this packet if it's marked as reliable
if (packet.Header.Reliable)
{
if (User_info.PendingAcks.Count > Settings.MAX_PENDING_ACKS)
{
SendAcks(User_info);
}
// Check if we already received this packet
if (User_info.Inbox.Contains(packet.Header.Sequence))
{
//Client.Log("Received a duplicate " + packet.Type.ToString() + ", sequence=" +
// packet.Header.Sequence + ", resent=" + ((packet.Header.Resent) ? "Yes" : "No") +
// ", Inbox.Count=" + Inbox.Count + ", NeedAck.Count=" + NeedAck.Count,
// Helpers.LogLevel.Info);
// Send an ACK for this packet immediately
//SendAck(packet.Header.Sequence);
// TESTING: Try just queuing up ACKs for resent packets instead of immediately triggering an ACK
lock (User_info.PendingAcks)
{
uint sequence = (uint)packet.Header.Sequence;
if (!User_info.PendingAcks.ContainsKey(sequence)) { User_info.PendingAcks[sequence] = sequence; }
}
// Avoid firing a callback twice for the same packet
// this.callback_object.error("avoiding callback");
return;
}
else
{
lock (User_info.PendingAcks)
{
uint sequence = (uint)packet.Header.Sequence;
if (!User_info.PendingAcks.ContainsKey(sequence)) { User_info.PendingAcks[sequence] = sequence; }
}
}
}
// Add this packet to our inbox
lock (User_info.Inbox)
{
while (User_info.Inbox.Count >= Settings.INBOX_SIZE)
{
User_info.Inbox.Dequeue();
}
User_info.Inbox.Enqueue(packet.Header.Sequence);
}
// Handle appended ACKs
if (packet.Header.AppendedAcks)
{
lock (User_info.NeedAck)
{
foreach (uint ack in packet.Header.AckList)
{
User_info.NeedAck.Remove(ack);
}
}
}
// Handle PacketAck packets
if (packet.Type == PacketType.PacketAck)
{
PacketAckPacket ackPacket = (PacketAckPacket)packet;
lock (User_info.NeedAck)
{
foreach (PacketAckPacket.PacketsBlock block in ackPacket.Packets)
{
User_info.NeedAck.Remove(block.ID);
}
}
}
this.CallbackObject.MainCallback(packet,User_info);
}
private void AckTimer_Elapsed(object sender, ElapsedEventArgs ea)
{
if (connected)
{
//TODO for each user_agent_info
for(int i=0; i<this.User_agents.Count; i++)
{
User_Agent_info user=(User_Agent_info)this.User_agents[i];
SendAcks(user);
ResendUnacked(user);
}
}
}
}
public class Server_Settings
{
/// <summary>The version of libsecondlife (not the SL protocol itself)</summary>
public string VERSION = "libsecondlife 0.0.9";
/// <summary>XML-RPC login server to connect to</summary>
public string LOGIN_SERVER = "https://login.agni.lindenlab.com/cgi-bin/login.cgi";
/// <summary>Millisecond interval between ticks, where all ACKs are
/// sent out and the age of unACKed packets is checked</summary>
public readonly int NETWORK_TICK_LENGTH = 500;
/// <summary>The maximum value of a packet sequence number. After that
/// we assume the sequence number just rolls over? Or maybe the
/// protocol isn't able to sustain a connection past that</summary>
public readonly int MAX_SEQUENCE = 0xFFFFFF;
/// <summary>Number of milliseconds before a teleport attempt will time
/// out</summary>
public readonly int TELEPORT_TIMEOUT = 18 * 1000;
/// <summary>Number of milliseconds before NetworkManager.Logout() will time out</summary>
public int LOGOUT_TIMEOUT = 5 * 1000;
/// <summary>Number of milliseconds for xml-rpc to timeout</summary>
public int LOGIN_TIMEOUT = 30 * 1000;
/// <summary>The maximum size of the sequence number inbox, used to
/// check for resent and/or duplicate packets</summary>
public int INBOX_SIZE = 100;
/// <summary>Milliseconds before a packet is assumed lost and resent</summary>
public int RESEND_TIMEOUT = 4000;
/// <summary>Milliseconds before the connection to a simulator is
/// assumed lost</summary>
public int SIMULATOR_TIMEOUT = 15000;
/// <summary>Maximum number of queued ACKs to be sent before SendAcks()
/// is forced</summary>
public int MAX_PENDING_ACKS = 10;
/// <summary>Maximum number of ACKs to append to a packet</summary>
public int MAX_APPENDED_ACKS = 10;
/// <summary>Cost of uploading an asset</summary>
public int UPLOAD_COST { get { return priceUpload; } }
private int priceUpload = 0;
public Server_Settings()
{
}
}
public class User_Agent_info
{
public EndPoint endpoint;
public LLUUID AgentID;
public LLUUID SessionID;
public uint circuitCode;
public string name;
public uint localID;
public string first_name;
public string last_name;
public Dictionary<uint, Packet> NeedAck = new Dictionary<uint, Packet>();
// Sequence numbers of packets we've received from the simulator
public Queue<uint> Inbox;
// ACKs that are queued up to be sent to the simulator
public Dictionary<uint, uint> PendingAcks = new Dictionary<uint, uint>();
public User_Agent_info()
{
}
}
}
|