Beispiel #1
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            config = builder.Build();

            var server = new IrcServer()
            {
                Name             = "Server",
                Hostname         = config.GetConnectionString("Hostname"),
                Port             = Convert.ToInt32(config.GetConnectionString("Port")),
                Ssl              = config.GetConnectionString("SSL") == "True",
                IgnoreCertErrors = true,
                Username         = config.GetConnectionString("Username"),
                Channels         = config.GetConnectionString("Channels")
            };

            _socket = new IrcSocket(server);
            _socket.Initialise();

            _socket.Connect();

            _socket.ChannelList.CollectionChanged += (s, e) =>
            {
                new ChannelHandler(config, _socket, (e.NewItems[0] as Channel)?.Name).Init();
            };
            var mre = new ManualResetEvent(false);

            _socket.HandleDisconnect += irc => { mre.Set(); };

            // The main thread can just wait on the wait handle, which basically puts it into a "sleep" state, and blocks it forever
            mre.WaitOne();
        }
        public void Initialize()
        {
            IrcServer = new IrcServer<IrcServerTabItem>(this);
            IrcServer.Connected += IrcServer_Connected;
            IrcServer.ConnectFailed += IrcServer_ConnectFailed;
            IrcServer.Disconnected += IrcServer_Disconnected;

            IrcServer.Connect(Data.ServerAddress, Data.ServerPort);
        }
Beispiel #3
0
        internal IrcServer CreateIrcServer()
        {
            IrcServer ircServer = new IrcServer();

            if (hostname.Text == "")
            {
                return(ShowFormError("No hostname entered!"));
            }

            if (Uri.CheckHostName(hostname.Text) == UriHostNameType.Unknown)
            {
                return(ShowFormError("Hostname is incorrect!"));
            }

            int portInt;

            if (port.Text == "")
            {
                return(ShowFormError("No port entered!"));
            }

            if (!int.TryParse(port.Text, out portInt))
            {
                return(ShowFormError("Port is not a number!"));
            }

            if (username.Text == "")
            {
                return(ShowFormError("No username entered!"));
            }

            if (username.Text.Contains(" "))
            {
                return(ShowFormError("Usernames cannot contain spaces!"));
            }

            ircServer.hostname         = hostname.Text;
            ircServer.port             = portInt;
            ircServer.ssl              = ssl.IsOn;
            ircServer.username         = username.Text;
            ircServer.password         = password.Password;
            ircServer.nickservPassword = nickservPassword.Password;
            ircServer.name             = server.Text;
            ircServer.webSocket        = webSocket.IsOn;
            ircServer.channels         = channels.Text;
            ircServer.invalid          = false;

            formError.Height = 0;

            if (ircServer.name == "")
            {
                ircServer.name = ircServer.hostname;
            }

            return(ircServer);
        }
Beispiel #4
0
        private void JoinSupport(object sender, RoutedEventArgs e)
        {
            IrcServer server = new IrcServer
            {
                name     = "WinIRC Support (Freenode)",
                hostname = "chat.freenode.net",
                port     = 6697,
                ssl      = true,
                channels = "#winirc"
            };

            MainPage.instance.IrcPrompt(server);
        }
Beispiel #5
0
 public IrcClient(TcpClient client,
                  SoraDbContext ctx,
                  IServerConfig cfg,
                  PresenceService ps,
                  ChannelService cs,
                  EventManager evmng,
                  IrcServer parent)
 {
     _client = client;
     _ctx    = ctx;
     _cfg    = cfg;
     _ps     = ps;
     _parent = parent;
     _cs     = cs;
     _evmng  = evmng;
 }
Beispiel #6
0
        public async void IrcPrompt(IrcServer server)
        {
            var dialog = new ContentDialog()
            {
                Title          = "Join " + server.hostname,
                RequestedTheme = ElementTheme.Dark,
                //FullSizeDesired = true,
                MaxWidth = this.ActualWidth // Required for Mobile!
            };

            // Setup Content
            var panel = new StackPanel();

            panel.Children.Add(new TextBlock
            {
                Text         = "To connect to this irc server, enter in a username first.",
                TextWrapping = TextWrapping.Wrap,
                Padding      = new Thickness
                {
                    Bottom = 8,
                },
            });

            var username = new TextBox
            {
                PlaceholderText = "Username",
                Text            = "winircuser-" + (new Random()).Next(100, 1000)
            };

            panel.Children.Add(username);
            dialog.Content = panel;

            // Add Buttons
            dialog.PrimaryButtonText   = "Join";
            dialog.PrimaryButtonClick += delegate
            {
                server.username = username.Text;

                var irc = new Net.IrcSocket();
                irc.server = server;
                MainPage.instance.Connect(irc);
            };

            dialog.SecondaryButtonText = "Cancel";
            dialog.ShowAsync();
        }
        public static void Main(string[] args)
        {
            Console.Title = "IrcServer Tests";
            Framework.Initialize();

            IrcServer server = new IrcServer();

            server.Host       = "ares.cncfps.com";
            server.ServerName = "atlantis.unifiedtech.org";
            server.Port       = new PortInfo(8067);
            server.Password   = "******";

            server.IsBackgroundThread = true;
            server.StartAsync();

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
            server.Stop();
        }
Beispiel #8
0
        protected override void OnActivated(IActivatedEventArgs e)
        {
            // Get the root frame
            Frame rootFrame = Window.Current.Content as Frame;

            var loaded = true;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                this.SetTheme();

                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
                loaded = false;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(MainPage));

                // Ensure the current window is active
                Window.Current.Activate();
                loaded = false;
            }

            // Handle toast activation
            if (e.Kind == ActivationKind.ToastNotification && loaded)
            {
                var args = e as ToastNotificationActivatedEventArgs;
                var toastActivationArgs = args;

                // Parse the query string
                QueryString qryStr = QueryString.Parse(toastActivationArgs.Argument);

                if (!qryStr.Contains("action"))
                {
                    return;
                }

                var ircHandler = IrcUiHandler.Instance;
                if (ircHandler == null)
                {
                    return;
                }

                // See what action is being requested
                if (qryStr["action"] == "reply")
                {
                    string channel  = qryStr["channel"];
                    string server   = qryStr["server"];
                    string username = qryStr["username"];

                    var message = args.UserInput["tbReply"];

                    var mainPage = (MainPage)rootFrame.Content;

                    if (!ircHandler.connectedServersList.Contains(server))
                    {
                        return;
                    }

                    if (mainPage != null)
                    {
                        mainPage.MentionReply(server, channel, username + ": " + message);
                    }

                    if (!mainPage.currentChannel.Equals(channel))
                    {
                        mainPage.SwitchChannel(server, channel, false);
                    }
                }
                else if (qryStr["action"] == "viewConversation")
                {
                    // The conversation ID retrieved from the toast args
                    string channel = qryStr["channel"];
                    string server  = qryStr["server"];

                    var mainPage = (MainPage)rootFrame.Content;

                    if (mainPage == null)
                    {
                        return;
                    }

                    if (!ircHandler.connectedServersList.Contains(server))
                    {
                        return;
                    }

                    // If we're already viewing that channel, do nothing
                    if (!mainPage.currentChannel.Equals(channel))
                    {
                        mainPage.SwitchChannel(server, channel, false);
                    }
                }

                // If we're loading the app for the first time, place the main page on
                // the back stack so that user can go back after they've been
                // navigated to the specific page
                if (rootFrame.BackStack.Count == 0)
                {
                    rootFrame.BackStack.Add(new PageStackEntry(typeof(MainPage), null, null));
                }
            }

            if (e.Kind == ActivationKind.Protocol)
            {
                ProtocolActivatedEventArgs eventArgs = e as ProtocolActivatedEventArgs;

                // TODO: Handle URI activation
                // The received URI is eventArgs.Uri.AbsoluteUri
                var uri  = eventArgs.Uri;
                var port = 0;

                if (uri.Port == 0)
                {
                    port = 6667;
                }
                else
                {
                    port = uri.Port;
                }

                IrcServer server = new IrcServer
                {
                    name     = uri.Host,
                    hostname = uri.Host,
                    port     = port,
                    ssl      = uri.Scheme == "ircs",
                };

                if (uri.Segments.Length >= 2)
                {
                    server.channels += "#" + uri.Segments[1];
                }

                MainPage.instance.IrcPrompt(server);
            }

            // Ensure the current window is active
            Window.Current.Activate();
        }
Beispiel #9
0
        /// <summary>
        /// The main program message loop
        /// </summary>
        /// <returns>An error code, indicating an error condition when the value returned is non-zero</returns>
        /// <exception cref="FormatException">Thrown when an attempt to construct a format string fails to properly format a finalized message</exception>
        /// <exception cref="IOException">Thrown when the process is unable to write status to the console window</exception>
        /// <exception cref="ArgumentNullException">Thrown when a 'null' value is attempted to be written to the console window</exception>
        /// <exception cref="ConfigurationErrorsException">Thrown when the configuration file for the process cannot be parsed</exception>
        /// <exception cref="SecurityException">Thrown when the X.509 certificate store cannot be opened or enumerated when constructing SSL ports</exception>
        public static int Main()
        {
            var version = Assembly.GetEntryAssembly().GetName().Version;

            Console.WriteLine("McNNTP Server Console Harness v{0}", version);

            try
            {
                // Setup LOG4NET
                XmlConfigurator.Configure();

                var logger = LogManager.GetLogger(typeof(Program));

                // Load configuration
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var mcnntpConfigurationSection = (McNNTPConfigurationSection)config.GetSection("mcnntp");
                logger.InfoFormat("Loaded configuration from {0}", config.FilePath);

                // Verify Database
                if (DatabaseUtility.VerifyDatabase())
                {
                    DatabaseUtility.UpdateSchema();
                }
                else if (DatabaseUtility.UpdateSchema() && !DatabaseUtility.VerifyDatabase(true))
                {
                    Console.WriteLine(
                        "Unable to verify a database.  Would you like to create and initialize a database?");
                    var resp = Console.ReadLine();
                    if (resp != null && new[] { "y", "yes" }.Contains(resp.ToLowerInvariant().Trim()))
                    {
                        DatabaseUtility.RebuildSchema();
                    }
                }

                _ircServer = new IrcServer
                {
                    SslGenerateSelfSignedServerCertificate =
                        mcnntpConfigurationSection.Ssl == null ||
                        mcnntpConfigurationSection.Ssl.GenerateSelfSignedServerCertificate,
                    SslServerCertificateThumbprint =
                        mcnntpConfigurationSection.Ssl == null
                            ? null
                            : mcnntpConfigurationSection.Ssl.ServerCertificateThumbprint
                };

                _ircServer.Start();

                _imapServer = new ImapServer
                {
                    AllowPosting   = true,
                    ImapClearPorts =
                        mcnntpConfigurationSection.Ports.Where(p => p.Ssl == "ClearText" && p.Protocol == "imap")
                        .Select(p => p.Port)
                        .ToArray(),
                    ImapExplicitTLSPorts =
                        mcnntpConfigurationSection.Ports.Where(p => p.Ssl == "ExplicitTLS" && p.Protocol == "imap")
                        .Select(p => p.Port)
                        .ToArray(),
                    ImapImplicitTLSPorts =
                        mcnntpConfigurationSection.Ports.Where(p => p.Ssl == "ImplicitTLS" && p.Protocol == "imap")
                        .Select(p => p.Port)
                        .ToArray(),
                    PathHost = mcnntpConfigurationSection.PathHost,
                    SslGenerateSelfSignedServerCertificate =
                        mcnntpConfigurationSection.Ssl == null ||
                        mcnntpConfigurationSection.Ssl.GenerateSelfSignedServerCertificate,
                    SslServerCertificateThumbprint =
                        mcnntpConfigurationSection.Ssl == null
                                             ? null
                                             : mcnntpConfigurationSection.Ssl.ServerCertificateThumbprint
                };

                _imapServer.Start();

                _nntpServer = new NntpServer
                {
                    AllowPosting  = true,
                    IrcClearPorts =
                        mcnntpConfigurationSection.Ports.Where(p => p.Ssl == "ClearText" && p.Protocol == "irc")
                        .Select(p => p.Port)
                        .ToArray(),
                    IrcImplicitTLSPorts =
                        mcnntpConfigurationSection.Ports.Where(p => p.Ssl == "ImplicitTLS" && p.Protocol == "irc")
                        .Select(p => p.Port)
                        .ToArray(),
                    NntpClearPorts =
                        mcnntpConfigurationSection.Ports.Where(p => p.Ssl == "ClearText" && p.Protocol == "nntp")
                        .Select(p => p.Port)
                        .ToArray(),
                    NntpExplicitTLSPorts =
                        mcnntpConfigurationSection.Ports.Where(p => p.Ssl == "ExplicitTLS" && p.Protocol == "nntp")
                        .Select(p => p.Port)
                        .ToArray(),
                    NntpImplicitTLSPorts =
                        mcnntpConfigurationSection.Ports.Where(p => p.Ssl == "ImplicitTLS" && p.Protocol == "nntp")
                        .Select(p => p.Port)
                        .ToArray(),
                    LdapDirectoryConfiguration =
                        mcnntpConfigurationSection.Authentication.UserDirectories
                        .OfType <LdapDirectoryConfigurationElement>()
                        .OrderBy(l => l.Priority)
                        .FirstOrDefault(),
                    PathHost = mcnntpConfigurationSection.PathHost,
                    SslGenerateSelfSignedServerCertificate =
                        mcnntpConfigurationSection.Ssl == null ||
                        mcnntpConfigurationSection.Ssl.GenerateSelfSignedServerCertificate,
                    SslServerCertificateThumbprint =
                        mcnntpConfigurationSection.Ssl == null
                                         ? null
                                         : mcnntpConfigurationSection.Ssl.ServerCertificateThumbprint
                };

                _nntpServer.Start();

                Console.WriteLine("Type QUIT and press Enter to end the server.");

                while (true)
                {
                    Console.Write("\r\n> ");
                    var input = Console.ReadLine();
                    if (input == null || !_CommandDirectory.ContainsKey(input.Split(' ')[0].ToUpperInvariant()))
                    {
                        Console.WriteLine("Unrecongized command.  Type HELP for a list of available commands.");
                        continue;
                    }

                    if (!_CommandDirectory[input.Split(' ')[0].ToUpperInvariant()].Invoke(input))
                    {
                        continue;
                    }

                    _imapServer.Stop();
                    _nntpServer.Stop();
                    return(0);
                }
            }
            catch (AggregateException ae)
            {
                foreach (var ex in ae.InnerExceptions)
                {
                    Console.WriteLine(ex.ToString());
                }
                Console.ReadLine();
                return(-2);
            }
            catch (SecurityException sex)
            {
                Console.WriteLine(sex.ToString());
                Console.ReadLine();
                return(-3);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
                return(-1);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Main loop for the CLI demo of the IrcClientCore
        /// </summary>
        private void Start()
        {
            IrcServer server = null;

            if (Prompt("Load Server?"))
            {
                var name = ReadLine.Read("Server Name: ");
                server = Serialize.DeserializeObject <IrcServer>(name);
            }

            if (server == null)
            {
                Console.WriteLine("Creating server...");
                server = new IrcServer()
                {
                    Name             = ReadLine.Read("Server Name: "),
                    Hostname         = ReadLine.Read("Server Hostname: "),
                    Port             = Convert.ToInt32(ReadLine.Read("Server Port: ", "6667")),
                    Ssl              = Prompt("Use SSL:"),
                    IgnoreCertErrors = true,
                    Username         = ReadLine.Read("Username: "******"Password: "******"Channels to join (format #channel,#other...): ")
                };

                if (Prompt("Save Server?"))
                {
                    Serialize.SerializeObject(server, server.Name);
                }
            }

            Console.WriteLine($"Connecting to {server.Hostname}");

            _socket = new Irc(server);
            _socket.Initialise();

            _socket.Connect();
            ((Buffer)_socket.InfoBuffer).Collection.CollectionChanged += ChannelBuffersOnCollectionChanged;

            var handler = _socket.CommandManager;

            handler.RegisterCommand("/switch", new SwitchCommand(this));
            handler.RegisterCommand("/reconnect", new ReconnectCommand());
            handler.RegisterCommand("/users", new UsersCommand());

            _autocompleteHandler = new AutocompleteHandler(handler);

            ReadLine.AutoCompletionHandler = _autocompleteHandler;

            SwitchChannel("");

            _socket.HandleDisplayChannelList = HandleChannelList;

            while (!_socket.ReadOrWriteFailed)
            {
                var prefix = _currentChannel != null
                    ? $"[{_currentChannel} ({_socket.GetChannelUsers(_currentChannel).Count})] "
                    : "";

                var line = ReadLine.Read($"{prefix}> "); // Get string from user
                if (line == "")
                {
                    continue;
                }

                handler.HandleCommand(_currentChannel, line);
            }
        }
Beispiel #11
0
        protected async Task Activated(IActivatedEventArgs e)
        {
            // Initialise the app if it's not already open
            Debug.WriteLine("App activated!");
            var loaded = await InitApp(e);

            // Handle toast activation
            if (e.Kind == ActivationKind.ToastNotification && loaded && NavigationService.Content is MainPage)
            {
                MainPage mainPage = NavigationService.Content as MainPage;

                var args = e as ToastNotificationActivatedEventArgs;
                var toastActivationArgs = args;
                // Parse the query string
                QueryString qryStr = QueryString.Parse(toastActivationArgs.Argument);
                if (!qryStr.Contains("action"))
                {
                    return;
                }
                var ircHandler = IrcUiHandler.Instance;
                if (ircHandler == null)
                {
                    return;
                }
                // See what action is being requested
                if (qryStr["action"] == "reply")
                {
                    string channel  = qryStr["channel"];
                    string server   = qryStr["server"];
                    string username = qryStr["username"];
                    var    message  = args.UserInput["tbReply"];
                    if (!ircHandler.connectedServersList.Contains(server))
                    {
                        return;
                    }

                    if (mainPage != null)
                    {
                        mainPage.MentionReply(server, channel, username + ": " + message);
                    }
                    if (!mainPage.currentChannel.Equals(channel))
                    {
                        mainPage.SwitchChannel(server, channel, false);
                    }
                }
                else if (qryStr["action"] == "viewConversation")
                {
                    // The conversation ID retrieved from the toast args
                    string channel = qryStr["channel"];
                    string server  = qryStr["server"];

                    if (mainPage == null)
                    {
                        return;
                    }

                    if (!ircHandler.connectedServersList.Contains(server))
                    {
                        return;
                    }

                    // If we're already viewing that channel, do nothing
                    if (!mainPage.currentChannel.Equals(channel))
                    {
                        mainPage.SwitchChannel(server, channel, false);
                    }
                }
            }

            if (e.Kind == ActivationKind.Protocol)
            {
                ProtocolActivatedEventArgs eventArgs = e as ProtocolActivatedEventArgs;
                // TODO: Handle URI activation
                // The received URI is eventArgs.Uri.AbsoluteUri
                var uri  = eventArgs.Uri;
                var port = 0;
                if (uri.Port == 0)
                {
                    port = 6667;
                }
                else
                {
                    port = uri.Port;
                }

                IrcServer server = new IrcServer {
                    name = uri.Host, hostname = uri.Host, port = port, ssl = uri.Scheme == "ircs",
                };
                if (uri.Segments.Length >= 2)
                {
                    server.channels += "#" + uri.Segments[1];
                }

                MainPage.instance.IrcPrompt(server);
            }

            // Ensure the current window is active
            Window.Current.Activate();
        }