public void ConnectToLoginServer(string server = null) { if (!string.IsNullOrEmpty(server)) { Server = server; } if (string.IsNullOrEmpty(Server)) { throw new ArgumentException("OwnerServer"); } if (Session == null) { Session = new Session(); } var addr = Dns.GetHostAddresses(Server); if (addr.Length == 0) { _logger.Error("Failed to resolve '{0}' to an ipaddress", Server); return; } _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _socketReader = new SocketReader(Session, _socket); _socketWriter = new SocketWriter(Session, _socket); var ip = addr.First(); _logger.Trace("resolved {0} to '{1}'", ip, Server); var endpoint = new IPEndPoint(ip, 44453); _socketReader.MaxMessageSize = 496; Session.Command = SessionCommand.Connect; _socket.Connect(endpoint); _socketReader.Start().WaitOne(Timeout); _socketWriter.Start().WaitOne(Timeout); var timeout = DateTime.Now.AddMilliseconds(Timeout); while (Session.Status != SessionStatus.Connected && Session.Status != SessionStatus.Error) { if (timeout <= DateTime.Now) { throw new TimeoutException("Timeout waiting for server conenction"); } Thread.Sleep(Timeout / 10); } }
public void SendPacket(Packet ToSend) { Int32 outlen = 0; ToSend.ReadIndex = 0; var packetType = ToSend.PacetTypeEnum; byte packetTypeLow = ToSend.PeekByte(); Array.ConstrainedCopy(ToSend.Data, 0, SendBuffer, 0, 2); if (packetType == SessionOp.SessionRequest || packetType == SessionOp.CriticalError) { Socket.Send(ToSend.Data, ToSend.Size, SocketFlags.None); return; } if (ToSend.Compressed) { var offset = packetTypeLow == 0 ? 2 : 1; outlen = _enccom.Compress(ToSend.Data, ToSend.Size - offset, SendBuffer, SendBuffer.Length - offset, offset, offset); if (outlen != 0) { SendBuffer[outlen + offset] = 0x1; outlen += offset + 1; } else { Array.ConstrainedCopy(ToSend.Data, 0, SendBuffer, 0, ToSend.Size); outlen = ToSend.Size; SendBuffer[outlen] = 0x0; outlen++; } } else { Array.ConstrainedCopy(ToSend.Data, 0, SendBuffer, 0, ToSend.Size); outlen = ToSend.Size; SendBuffer[outlen] = 0x0; outlen += 1; } if (ToSend.Encrypted) { var offset = packetTypeLow == 0 ? 2 : 1; if (packetTypeLow == 0 || packetTypeLow < 0x0d) { _enccom.Encrypt(SendBuffer, outlen - offset, Session.EncryptionKey, offset); } ToSend.CRC = _enccom.GenerateCRC(SendBuffer, outlen, Session.EncryptionKey, 0); SendBuffer[outlen] = (byte)(ToSend.CRC >> 8); SendBuffer[outlen + 1] = (byte)ToSend.CRC; outlen += 2; } else if (ToSend.SendCRC) { ToSend.CRC = _enccom.GenerateCRC(SendBuffer, outlen, Session.EncryptionKey, 0); SendBuffer[outlen] = (byte)(ToSend.CRC >> 8); SendBuffer[outlen + 1] = (byte)ToSend.CRC; outlen += 2; } SocketError error; Socket.Send(SendBuffer, 0, outlen, SocketFlags.None, out error); if (error != SocketError.Success) { _logger.Error("Error sending data: {0}", error); } }
public void EstablishConnection(uint userId, byte[] sessionKey, IPAddress address, int port) { ConnectedAddress = address; ConnectedPort = port; Session = new Session(); _Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _SocketReader = new SocketReader(Session, _Socket); _SocketWriter = new SocketWriter(Session, _Socket); Session.Command = SessionCommand.Connect; _logger.Debug("Connecting to zone server at {0}:{1}", address, port); _Socket.Connect(address, port); _SocketReader.Start().WaitOne(ConnectTimeout); _SocketWriter.Start().WaitOne(ConnectTimeout); var timeout = DateTime.Now.Add(ConnectTimeout); while (Session.Status != SessionStatus.Connected && Session.Status != SessionStatus.Error) { if (timeout <= DateTime.Now) { _logger.Error("Timeout waiting for connecting to establish"); throw new TimeoutException("Timeout waiting for server conenction"); } Thread.Sleep(TimeSpan.FromMilliseconds(ConnectTimeout.TotalMilliseconds / 10)); } if (!Start().WaitOne(ConnectTimeout)) { _logger.Error("ObjectGraph service failed to start in time"); throw new TimeoutException("Timeout waiting for server conenction"); } var clientIDMsg = new ClientIDMessage(userId, sessionKey); clientIDMsg.AddFieldsToData(); Session.SendChannelA(clientIDMsg); var messages = Messages.WaitForMessages(Convert.ToInt32(ConnectTimeout.TotalMilliseconds), MessageOp.ErrorMessage, MessageOp.ClientPermissionsMessage); if (messages == null) { _logger.Error("Timeout waiting for ClientPermissionsMessage"); throw new TimeoutException("Timeout waiting for server connection"); } var errorMsg = Message.Create <ErrorMessage>( messages.FirstOrDefault(cur => cur.MessageOpCodeEnum == MessageOp.ErrorMessage)); if (errorMsg != null) { _logger.Error("Error getting client permission: [{0}] {1}", errorMsg.ErrorType, errorMsg.Message); throw new Exception(string.Format("[{0}] {1}", errorMsg.ErrorType, errorMsg.Message)); } var permissionMessage = Message.Create <ClientPermissionsMessage>( messages.FirstOrDefault(cur => cur.MessageOpCodeEnum == MessageOp.ClientPermissionsMessage)); if (permissionMessage == null) { _logger.Error("Unknow packet when expecting ClientPermissionsMessage"); throw new Exception("Unknown error connecting to server"); } SelectedGalaxyOpen = permissionMessage.GalaxyOpenFlag == 1; CanCreateCharacterOnGalaxy = permissionMessage.CharacterSlotOpenFlag == 1; }
protected override void DoWork() { Packet recievedPacket; int recievedCount = 0; SocketError error; recievedPacket = new Packet(496); recievedCount = Socket.Receive(recievedPacket.Data, 0, MaxMessageSize, SocketFlags.None, out error); if (error != SocketError.Success) { _logger.Error("Socket Error: {0}", error); } if (error == SocketError.ConnectionReset) { Session.Command = SessionCommand.Disconnect; _exit = true; } else if (error == SocketError.Interrupted) //we closed the socket { return; } if (recievedCount > MaxMessageSize || recievedCount == 0) { _logger.Warn("Recieved count ({0}) larger than max packet size", recievedCount); return; } recievedPacket.Reset(); recievedPacket.Size = recievedCount; byte packetTypeLow = recievedPacket.PeekByte(); UInt16 packetType = recievedPacket.PeekUInt16(); SessionOp packetTypeEnum = recievedPacket.PacetTypeEnum; if (packetType > 0x00ff && (packetType & 0x00ff) == 0) { switch (packetTypeEnum) { case SessionOp.Disconnect: case SessionOp.DataAck1: case SessionOp.DataAck2: case SessionOp.DataAck3: case SessionOp.DataAck4: case SessionOp.DataOrder1: case SessionOp.DataOrder2: case SessionOp.DataOrder3: case SessionOp.DataOrder4: case SessionOp.Ping: _HandleEncryptedPacket(recievedPacket, recievedCount); break; case SessionOp.MultiPacket: case SessionOp.NetStatRequest: case SessionOp.NetStatResponse: case SessionOp.DataChannel1: case SessionOp.DataChannel2: case SessionOp.DataChannel3: case SessionOp.DataChannel4: case SessionOp.DataFrag1: case SessionOp.DataFrag2: case SessionOp.DataFrag3: case SessionOp.DataFrag4: _HandleCompressedEncryptedPacket(recievedPacket, recievedCount); break; case SessionOp.SessionRequest: case SessionOp.SessionResponse: case SessionOp.FatalError: case SessionOp.FatalErrorResponse: Session.HandleSessionPacket(recievedPacket); break; } } else if (packetTypeLow < 0x0d) { _HandleFastpathPacket(recievedPacket, recievedCount); } else { _logger.Warn("Invalid packet type: {0:X}. Type Enum: {1}", packetType, packetTypeEnum); } Thread.Sleep(WaitTime); }