예제 #1
0
        private async Task SoftCloseAsync()
        {
            if (this.isDisposed || this.State == XmppTransportState.Closed || this.State == XmppTransportState.Closing)
            {
                return;
            }

            try
            {
                this.State = XmppTransportState.Closing;

                // Send the XMPP stream close tag
                await this.CloseStreamAsync().ConfigureAwait(false);

#warning TODO: Wait until the server sends the stream close tag

                // Close the underlying transport
                this.CloseTransport();
            }
            catch
            {
            }
            finally
            {
                this.transport      = null;
                this.saslMechanism  = null;
                this.serverFeatures = ServerFeatures.None;
                this.State          = XmppTransportState.Closed;
            }
        }
예제 #2
0
        public override ServerFeatures[] GetValue()
        {
            var result = default(ServerFeatures[]);

            if (Success && Data.Length > 0)
            {
                try
                {
                    var buffer = Data.Span.Slice(Header.BodyOffset);
                    result = new ServerFeatures[Header.BodyLength / 2];

                    for (int i = 0; i < result.Length; i++)
                    {
                        result[i] = (ServerFeatures)ByteConverter.ToInt16(buffer);

                        buffer = buffer.Slice(2);
                        if (buffer.Length <= 0)
                        {
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    Exception = e;
                    HandleClientError(e.Message, ResponseStatus.ClientFailure);
                }
            }
            return(result);
        }
예제 #3
0
        /// <summary>
        /// Disposes the specified disposing.
        /// </summary>
        /// <param name="disposing">if set to <c>true</c> [disposing].</param>
        private void Dispose(bool disposing)
        {
            if (!this.isDisposed)
            {
                if (disposing)
                {
                    // Release managed resources here
                    this.CloseAsync().GetAwaiter().GetResult();
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                // If disposing is false,
                // only the following code is executed.
                this.connectionString   = null;
                this.userAddress        = null;
                this.saslMechanism      = null;
                this.people             = null;
                this.activity           = null;
                this.capabilities       = null;
                this.personalEventing   = null;
                this.presence           = null;
                this.serverCapabilities = null;
                this.serverFeatures     = ServerFeatures.None;
                this.state = XmppTransportState.Closed;
                this.CloseTransport();
                this.DisposeSubscriptions();
                this.ReleaseSubjects();
            }

            this.isDisposed = true;
        }
예제 #4
0
        public static byte[] MyFeatures(AresClient client)
        {
            TCPPacketWriter packet = new TCPPacketWriter();

            packet.WriteString(client, Settings.VERSION + " - " + Settings.RELEASE_URL);

            ServerFeatures flag = (ServerFeatures.SERVER_SUPPORTS_PVT |
                                   ServerFeatures.SERVER_SUPPORTS_SHARING |
                                   ServerFeatures.SERVER_SUPPORTS_COMPRESSION |
                                   ServerFeatures.SERVER_SUPPORTS_VC |
                                   ServerFeatures.SERVER_SUPPORTS_OPUS_VC |
                                   ServerFeatures.SERVER_SUPPORTS_PM_SCRIBBLES);

            if (client.SupportsHTML)
            {
                flag |= ServerFeatures.SERVER_SUPPORTS_HTML;
            }

            if (Settings.Get <bool>("can_room_scribble"))
            {
                flag |= ServerFeatures.SERVER_SUPPORTS_ROOM_SCRIBBLES;
            }

            packet.WriteByte((byte)flag);
            packet.WriteByte(63);
            packet.WriteByte(Settings.Get <byte>("language"));
            packet.WriteUInt32(client.Cookie);
            packet.WriteByte(1);
            return(packet.ToAresPacket(TCPMsg.MSG_CHAT_SERVER_MYFEATURES));
        }
예제 #5
0
 public RequiresFeatureFactAttribute(ServerFeatures features)
 {
     if (!AppConfig.SupportedFeatures.HasFlag(features))
     {
         Skip = "Doesn't support " + features;
     }
 }
예제 #6
0
파일: Config.cs 프로젝트: hollow87/Zorbo
        public ServerFeatures GetFeatures()
        {
            ServerFeatures ret = ServerFeatures.NONE;

            if (AllowPrivate)
            {
                ret |= ServerFeatures.PRIVATE;
            }
            if (AllowSharing)
            {
                ret |= ServerFeatures.SHARING;
            }
            if (AllowCompression)
            {
                ret |= ServerFeatures.COMPRESSION;
            }
            if (AllowVoice)
            {
                ret |= ServerFeatures.VOICE;
            }
            if (AllowOpusVoice)
            {
                ret |= ServerFeatures.OPUS_VOICE;
            }
            if (AllowHtml)
            {
                ret |= ServerFeatures.HTML;
            }

            return(ret);
        }
예제 #7
0
 public RequiresFeatureFactAttribute(ServerFeatures features)
 {
     if ((AppConfig.SupportedFeatures & features) != features)
     {
         Skip = "Doesn't support " + features;
     }
 }
예제 #8
0
        public override ServerFeatures[] GetValue()
        {
            var result = default(ServerFeatures[]);

            if (Success && Data.Length > 0)
            {
                try
                {
                    var buffer = Data.Span.Slice(Header.BodyOffset);
                    result = new ServerFeatures[Header.BodyLength / 2];

                    // Other than some range checking, this is basically a straight memcpy, very fast
                    MemoryMarshal.Cast <byte, ServerFeatures>(buffer).CopyTo(result);

                    if (BitConverter.IsLittleEndian) // If statement is optimized out during JIT compilation
                    {
                        // The ServerFeature values are sent to us big endian, we need to reverse
                        for (var i = 0; i < result.Length; i++)
                        {
                            result[i] = (ServerFeatures)BinaryPrimitives.ReverseEndianness((ushort)result[i]);
                        }
                    }
                }
                catch (Exception e)
                {
                    Exception = e;
                    HandleClientError(e.Message, ResponseStatus.ClientFailure);
                }
            }
            return(result);
        }
예제 #9
0
        /// <summary>
        /// Closes the connection.
        /// </summary>
        /// <returns></returns>
        public async Task CloseAsync()
        {
            if (this.isDisposed || this.State == XmppTransportState.Closed || this.State == XmppTransportState.Closing)
            {
                return;
            }

            try
            {
                await SoftCloseAsync().ConfigureAwait(false);
            }
            catch
            {
            }
            finally
            {
                this.DisposeSubscriptions();

                this.transport          = null;
                this.saslMechanism      = null;
                this.connectionString   = null;
                this.userAddress        = null;
                this.people             = null;
                this.activity           = null;
                this.capabilities       = null;
                this.personalEventing   = null;
                this.presence           = null;
                this.serverCapabilities = null;
                this.serverFeatures     = ServerFeatures.None;

                this.ReleaseSubjects();
            }
        }
예제 #10
0
		public static string GetSkipReason(ServerFeatures serverFeatures, ConfigSettings configSettings)
		{
			if (!AppConfig.SupportedFeatures.HasFlag(serverFeatures))
				return $"Requires ServerFeatures.{serverFeatures}";

			if (configSettings == ConfigSettings.None)
				return null;

			var csb = AppConfig.CreateConnectionStringBuilder();
			if (configSettings.HasFlag(ConfigSettings.RequiresSsl) && (csb.SslMode == MySqlSslMode.None
#if !BASELINE
			 || csb.SslMode == MySqlSslMode.Preferred
#endif
			 ))
				return "Requires SslMode=Required or higher in connection string";

			if (configSettings.HasFlag(ConfigSettings.TrustedHost) &&
				(csb.SslMode == MySqlSslMode.None ||
#if !BASELINE
				csb.SslMode == MySqlSslMode.Preferred ||
#endif
				csb.SslMode == MySqlSslMode.Required))
			{
				return "Requires SslMode=VerifyCA or higher in connection string";
			}

			if (configSettings.HasFlag(ConfigSettings.UntrustedHost) &&
				(csb.SslMode == MySqlSslMode.VerifyCA || csb.SslMode == MySqlSslMode.VerifyFull))
			{
				return "Requires SslMode=Required or lower in connection string";
			}

			if (configSettings.HasFlag(ConfigSettings.KnownClientCertificate) && !(csb.CertificateFile?.EndsWith("ssl-client.pfx", StringComparison.OrdinalIgnoreCase) ?? false))
				return "Requires CertificateFile=client.pfx in connection string";

			if (configSettings.HasFlag(ConfigSettings.PasswordlessUser) && string.IsNullOrWhiteSpace(AppConfig.PasswordlessUser))
				return "Requires PasswordlessUser in config.json";

			if (configSettings.HasFlag(ConfigSettings.CsvFile) && string.IsNullOrWhiteSpace(AppConfig.MySqlBulkLoaderCsvFile))
				return "Requires MySqlBulkLoaderCsvFile in config.json";

			if (configSettings.HasFlag(ConfigSettings.LocalCsvFile) && string.IsNullOrWhiteSpace(AppConfig.MySqlBulkLoaderLocalCsvFile))
				return "Requires MySqlBulkLoaderLocalCsvFile in config.json";

			if (configSettings.HasFlag(ConfigSettings.TsvFile) && string.IsNullOrWhiteSpace(AppConfig.MySqlBulkLoaderTsvFile))
				return "Requires MySqlBulkLoaderTsvFile in config.json";

			if (configSettings.HasFlag(ConfigSettings.LocalTsvFile) && string.IsNullOrWhiteSpace(AppConfig.MySqlBulkLoaderLocalTsvFile))
				return "Requires MySqlBulkLoaderLocalTsvFile in config.json";

			if (configSettings.HasFlag(ConfigSettings.TcpConnection) && (csb.Server.StartsWith("/", StringComparison.Ordinal) || csb.Server.StartsWith("./", StringComparison.Ordinal)))
				return "Requires a TCP connection";

			if (configSettings.HasFlag(ConfigSettings.SecondaryDatabase) && string.IsNullOrEmpty(AppConfig.SecondaryDatabase))
				return "Requires SecondaryDatabase in config.json";

			return null;
		}
예제 #11
0
        private async Task OnBindedResourceAsync(InfoQuery iq)
        {
            // Update user ID
            this.userAddress = iq.Bind.Jid;

            // Update negotiated features
            this.serverFeatures = this.serverFeatures & (~ServerFeatures.ResourceBinding);

            // Continue feature negotiation
            await this.NegotiateStreamFeaturesAsync().ConfigureAwait(false);
        }
예제 #12
0
파일: Plugin.cs 프로젝트: hollow87/Zorbo
        public ServerFeatures OnSendFeatures(IClient client, ServerFeatures features)
        {
            if ((features & ServerFeatures.ROOM_SCRIBBLES) != ServerFeatures.ROOM_SCRIBBLES)
            {
                features |= ServerFeatures.ROOM_SCRIBBLES;
            }

            if ((features & ServerFeatures.PRIVATE_SCRIBBLES) != ServerFeatures.PRIVATE_SCRIBBLES)
            {
                features |= ServerFeatures.PRIVATE_SCRIBBLES;
            }

            return(features);
        }
예제 #13
0
 public ServerFeatures OnSendFeatures(IClient client, ServerFeatures features)
 {
     lock (plugins) {
         foreach (var plugin in plugins)
         {
             try {
                 if (plugin.Enabled)
                 {
                     features |= plugin.Plugin.OnSendFeatures(client, features);
                 }
             }
             catch (Exception ex) {
                 OnError(plugin, "OnSendFeatures", ex);
             }
         }
     }
     return(features);
 }
예제 #14
0
        private Features MapFeatures(int value)
        {
            var features = new ServerFeatures(value);

            if (features.IsSecureCore())
            {
                return(Features.SecureCore);
            }
            if (features.SupportsTor())
            {
                return(Features.Tor);
            }
            if (features.SupportsP2P())
            {
                return(Features.P2P);
            }

            return(Features.None);
        }
예제 #15
0
        private async Task OnRequestSessionAsync()
        {
            if (!this.Supports(ServerFeatures.Sessions))
            {
                return;
            }

            var iq = new InfoQuery
            {
                Type      = InfoQueryType.Set
                , Session = new Session()
            };

            await this.SendAsync(iq).ConfigureAwait(false);

            // Update negotiated features
            this.serverFeatures = this.serverFeatures & (~ServerFeatures.Sessions);

            // Continue feature negotiation
            await this.NegotiateStreamFeaturesAsync().ConfigureAwait(false);
        }
예제 #16
0
        private async Task OnNegotiateStreamFeaturesAsync(StreamFeatures features)
        {
            this.serverFeatures = ServerFeatures.None;

            if (features.SecureConnectionRequired)
            {
                this.serverFeatures |= ServerFeatures.SecureConnection;
            }

            if (features.HasAuthMechanisms)
            {
                this.serverFeatures |= this.DiscoverAuthMechanisms(features);
            }

            if (features.SupportsResourceBinding)
            {
                this.serverFeatures |= ServerFeatures.ResourceBinding;
            }

            if (features.SupportsSessions)
            {
                this.serverFeatures |= ServerFeatures.Sessions;
            }

            if (features.SupportsInBandRegistration)
            {
                this.serverFeatures |= ServerFeatures.InBandRegistration;
            }

            if (features.SupportsEntityCapabilities)
            {
                this.serverFeatures |= ServerFeatures.EntityCapabilities;

                this.serverCapabilities.Address = this.UserAddress.DomainName;
                this.serverCapabilities.ServiceDiscoveryNode = features.EntityCapabilities.DiscoveryNode;
            }

            await this.NegotiateStreamFeaturesAsync().ConfigureAwait(false);
        }
예제 #17
0
 public static bool SupportsIpV6(this Server server) => ServerFeatures.SupportsIpV6(server.Features);
예제 #18
0
 /// <summary>
 /// Creates a <see cref="NotSupportedException"/> with message that says that <paramref name="feature"/>
 /// is not supported by current storage.
 /// </summary>
 /// <param name="feature">The feature.</param>
 /// <returns>Created exception.</returns>
 public static NotSupportedException NotSupported(ServerFeatures feature)
 {
     return(NotSupported(feature.ToString()));
 }
예제 #19
0
 public override bool IsSatisfiedBy(LogicalServerContract item)
 {
     return(ServerFeatures.IsSecureCore(item.Features));
 }
예제 #20
0
        private void OpenFile(string fileName)
        {
            Clear();

            txtINIFile.Text = fileName;

            UOXData.Script.UOXIni iniFile = new UOXData.Script.UOXIni(fileName);

            foreach (UOXData.Script.ScriptSection mSect in iniFile.Sections)
            {
                if (mSect.SectionName == "play server list")
                {
                    foreach (UOXData.Script.TagDataPair sRow in mSect.TagDataPairs)
                    {
                        dataGridServers.Rows.Add(sRow.Data.ToString().Split(",".ToCharArray()));
                    }
                }
                else if (mSect.SectionName == "start locations")
                {
                    foreach (UOXData.Script.TagDataPair lRow in mSect.TagDataPairs)
                    {
                        dataGridLocations.Rows.Add(lRow.Data.ToString().Split(",".ToCharArray()));
                    }
                }
                else if (mSect.SectionName == "directories")
                {
                    for (UOXData.Script.UOXIni.DirectoryPaths dPath = UOXData.Script.UOXIni.DirectoryPaths.Root; dPath != UOXData.Script.UOXIni.DirectoryPaths.COUNT; ++dPath)
                    {
                        dataGridDirectories.Rows.Add(dPath.ToString(), iniFile.Directory(dPath));
                    }
                }
                else
                {
                    foreach (UOXData.Script.TagDataPair mPair in mSect.TagDataPairs)
                    {
                        try
                        {
                            ControlData mControl = iniControls[mPair.Tag.ToString()];
                            Control     ctrl     = Controls.Find(mControl.CtrlName, true)[0];
                            if (ctrl.GetType() == typeof(CheckBox))
                            {
                                ((CheckBox)ctrl).Checked = (mPair.Data.ToInt08() == 1);
                            }
                            else if (ctrl.GetType() == typeof(ComboBox))
                            {
                                int aSound = mPair.Data.ToInt08();
                                if (aSound < ((ComboBox)ctrl).Items.Count)
                                {
                                    ((ComboBox)ctrl).SelectedIndex = aSound;
                                }
                            }
                            else if (ctrl.GetType() == typeof(DataGridView))
                            {
                                ((DataGridView)ctrl).Rows.Add(mControl.CtrlDesc, mPair.Data.ToString());
                            }
                            else if (ctrl.GetType() == typeof(MaskedTextBox))
                            {
                                ((MaskedTextBox)ctrl).Text = mPair.Data.ToString();
                            }
                            else if (ctrl.GetType() == typeof(RadioButton))
                            {
                                ((RadioButton)ctrl).Checked = (mPair.Data.ToInt08() == 1);
                            }
                            else if (ctrl.GetType() == typeof(TextBox))
                            {
                                ((TextBox)ctrl).Text = mPair.Data.ToString();
                            }
                        }
                        catch (KeyNotFoundException)
                        {
                            switch (mPair.Tag.ToString())
                            {
                            case "BACKGROUNDPIC":
                                mtxtGumpBackground.Text = mPair.Data.ToString();
                                break;

                            case "BUTTONCANCEL":
                                gumpButtons[0] = mPair.Data.ToUInt16();
                                break;

                            case "BUTTONLEFT":
                                gumpButtons[1] = mPair.Data.ToUInt16();
                                break;

                            case "BUTTONRIGHT":
                                gumpButtons[2] = mPair.Data.ToUInt16();
                                break;

                            case "CLIENTFEATURES":
                                BitVector32 sCFeat = new BitVector32(mPair.Data.ToUInt16());
                                int         cmask  = BitVector32.CreateMask();
                                for (ClientFeatures cEnum = ClientFeatures.Chat_Button; cEnum < ClientFeatures.COUNT; ++cEnum)
                                {
                                    dataGridClientFeatures.Rows.Add(cEnum.ToString().Replace("_", " "), sCFeat[cmask]);
                                    cmask = BitVector32.CreateMask(cmask);
                                    if (cEnum.ToString().Contains("UNKNOWN"))
                                    {
                                        dataGridClientFeatures.Rows[dataGridClientFeatures.Rows.Count - 1].Visible = false;
                                    }
                                }
                                break;

                            case "LEFTTEXTCOLOUR":
                                gumpText[1] = mPair.Data.ToUInt16();
                                break;

                            case "RIGHTTEXTCOLOUR":
                                gumpText[2] = mPair.Data.ToUInt16();
                                break;

                            case "SERVERFEATURES":
                                BitVector32 sSFeat = new BitVector32(mPair.Data.ToInt32());
                                int         smask  = BitVector32.CreateMask();
                                for (ServerFeatures sEnum = ServerFeatures.UNKNOWN1; sEnum < ServerFeatures.COUNT; ++sEnum)
                                {
                                    dataGridServerFeatures.Rows.Add(sEnum.ToString().Replace("_", " "), sSFeat[smask]);
                                    smask = BitVector32.CreateMask(smask);
                                    if (sEnum.ToString().Contains("UNKNOWN"))
                                    {
                                        dataGridServerFeatures.Rows[dataGridServerFeatures.Rows.Count - 1].Visible = false;
                                    }
                                }
                                break;

                            case "STARTGOLD":
                                mtxtStartGold.Text = mPair.Data.ToString();
                                break;

                            case "STARTPRIVS":
                                BitVector32 sPriv = new BitVector32(mPair.Data.ToUInt16());
                                int         pmask = BitVector32.CreateMask();
                                for (StartPrivs pEnum = StartPrivs.GM; pEnum < StartPrivs.COUNT; ++pEnum)
                                {
                                    dataGridPrivs.Rows.Add(pEnum.ToString().Replace("_", " "), sPriv[pmask]);
                                    pmask = BitVector32.CreateMask(pmask);
                                }
                                break;

                            case "TITLECOLOUR":
                                gumpText[0] = mPair.Data.ToUInt16();
                                break;

                            default:
                                dataGridUncategorized.Rows.Add(mPair.Tag.ToString(), mPair.Data.ToString());
                                break;
                            }
                        }
                    }
                }
            }
            comboGumpText.SelectedIndex    = 0;
            comboGumpButtons.SelectedIndex = 0;

            Text = title + " - " + Path.GetFileName(txtINIFile.Text);
        }
 /// <summary>
 /// Determines whether the specified active features is supported.
 /// </summary>
 public static bool Supports(this ServerFeatures available, ServerFeatures required)
 {
     return((available & required) == required);
 }
예제 #22
0
        private void Eval_Features(TCPPacketReader packet)
        {
            String version = packet.ReadString(this.crypto);

            this.Credentials.Server = version;
            this.Panel.ServerText(StringTemplate.Get(STType.Messages, 17) + ": " + version);
            this.Panel.Userlist.UpdateServerVersion(version);
            this.should_check_for_current_topic_update = true;

            if (version.StartsWith("sb0t 5."))
            {
                version = version.Substring(version.IndexOf(" ") + 1).Split(' ')[0];
                String vnum_str = new String(version.Where(x => Char.IsNumber(x)).ToArray());

                uint vnum;

                if (!uint.TryParse(vnum_str, out vnum))
                {
                    vnum = 0;
                }

                this.new_sbot = (vnum >= 514);
            }
            else if (version.StartsWith("Ares 2.") || version.StartsWith("Ares_2."))
            {
                this.new_sbot = true; // maybe future Ares Server will support cb0t Custom Fonts?
            }
            ServerFeatures flag = (ServerFeatures)((byte)packet);

            this.CanVC = ((flag & ServerFeatures.SERVER_SUPPORTS_VC) == ServerFeatures.SERVER_SUPPORTS_VC);
            bool has_html        = ((flag & ServerFeatures.SERVER_SUPPORTS_HTML) == ServerFeatures.SERVER_SUPPORTS_HTML);
            bool has_scribble    = ((flag & ServerFeatures.SERVER_SUPPORTS_ROOM_SCRIBBLES) == ServerFeatures.SERVER_SUPPORTS_ROOM_SCRIBBLES);
            bool has_pm_scribble = ((flag & ServerFeatures.SERVER_SUPPORTS_PM_SCRIBBLES) == ServerFeatures.SERVER_SUPPORTS_PM_SCRIBBLES);

            this.CanOpusVC = ((flag & ServerFeatures.SERVER_SUPPORTS_OPUS_VC) == ServerFeatures.SERVER_SUPPORTS_OPUS_VC);
            this.Panel.CanVC(this.CanVC);
            this.Panel.CanScribbleAll(has_scribble);
            this.Panel.CanScribblePM(has_pm_scribble);
            this.Panel.InitScribbleButton();
            this.CanNP = true;

            if (has_html)
            {
                this.Panel.Userlist.AcquireServerIcon(this.EndPoint);
            }

            packet.SkipByte();
            this.Panel.ServerText(StringTemplate.Get(STType.Messages, 16) + ": " + (RoomLanguage)((byte)packet));
            uint cookie = packet;

            if (!String.IsNullOrEmpty(this.Credentials.Password))
            {
                this.sock.Send(TCPOutbound.SecureAdminLogin(this.Credentials.Password, cookie, this.Credentials.IP));
            }

            this.UpdatePersonalMessage();

            if (Avatar.Data != null)
            {
                this.sock.SendTrickle(TCPOutbound.Avatar());
            }

            if (Settings.GetReg <bool>("user_font_enabled", false))
            {
                this.sock.SendTrickle(TCPOutbound.Font(this.new_sbot, this.crypto));
            }

            if (Settings.GetReg <bool>("block_custom_names", false))
            {
                this.sock.SendTrickle(TCPOutbound.BlockCustomNames(true));
            }

            ScriptEvents.OnConnected(this);
        }
예제 #23
0
 public SkippableFactAttribute(ServerFeatures serverFeatures, ConfigSettings configSettings)
 {
     Skip = TestUtilities.GetSkipReason(serverFeatures, configSettings);
 }
예제 #24
0
 public SkippableFactAttribute(ServerFeatures serverFeatures)
     : this(serverFeatures, ConfigSettings.None)
 {
 }
예제 #25
0
 public ServerFeatures OnSendFeatures(IClient client, ServerFeatures features)
 {
     return(features);
 }
예제 #26
0
 public override bool IsSatisfiedBy(LogicalServerContract item)
 {
     return(ServerFeatures.SupportsP2P(item.Features));
 }
예제 #27
0
 public static bool IsSecureCore(this Server server) => ServerFeatures.IsSecureCore(server.Features);
예제 #28
0
        public override async Task <int> ExecuteAsync(CommandContext context, Settings settings)
        {
            var webHost = default(IWebHost);

            using var cancellationTokenSource = new CancellationTokenSource();

            Logger.LogInformation(
                "Generating self-signed certificate for HTTPS"
                );

            using var cert = CertificateManager.Create();

            await Console.Status()
            .Spinner(Spinner.Known.Earth)
            .StartAsync(
                "Starting AirDrop services...",
                async _ =>
            {
                webHost = WebHost.CreateDefaultBuilder()
                          .ConfigureLogging(
                    (hostContext, builder) =>
                {
                    builder.ClearProviders();
                    builder.AddConfiguration(hostContext.Configuration.GetSection("Logging"));
                    builder.AddProvider(new SpectreInlineLoggerProvider(Console));
                }
                    )
                          .ConfigureKestrel(
                    options => options.ConfigureAirDropDefaults(cert)
                    )
                          .ConfigureServices(
                    (hostContext, services) =>
                {
                    var uploadPath = Path.Join(
                        hostContext.HostingEnvironment.ContentRootPath,
                        "uploads"
                        );

                    Directory.CreateDirectory(uploadPath);

                    services.Configure <StaticFileOptions>(options =>
                    {
                        options.FileProvider = new CompositeFileProvider(
                            new IFileProvider[]
                        {
                            // provides access to the files embedded in the assembly
                            new ManifestEmbeddedFileProvider(
                                typeof(ServerCommand).Assembly, "wwwroot"
                                ),
                            // provides access to uploaded files
                            new PhysicalFileProvider(uploadPath)
                        }
                            );

                        // we don't know what files could be uploaded using AirDrop
                        // so enable everything by default
                        options.ServeUnknownFileTypes = true;
                    }
                                                           );
                    services.AddAirDrop(
                        options =>
                    {
                        options.ListenPort = settings.Port;
                        options.UploadPath = uploadPath;
                    }
                        );
                    services.AddRouting();
                    services
                    .AddSignalR(
                        options =>
                    {
                        options.EnableDetailedErrors = true;
                    }
                        )
                    .AddJsonProtocol(
                        options =>
                    {
                        options.PayloadSerializerOptions = new JsonSerializerOptions
                        {
                            Converters =
                            {
                                PolymorphicJsonConverter.Create(typeof(AirDropHubMessage))
                            }
                        };
                    }
                        );
                }
                    )
                          .Configure(
                    app =>
                {
                    app
                    .UseRouting()
                    .UseStaticFiles()
                    .UseEndpoints(
                        endpoints =>
                    {
                        endpoints.MapAirDrop();
                        endpoints.MapHub <AirDropHub>("/airdrop");
                        endpoints.MapFallbackToFile("index.html");
                    }
                        );
                }
                    )
                          .SuppressStatusMessages(true)
                          .Build();

                await webHost.StartAsync(cancellationTokenSource.Token);
            }
                );

            var feature = webHost !.ServerFeatures.Get <IServerAddressesFeature>();

            if (feature != null)
            {
                foreach (var address in feature.Addresses)
                {
                    Logger.LogInformation("Listening on {Url}", address);
                }
            }

            Logger.LogInformation("Waiting for AirDrop clients...");

            // ReSharper disable AccessToDisposedClosure
            void Shutdown()
            {
                if (!cancellationTokenSource.IsCancellationRequested)
                {
                    Logger.LogInformation("Shutting down AirDrop services...");
                    cancellationTokenSource.Cancel();
                }
            }

            AppDomain.CurrentDomain.ProcessExit += (_, _) => Shutdown();
            System.Console.CancelKeyPress       += (_, _) => Shutdown();
            await webHost.WaitForShutdownAsync(cancellationTokenSource.Token);

            return(0);
        }
예제 #29
0
 public bool Supports(ServerFeatures feature)
 {
     return(ServerFeatures.Contains((short)feature));
 }
예제 #30
0
        public static string GetSkipReason(ServerFeatures serverFeatures, ConfigSettings configSettings)
        {
            if (!AppConfig.SupportedFeatures.HasFlag(serverFeatures))
            {
                return($"Requires ServerFeatures.{serverFeatures}");
            }

            if (configSettings == ConfigSettings.None)
            {
                return(null);
            }

            var csb = AppConfig.CreateConnectionStringBuilder();

            if (configSettings.HasFlag(ConfigSettings.RequiresSsl) && (csb.SslMode == MySqlSslMode.None || csb.SslMode == MySqlSslMode.Preferred))
            {
                return("Requires SslMode=Required or higher in connection string");
            }

            if (configSettings.HasFlag(ConfigSettings.TrustedHost) &&
                (csb.SslMode == MySqlSslMode.None || csb.SslMode == MySqlSslMode.Preferred || csb.SslMode == MySqlSslMode.Required))
            {
                return("Requires SslMode=VerifyCA or higher in connection string");
            }

            if (configSettings.HasFlag(ConfigSettings.UntrustedHost) &&
                (csb.SslMode == MySqlSslMode.VerifyCA || csb.SslMode == MySqlSslMode.VerifyFull))
            {
                return("Requires SslMode=Required or lower in connection string");
            }

            if (configSettings.HasFlag(ConfigSettings.PasswordlessUser) && string.IsNullOrWhiteSpace(AppConfig.PasswordlessUser))
            {
                return("Requires PasswordlessUser in config.json");
            }

            if (configSettings.HasFlag(ConfigSettings.CsvFile) && string.IsNullOrWhiteSpace(AppConfig.MySqlBulkLoaderCsvFile))
            {
                return("Requires MySqlBulkLoaderCsvFile in config.json");
            }

            if (configSettings.HasFlag(ConfigSettings.LocalCsvFile) && string.IsNullOrWhiteSpace(AppConfig.MySqlBulkLoaderLocalCsvFile))
            {
                return("Requires MySqlBulkLoaderLocalCsvFile in config.json");
            }

            if (configSettings.HasFlag(ConfigSettings.TsvFile) && string.IsNullOrWhiteSpace(AppConfig.MySqlBulkLoaderTsvFile))
            {
                return("Requires MySqlBulkLoaderTsvFile in config.json");
            }

            if (configSettings.HasFlag(ConfigSettings.LocalTsvFile) && string.IsNullOrWhiteSpace(AppConfig.MySqlBulkLoaderLocalTsvFile))
            {
                return("Requires MySqlBulkLoaderLocalTsvFile in config.json");
            }

            if (configSettings.HasFlag(ConfigSettings.TcpConnection) && (csb.Server.StartsWith("/", StringComparison.Ordinal) || csb.Server.StartsWith("./", StringComparison.Ordinal)))
            {
                return("Requires a TCP connection");
            }

            if (configSettings.HasFlag(ConfigSettings.SecondaryDatabase) && string.IsNullOrEmpty(AppConfig.SecondaryDatabase))
            {
                return("Requires SecondaryDatabase in config.json");
            }

            return(null);
        }