/// <summary>Initializes a new instance of the <see cref="MySqlStorage" /> class.</summary> /// <param name="connectionString">the connection details.</param> /// <param name="flags">The connection flags.</param> public MySqlStorage(ConnectionString connectionString, ConnectionFlags flags = default) : base(connectionString, flags) { VersionString = (string)QueryValue("SELECT VERSION()"); if (VersionString == null) { throw new InvalidDataException("Could not read mysql version!"); } if (VersionString.IndexOf('-') > -1) { Version = new Version(VersionString.Substring(0, VersionString.IndexOf('-'))); } else { Version = new Version(VersionString); } if (Version < new Version(5, 5, 3)) { SupportsFullUTF8 = false; CharacterSet = "utf8"; } else { SupportsFullUTF8 = true; CharacterSet = "utf8mb4"; } Trace.TraceInformation($"mysql version <cyan>{Version}<default> supports full utf-8 {(SupportsFullUTF8 ? "<green>" : "<red>") + SupportsFullUTF8}"); ClearCachedConnections(); }
//! Constructor for asynchronous connections. public MySqlConnection(ProducerConsumerQueue <SqlOperation> queue, MySqlConnectionInfo connectionInfo) { _queue = queue; _connectionInfo = connectionInfo; _connectionFlags = ConnectionFlags.CONNECTION_ASYNC; _worker = new DatabaseWorker(_queue, this); }
protected void PrepareStatement(int index, string sql, ConnectionFlags flags) { // Check if specified query should be prepared on this connection // i.e. don't prepare async statements on synchronous connections // to save memory that will not be used. if ((_connectionFlags & flags) == 0) { _stmts[index] = null; return; } var stmt = mysql_stmt_init(_mysql); if (stmt == IntPtr.Zero) { FEL_LOG_ERROR("sql.sql", "In mysql_stmt_init() id: {0}, sql: \"{1}\"", index, sql); FEL_LOG_ERROR("sql.sql", "{0}", mysql_error(_mysql)); _prepareError = true; } else { if (mysql_stmt_prepare(stmt, sql) != 0) { FEL_LOG_ERROR("sql.sql", "In mysql_stmt_prepare() id: {0}, sql: \"{1}\"", index, sql); FEL_LOG_ERROR("sql.sql", "{0}", mysql_stmt_error(stmt)); mysql_stmt_close(stmt); _prepareError = true; } else { _stmts[index] = new MySqlPreparedStatement(stmt, sql); } } }
/// <summary>Initializes a new instance of the <see cref="FileStorage" /> class. /// <para>Following formats are supported:<br /> file://server/relativepath<br /> file:absolutepath.<br /></para> /// </summary> /// <param name="connectionString">ConnectionString of the storage.</param> /// <param name="options">The options.</param> protected FileStorage(ConnectionString connectionString, ConnectionFlags options) : base(connectionString, options) { if (string.IsNullOrEmpty(connectionString.Server)) { connectionString.Server = "localhost"; } if ((connectionString.Server != "localhost") && (connectionString.Server != ".")) { throw new NotSupportedException("Remote access via server setting is not supported atm.! (use localhost or .)"); } if (string.IsNullOrEmpty(connectionString.Location) || !connectionString.Location.Contains("/")) { connectionString.Location = $"./{connectionString.Location}"; } Folder = Path.GetFullPath(Path.GetDirectoryName(connectionString.Location)); if (!Directory.Exists(Folder)) { try { Directory.CreateDirectory(Folder); } catch (Exception ex) { throw new DirectoryNotFoundException($"The directory '{connectionString.Location}' cannot be found or created!", ex); } } }
/// <summary>Initializes a new instance of the <see cref="PgSqlStorage" /> class.</summary> /// <param name="connectionString">the connection details.</param> /// <param name="flags">The connection flags.</param> public PgSqlStorage(ConnectionString connectionString, ConnectionFlags flags = default) : base(connectionString, flags) { VersionString = (string)QueryValue("SELECT VERSION()"); var parts = VersionString.Split(' '); Version = new Version(parts[1]); Trace.TraceInformation($"pgsql version {Version}"); }
public void Abort() { try { if(DbConnection != null && DbConnection.State == ConnectionState.Open && DbTransaction != null) DbTransaction.Rollback(); DbTransaction = null; Flags &= ~ConnectionFlags.CommitOnSave; this.Session.LogMessage("--ROLLBACK TRANS"); } catch { } }
/// <summary>Initializes a new instance of the <see cref="Storage" /> class.</summary> /// <param name="connectionString">ConnectionString of the storage.</param> /// <param name="flags">The connection flags.</param> protected Storage(ConnectionString connectionString, ConnectionFlags flags) { ConnectionString = connectionString; AllowUnsafeConnections = flags.HasFlag(ConnectionFlags.AllowUnsafeConnections); LogVerboseMessages = flags.HasFlag(ConnectionFlags.VerboseLogging); if (LogVerboseMessages) { Trace.TraceInformation("Verbose logging <green>enabled!"); } }
/// <summary> /// Connects to a database storage. /// </summary> /// <param name="connectionString">The connection string.</param> /// <param name="options">The options.</param> /// <returns>Returns a new storage connection.</returns> /// <exception cref="NotSupportedException">Unknown database provider '{connectionString.Protocol}'!.</exception> public static IStorage ConnectStorage(ConnectionString connectionString, ConnectionFlags options = 0) { return(connectionString.ConnectionType switch { ConnectionType.MEMORY => new MemoryStorage(), ConnectionType.MYSQL => new MySqlStorage(connectionString, options), ConnectionType.MSSQL => new MsSqlStorage(connectionString, options), ConnectionType.SQLITE => new SQLiteStorage(connectionString, options), ConnectionType.PGSQL => new PgSqlStorage(connectionString, options), _ => throw new NotSupportedException($"Unknown database provider '{connectionString.Protocol}'!"), });
public void Abort() { try { if (DbConnection != null && DbConnection.State == ConnectionState.Open && DbTransaction != null) { DbTransaction.Rollback(); } DbTransaction = null; Flags &= ~ConnectionFlags.CommitOnSave; this.Session.LogMessage("--ROLLBACK TRANS"); } catch { } }
public async Task OnDataChannelEncryptionDisabled() { ClientDataConnection.DisableEncryption(); ActionsTracker.ConnectionSecurityChanged(null, new ConnectionSecurityChangedEventArgs() { EndPoint = ClientInitialRemoteEndPoint, Security = ConnectionFlags.HasFlag(ControlConnectionFlags.UsingTLSorSSL) ? ConnectionSecurity.ControlConnectionSecured : ConnectionSecurity.NonSecure }); }
#pragma warning disable CA2214 // Constructor calls virtual method to retrieve required database connection class /// <summary>Initializes a new instance of the <see cref="SqlStorage" /> class.</summary> /// <param name="connectionString">the connection details.</param> /// <param name="flags">The connection flags.</param> protected SqlStorage(ConnectionString connectionString, ConnectionFlags flags = ConnectionFlags.None) : base(connectionString, flags) { Trace.TraceInformation("Initializing native interop assemblies."); using (var dbConnection = GetDbConnectionType()) using (var cmd = dbConnection.CreateCommand()) { DbConnectionType = dbConnection.GetType(); } pool = new SqlConnectionPool(this); WarnUnsafe(); }
public static string UseConnection(Control ownerWindow, NetResource netResource, string password, string userId, ConnectionFlags flags) { StringBuilder accessName = new StringBuilder(0); int length = 0; int result = 0; GenerateExceptionIfError(WNet_Api.WNetUseConnection(Common.ControlToHwnd(ownerWindow), netResource, password, userId, flags, accessName, ref length, ref result), WNetErrors.NoError, WNetErrors.NoMoreData); accessName = new StringBuilder(length); GenerateExceptionIfError(WNet_Api.WNetUseConnection(Common.ControlToHwnd(ownerWindow), netResource, password, userId, flags, accessName, ref length, ref result)); return(accessName.ToString()); }
public void Commit() { if (DbTransaction == null) { return; } DbTransaction.Commit(); DbTransaction = null; Flags &= ~ConnectionFlags.CommitOnSave; var now = Session.Context.App.TimeService.ElapsedMilliseconds; //Log Commit trans var msg = string.Format("{0} -- {1} ms", this.Database.Settings.Driver.BatchCommitTransaction, now - _transactionStart); this.Session.LogMessage(msg); }
public void BeginTransaction(bool commitOnSave, IsolationLevel isolationLevel = IsolationLevel.Unspecified) { if (DbConnection.State != ConnectionState.Open) { Open(); } DbTransaction = isolationLevel == IsolationLevel.Unspecified ? DbConnection.BeginTransaction() : DbConnection.BeginTransaction(isolationLevel); _transactionStart = Session.Context.App.TimeService.ElapsedMilliseconds; //Log begin trans if (commitOnSave) { Flags |= ConnectionFlags.CommitOnSave; } this.Session.LogMessage(this.Database.Settings.Driver.BatchBeginTransaction); }
/// <summary>Connects to a database storage.</summary> /// <param name="connectionString">The connection string.</param> /// <param name="options">The options.</param> /// <returns>Returns a new storage connection.</returns> /// <exception cref="NotSupportedException">Unknown database provider '{connectionString.Protocol}'!.</exception> public static IStorage ConnectStorage(ConnectionString connectionString, ConnectionFlags options = 0) { switch (connectionString.ConnectionType) { case ConnectionType.MEMORY: return(new MemoryStorage()); case ConnectionType.MYSQL: return(new MySqlStorage(connectionString, options)); case ConnectionType.MSSQL: return(new MsSqlStorage(connectionString, options)); case ConnectionType.SQLITE: return(new SQLiteStorage(connectionString, options)); case ConnectionType.PGSQL: return(new PgSqlStorage(connectionString, options)); default: throw new NotSupportedException($"Unknown database provider '{connectionString.Protocol}'!"); } }
/// <summary>Connects to a database using the specified <see cref="ConnectionString" />.</summary> /// <param name="connection">The ConnectionString.</param> /// <param name="options">The database connection options.</param> /// <returns>Returns a new database connection.</returns> /// <exception cref="ArgumentException">Missing database name at connection string!.</exception> public static IDatabase ConnectDatabase(ConnectionString connection, ConnectionFlags options = ConnectionFlags.None) { var storage = ConnectStorage(connection, options); if (connection.Location == null) { throw new ArgumentOutOfRangeException(nameof(connection), "Database name not specified!"); } var parts = connection.Location.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 1) { throw new ArgumentException("Missing database name at connection string!"); } return(storage.GetDatabase(parts[0], (options & ConnectionFlags.AllowCreate) != 0)); }
private void SetFlag(ConnectionFlags flag, bool value) { int oldValue, newValue; do { oldValue = Thread.VolatileRead(ref flags); if (value) { newValue = oldValue | ((int) flag); } else { newValue = oldValue & ~((int) flag); } if (oldValue == newValue) return; } while (Interlocked.CompareExchange(ref flags, newValue, oldValue) != oldValue); }
private void SetFlag(ConnectionFlags flag, bool value) { int oldValue, newValue; do { oldValue = Thread.VolatileRead(ref flags); if (value) { newValue = oldValue | ((int)flag); } else { newValue = oldValue & ~((int)flag); } if (oldValue == newValue) { return; } } while (Interlocked.CompareExchange(ref flags, newValue, oldValue) != oldValue); }
public async Task OnDataChannelEncryptionEnabled() { if (!IsEncryptionSupported) { SendResponse(new FtpReply() { ReplyCode = FtpReplyCode.NotImplemented, Message = "Server is not configured to support SSL/TLS." }, false); return; } ClientDataConnection.ActivateEncryption(); ActionsTracker.ConnectionSecurityChanged(null, new ConnectionSecurityChangedEventArgs() { EndPoint = ClientInitialRemoteEndPoint, Security = ConnectionFlags.HasFlag(ControlConnectionFlags.UsingTLSorSSL) ? ConnectionSecurity.Both : ConnectionSecurity.DataChannelSecured }); Logger.Log($"Enabled encryption for datachannel : {ClientInitialRemoteEndPoint.ToString()}" , RecordKind.Status); }
public MySqlConnection(MySqlConnectionInfo connectionInfo) { _connectionInfo = connectionInfo; _connectionFlags = ConnectionFlags.CONNECTION_SYNCH; }
/// <summary> /// Opens a SQLite database. /// </summary> /// <param name="filename">The database filename.</param> /// <param name="flags"><see cref="ConnectionFlags"/> used to defined if the database is readonly, /// read/write and whether a new database file should be created if it does not already exist.</param> /// <param name="vfs"> /// The name of the sqlite3_vfs object that defines the operating system interface /// that the new database connection should use. If <see langword="null"/>, then /// the default sqlite3_vfs object is used.</param> /// <returns>A <see cref="SQLiteDatabaseConnection"/> instance.</returns> /// <seealso href="https://sqlite.org/c3ref/open.html"/> public static SQLiteDatabaseConnection Open(string filename, ConnectionFlags flags, string vfs) { Contract.Requires(filename != null); sqlite3 db; int rc = raw.sqlite3_open_v2(filename, out db, (int)flags, vfs); SQLiteException.CheckOk(rc); return new SQLiteDatabaseConnection(db); }
static Client OnConnectionError(ref ConnectionFlags flag) { flag = ConnectionFlags.SocketError; return(null); }
private Client OnClientConnected(Socket newGuy, ref ConnectionFlags flag) { #region hide //switch (Server.AuthMethod) //{ // case AuthMethod.UsernameOnly: // newGuy.Send(NameRequiredPacket); // break; // case AuthMethod.Full: // newGuy.Send(FullAuthRequiredPacket); // break; // case AuthMethod.InviteCode: // newGuy.Send(InviteCodeRequiredPacket); // break; // default: // throw new NotImplementedException(); //} #endregion byte[] buffer = new byte[32]; int bytesRead = 0; if (!Receive(newGuy, buffer, ref bytesRead)) return OnConnectionError(ref flag); using (Packet loginPacket = new Packet(Encoding.GetString(buffer))) { if (loginPacket.ReadString() == "1") { string username = loginPacket.ReadString(); flag = ConnectionFlags.Accepted; return new Client(username, newGuy); #region hide //if (buffer[0] == 0x45)// && AuthMethod == ChatServer.AuthMethod.UsernameOnly) // UsernameOnly //{ // string username = Helper.XorText(enc.GetString(buffer, 1, bytesRead - 1), buffer[0]); // while (this.Connections.ValuesWhere(c => c.Username == username).Any() || Program.ReservedNames.Contains(username.ToLower())) // username += (char)Helper.Randomizer.Next((int)'a', (int)'z'); // flag = ConnectionFlags.OK; // return new Client(username, newGuy); //} //else if (buffer[0] == 0x55 && AuthMethod == ChatServer.AuthMethod.Full) //{ // string[] data = GetLoginPacketParams(buffer, bytesRead); // if (Server.Password == data[1]) // { // flag = ConnectionFlags.OK; // return new Client(data[0], newGuy); // } // else // { // flag = ConnectionFlags.BadPassword; // return null; // } //} //else if (buffer[0] == 0x65 && AuthMethod == ChatServer.AuthMethod.InviteCode) //{ // string[] data = GetLoginPacketParams(buffer, bytesRead); // //data[1] = Helper.XorText(data[1], data[1].Length); // lock (Program.InviteCodes) // { // if (Program.InviteCodes.Contains(data[1])) // { // Program.InviteCodes.Remove(data[1]); // remove the invite code from the list // Program.Write(LogMessageType.Auth, "{0} used invite code {1}", data[0], data[1]); // flag = ConnectionFlags.OK; // return new Client(data[0], newGuy); // } // else // { // flag = ConnectionFlags.BadInviteCode; // return null; // } // } //} #endregion } else { flag = ConnectionFlags.BadFirstPacket; return null; } } /* if (buffer[0] < 128) { string username = Encoding.GetString(buffer, 1, bytesRead - 1); if (username.Length > 18) { username = new string(username.ToCharArray(), 0, 18); } flag = ConnectionFlags.Accepted; return new Client(username, newGuy); } else { flag = ConnectionFlags.BadFirstPacket; return null; } */ }
public void Commit() { if (DbTransaction == null) return; DbTransaction.Commit(); DbTransaction = null; Flags &= ~ConnectionFlags.CommitOnSave; var now = Session.Context.App.TimeService.ElapsedMilliseconds; //Log Commit trans var msg = string.Format("{0} -- {1} ms", this.Database.Settings.Driver.BatchCommitTransaction, now - _transactionStart); this.Session.LogMessage(msg); }
public static extern int WNetCancelConnection2(string name, ConnectionFlags flags, bool isForce);
private bool GetFlag(ConnectionFlags flag) { return (Thread.VolatileRead(ref flags) & (int) flag) != 0; }
public Connection(Component owner, ConnectionFlags flags, ConnectionDescription description) { Owner = owner; Flags = flags; Description = description; }
public static void CancelConnection(string name, ConnectionFlags options, bool isForce) { GenerateExceptionIfError(WNet_Api.WNetCancelConnection2(name, options, isForce)); }
public void BeginTransaction(bool commitOnSave, IsolationLevel isolationLevel = IsolationLevel.Unspecified) { if (DbConnection.State != ConnectionState.Open) Open(); DbTransaction = isolationLevel == IsolationLevel.Unspecified ? DbConnection.BeginTransaction() : DbConnection.BeginTransaction(isolationLevel); _transactionStart = Session.Context.App.TimeService.ElapsedMilliseconds; //Log begin trans if (commitOnSave) Flags |= ConnectionFlags.CommitOnSave; this.Session.LogMessage(this.Database.Settings.Driver.BatchBeginTransaction); }
public static bool IsSet(this ConnectionFlags flags, ConnectionFlags flag) { return((flags & flag) != 0); }
public static extern int WNetUseConnection(IntPtr owner, NetResource netResource, string password, string userId, ConnectionFlags flags, StringBuilder accessName, ref int bufferSize, ref int result);
public IList <ConnectionPoint> PositionConnections(PositionalComponent instance, ComponentDescription description, LayoutOptions layoutOptions) { var connections = new List <ConnectionPoint>(); foreach (ConnectionGroup group in description.Connections) { if (group.Conditions.IsMet(instance, description)) { foreach (ConnectionDescription connectionDescription in group.Value) { Point start = connectionDescription.Start.Resolve(instance.Layout, layoutOptions); start = start.WithNewX(Math.Ceiling(start.X / layoutOptions.GridSize) * layoutOptions.GridSize); start = start.WithNewY(Math.Ceiling(start.Y / layoutOptions.GridSize) * layoutOptions.GridSize); Point end = connectionDescription.End.Resolve(instance.Layout, layoutOptions); end = end.WithNewX(Math.Floor(end.X / layoutOptions.GridSize) * layoutOptions.GridSize); end = end.WithNewY(Math.Floor(end.Y / layoutOptions.GridSize) * layoutOptions.GridSize); // Reverse if in the wrong order bool reversed = false; if ((start.X == end.X && end.Y < start.Y) || (start.Y == end.Y && end.X < start.X)) { Point temp = start; start = end; end = temp; reversed = true; } if (connectionDescription.Start.Resolve(instance.Layout, layoutOptions).X == connectionDescription.End.Resolve(instance.Layout, layoutOptions).X) // use original coordinates to check correctly when single point { for (double i = start.Y; i <= end.Y; i += layoutOptions.GridSize) { var flags = ConnectionFlags.Vertical; if (!reversed) { if (i == start.Y && (connectionDescription.Edge == ConnectionEdge.Start || connectionDescription.Edge == ConnectionEdge.Both)) { flags |= ConnectionFlags.Edge; } else if (i == end.Y && (connectionDescription.Edge == ConnectionEdge.End || connectionDescription.Edge == ConnectionEdge.Both)) { flags |= ConnectionFlags.Edge; } } else if (instance.Layout.Orientation == Orientation.Vertical) { if (i == start.Y && (connectionDescription.Edge == ConnectionEdge.End || connectionDescription.Edge == ConnectionEdge.Both)) { flags |= ConnectionFlags.Edge; } else if (i == end.Y && (connectionDescription.Edge == ConnectionEdge.Start || connectionDescription.Edge == ConnectionEdge.Both)) { flags |= ConnectionFlags.Edge; } } var location = new Point(instance.Layout.Location.X + start.X, instance.Layout.Location.Y + i); connections.Add(new ConnectionPoint(location, connectionDescription.Name, flags)); } } else if (start.Y == end.Y) { for (double i = start.X; i <= end.X; i += layoutOptions.GridSize) { ConnectionFlags flags = ConnectionFlags.Horizontal; if (!reversed) { if (i == start.X && (connectionDescription.Edge == ConnectionEdge.Start || connectionDescription.Edge == ConnectionEdge.Both)) { flags |= ConnectionFlags.Edge; } else if (i == end.X && (connectionDescription.Edge == ConnectionEdge.End || connectionDescription.Edge == ConnectionEdge.Both)) { flags |= ConnectionFlags.Edge; } } else if (instance.Layout.Orientation == Orientation.Horizontal && reversed) { if (i == start.X && (connectionDescription.Edge == ConnectionEdge.End || connectionDescription.Edge == ConnectionEdge.Both)) { flags |= ConnectionFlags.Edge; } else if (i == end.X && (connectionDescription.Edge == ConnectionEdge.Start || connectionDescription.Edge == ConnectionEdge.Both)) { flags |= ConnectionFlags.Edge; } } var location = new Point(instance.Layout.Location.X + i, instance.Layout.Location.Y + start.Y); connections.Add(new ConnectionPoint(location, connectionDescription.Name, flags)); } } } } } return(connections); }
private bool GetFlag(ConnectionFlags flag) { return((Thread.VolatileRead(ref flags) & (int)flag) != 0); }
private Client OnConnectionError(ref ConnectionFlags flag) { flag = ConnectionFlags.SocketError; return null; }
public ConnectionPoint(Point location, ConnectionName connection, ConnectionFlags flags) { Location = location; Connection = connection; Flags = flags; }
private Client OnClientConnected(Socket newGuy, ref ConnectionFlags flag) { switch (Server.AuthMethod) { case AuthMethod.UsernameOnly: newGuy.Send(NameRequiredPacket); break; case AuthMethod.Full: newGuy.Send(FullAuthRequiredPacket); break; case AuthMethod.InviteCode: newGuy.Send(InviteCodeRequiredPacket); break; default: throw new NotImplementedException(); } byte[] buffer = new byte[768]; int bytesRead = 0; if (!Receive(newGuy, buffer, ref bytesRead)) { return(OnConnectionError(ref flag)); } if (buffer[0] < 128) { if (buffer[0] == 0x45 && AuthMethod == ChatServer.AuthMethod.UsernameOnly) // UsernameOnly { string username = Helper.XorText(enc.GetString(buffer, 1, bytesRead - 1), buffer[0]); while (this.Connections.ValuesWhere(c => c.Username == username).Any() || Program.ReservedNames.Contains(username.ToLower())) { username += (char)Helper.Randomizer.Next((int)'a', (int)'z'); } flag = ConnectionFlags.OK; return(new Client(username, newGuy)); } else if (buffer[0] == 0x55 && AuthMethod == ChatServer.AuthMethod.Full) { string[] data = GetLoginPacketParams(buffer, bytesRead); if (Server.Password == data[1]) { flag = ConnectionFlags.OK; return(new Client(data[0], newGuy)); } else { flag = ConnectionFlags.BadPassword; return(null); } } else if (buffer[0] == 0x65 && AuthMethod == ChatServer.AuthMethod.InviteCode) { string[] data = GetLoginPacketParams(buffer, bytesRead); //data[1] = Helper.XorText(data[1], data[1].Length); lock (Program.InviteCodes) { if (Program.InviteCodes.Contains(data[1])) { Program.Write(LogMessageType.Auth, "{0} used invite code {1}", data[0], data[1]); Program.InviteCodes.Remove(data[1]); // remove the invite code from the list if (Program.InviteCodes.Count == 0) { Program.Write(LogMessageType.Warning, "All invite codes have been used."); } flag = ConnectionFlags.OK; return(new Client(data[0], newGuy)); } else { flag = ConnectionFlags.BadInviteCode; return(null); } } } } else { flag = ConnectionFlags.BadFirstPacket; return(null); } return(null); }
/// <summary>Initializes a new instance of the <see cref="MsSqlStorage" /> class.</summary> /// <param name="connectionString">the connection details.</param> /// <param name="flags">The connection flags.</param> public MsSqlStorage(ConnectionString connectionString, ConnectionFlags flags = default) : base(connectionString, flags) { }
void StartListening() { try { _listener.Start(); Listen = true; Program.Write(LogMessageType.Network, "Started listening on port " + this.port); } catch { Program.Write("There may be another server listening on this port, we can't start our TCP listener", "Network", ConsoleColor.Magenta); } while (Listen) { try { Socket socket = _listener.AcceptSocket(); if (Connections.Count + 1 > maxConnections) { socket.Send(ServerIsFullPacket); socket.Close(); Thread.Sleep(500); continue; } if (this.Blacklist.Contains(socket.RemoteEndPoint.ToString().Split(':')[0])) { Program.Write(LogMessageType.Auth, "Rejected blacklisted IP: {0}", socket.RemoteEndPoint.ToString()); socket.Send(BlacklistedPacket); socket.Close(); continue; } var watch = Stopwatch.StartNew(); Program.Write(LogMessageType.Network, "Incoming connection"); ConnectionFlags flag = ConnectionFlags.None; Client client = OnClientConnected(socket, ref flag); if (client != null && flag == ConnectionFlags.OK) { OnSuccessfulClientConnect(client); } else if ((flag == ConnectionFlags.BadPassword && AuthMethod == ChatServer.AuthMethod.Full) || flag == ConnectionFlags.BadFirstPacket || flag == ConnectionFlags.BadInviteCode) { try { socket.Send(AccessDeniedPacket); socket.Shutdown(SocketShutdown.Both); Program.Write(LogMessageType.Auth, "A client failed to connect"); } finally { socket.Close(); socket = null; } } else if (flag == ConnectionFlags.SocketError) { Program.Write("Socket error on connection", "Auth", ConsoleColor.Red); } watch.Stop(); Program.Write("Handled new connection in " + watch.Elapsed.TotalSeconds + " seconds", "Trace"); } catch (SocketException e) { Program.Write("Exception code: " + e.ErrorCode, "Socket Error", ConsoleColor.Red); break; } } }
/// <summary> /// Parse the AUX_CLIENT_CONNECTION_INFO structure. /// </summary> /// <param name="s">A stream containing the AUX_ENDPOINT_CAPABILITIES structure</param> public override void Parse(Stream s) { base.Parse(s); this.ConnectionGUID = ReadGuid(); this.OffsetConnectionContextInfo = ReadUshort(); this.Reserved = ReadUshort(); this.ConnectionAttempts = ReadUint(); this.ConnectionFlags = (ConnectionFlags)ReadUint(); if (OffsetConnectionContextInfo != 0) { this.ConnectionContextInfo = new MAPIString(Encoding.Unicode); this.ConnectionContextInfo.Parse(s); } }
public static bool IsSet(this ConnectionFlags flags, ConnectionFlags flag) { return (flags & flag) != 0; }
public static extern int WNetAddConnection3(IntPtr owner, NetResource netResource, string password, string userName, ConnectionFlags flags);