Esempio n. 1
0
        public void TestSendPresenceAndMessage()
        {
            //Logger logger = LogManager.GetLogger("foo");
            ILogger log = NLog.LogManager.GetLogger("foo");

            log.Info("Program started");
            Presence presence = new Presence(ShowType.Show);

            JabberID from    = new JabberID(myJid);
            JabberID to      = new JabberID(partnerJid);
            string   msg     = "Hello";
            Message  message = new Message(from, to, msg);

            XmppClientConnection connection = new XmppClientConnection(
                new JabberID(myJid), password);

            connection.Login();

            if (!connection.Connected || !connection.Authenticated)
            {
                throw new Exception("Not authenticate");
            }

            Assert.DoesNotThrow(() => { connection.Send(presence); });
            Assert.DoesNotThrow(() => { connection.Send(message); });

            //NLogger.ShutdownLogger();
        }
Esempio n. 2
0
        public void addSession(Session session)
        {
            resources.Add(session.getJID().getResource(), session); // key, value
            if (activeSession == null)
            {
                activeSession = session;
            }
            else if (activeSession.getPriority() < session.getPriority())
            {
                activeSession = session;
            }


            //isprakjanje na Roster (ne e spored stadard)

            Packet packet = new Packet("iq");

            packet["type"] = "set";
            JabberID jidTo = session.getJID();

            packet.To = jidTo.User + "@" + jidTo.Domain;

            getRoster().getPacket().setParent(packet);
            MessageHandler.deliverPacket(packet);


            // kraj na isprakjanje a roster



            deliverMessages();
        }
Esempio n. 3
0
        public void TestMessageGrabber()
        {
            Presence presence = new Presence(ShowType.Show);

            int    waitMessage = 20000;
            string msg         = "hello";
            string expected    = partnerJid + ":hello";

            JabberID jidPartner = new JabberID(partnerJid);
            Message  message    = new Message(myJid, jidPartner.Full, msg);

            XmppClientConnection connection = new XmppClientConnection(
                new JabberID(myJid), password);

            connection.MessageGrabber.Add(
                jidPartner, new MessageCallback(messageCallback));

            connection.Login();

            connection.Send(presence);
            connection.Send(message);

            while (partnerMessage == null)
            {
                Thread.Sleep(2000);
            }

            Assert.AreEqual(expected, partnerMessage);
        }
Esempio n. 4
0
        public void notify(Packet packet)
        {
            Console.WriteLine("in message handler");
            String type = packet.Type == null ? "normal" : packet.Type;

            Console.WriteLine("Received " + type + " message: " + packet.getChildValue("body"));
            Console.WriteLine("    To: " + packet.To);
            Console.WriteLine("  From: " + packet.From);
            JabberID jid = new JabberID(packet.From);

            if (jid.User != null && jid.User.EndsWith(".group"))               // groupchat message
            //void ReceiveGroupMessage(String groupJID, String userNick, String message)

            {
                String user     = jid.User;
                String groupJID = user.Substring(0, user.LastIndexOf(".group"));
                String userNick = jid.Resource;

                //ReceiveGroupMessage(groupJID, userNick, packet.getChildValue("body");
                RecieveGroupMessageDelegate rgmd = new RecieveGroupMessageDelegate(model.gui.ReceiveGroupMessage);
                model.gui.Invoke(rgmd, new Object[] { groupJID, userNick, packet.getChildValue("body") });
            }
            else                 // regular message

            {
                RecieveMessageDelegate del = new RecieveMessageDelegate(model.gui.ReceiveMessage);
                model.gui.Invoke(del, new Object[] { jid, packet.getChildValue("body") });
                //model.gui.ReceiveMessage(jid, packet.getChildValue("body"));
            }
        }
Esempio n. 5
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            Hide();
            if (ValidateInput() == false)
            {
                DialogResult = DialogResult.None;
                return;
            }

            Contact contact = AppController.Instance.Contacts[cbContactname.SelectedItem.ToString()];
            JabberID Jid =
                new JabberID(contact.UserName.ToString(), contact.ServerName.ToString(), Settings.Default.Resource);
            Contact delContact = new Contact(Jid, contact.GroupName.ToString(), LoginState.Offline);
            Contact editContact = new Contact(Jid, tbnewGpName.Text.Trim(), LoginState.Offline);

            UnsubscribedResponse resp = new UnsubscribedResponse(Jid);
            AppController.Instance.SessionManager.Send(resp);
            AppController.Instance.SessionManager.BeginSend(new RosterRemove(Jid, contact.UserName.ToString()));
            AppController.Instance.Contacts.Remove(delContact);

            SubscribeRequest p = new SubscribeRequest(Jid);
            AppController.Instance.SessionManager.Send(p);
            AppController.Instance.SessionManager.BeginSend(
                new RosterAdd(Jid, contact.UserName.ToString(), tbnewGpName.Text.ToString()));
            AppController.Instance.Contacts.Add(editContact);

            AppController.Instance.MainWindow.UpdateContactList();
        }
Esempio n. 6
0
 // Invokes a method to receive message in a conversation window, delegate is used for cross thread calls
 public void ReceiveMessage(JabberID from, string body)
 {
     Console.WriteLine("Gui received message from: " + from);
     if (!conversations.ContainsKey(from.User + "@" + from.Domain))                      // Check if there is already open conversation window
     {
         Contact c;
         if (contacts.ContainsKey(from.User + "@" + from.Domain))                                // Check if sender is in Contact list
         {
             c = contacts[from.User + "@" + from.Domain];
         }
         else
         {
             c = new Contact(from.User + "@" + from.Domain);
         }
         conversations[from.User + "@" + from.Domain] = new ConverstationWindow(c, this);                        // Open new conversation window
         conversations[from.User + "@" + from.Domain].Show();                                                    // Show if new window
     }
     else
     {
         if (!conversations[from.User + "@" + from.Domain].Visible)
         {
             conversations[from.User + "@" + from.Domain].Show();
         }
         conversations[from.User + "@" + from.Domain].Activate();                                                                // Just activate if already opened
     }
     conversations[from.User + "@" + from.Domain].ReceiveMessage(body);                                                          // Receive message
 }
Esempio n. 7
0
 public ChatServerMenuItem(JabberID jid, MultiUserChatForm parentForm)
     : base(jid.ToString())
 {
     base.Click +=new EventHandler(ChatServerMenuItem_Click);
     _myJID = jid;
     _myForm = parentForm;
 }
Esempio n. 8
0
        public void notify(Packet packet)
        {
            packet.To   = null;
            packet.From = null;
            if (packet.getSession().getStatus() != Session.SessionStatus.authenticated)
            {
                //can not send message:user is not authenticated
                //Error Monitoring must be implemented
                MessageHandler.deliverPacket(packet);
                return;
            }
            User user = userIndex.getUser(packet.getSession());

            if (packet.Type.Equals("set"))
            {
                user.getRoster().updateRoster(packet);
                return;
            }
            if (packet.Type.Equals("get"))
            {
                packet.Type = "result";
                JabberID jidTo = packet.getSession().getJID();
                packet.To = jidTo.User + "@" + jidTo.Domain;
                // packet.From = null;
                packet.removeAttribute("from");
                packet.getChildren().Clear();
                user.getRoster().getPacket().setParent(packet);
                MessageHandler.deliverPacket(packet);
                return;
            }
            //error in packet
            MessageHandler.deliverPacket(packet);
        }
Esempio n. 9
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            ArrayList deleteUsers = new ArrayList();
            Hide();

            foreach (Contact contact in AppController.Instance.Contacts)
            {
                if (contact.GroupName.Equals(cbDeletegroup.SelectedItem.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    deleteUsers.Add(contact.UserName);
                }
            }

            for (int i = 0; i < deleteUsers.Count; i++)
            {
                Contact delcontact = AppController.Instance.Contacts[deleteUsers[i].ToString()];
                JabberID Jid =
                    new JabberID(delcontact.UserName.ToString(), delcontact.ServerName.ToString(),
                                 Settings.Default.Resource);

                UnsubscribedResponse resp = new UnsubscribedResponse(Jid);
                AppController.Instance.SessionManager.Send(resp);
                AppController.Instance.SessionManager.BeginSend(new RosterRemove(Jid, delcontact.UserName.ToString()));

                AppController.Instance.Contacts.Remove(delcontact);
                AppController.Instance.MainWindow.UpdateContactList();
            }
        }
Esempio n. 10
0
        protected static IEnumerator <object> HandlePing(Session session, string xml, long socketID)
        {
            try {
                var si = Program.GetScriptInstance <Common>("Common.Script.dll");
                if (si != null)
                {
                    si.LogPrint(null, "Attempting to respond to jabber ping.");
                }
                else
                {
                    Console.WriteLine("Attempting to respond to jabber ping.");
                }
            } catch {
            }

            var fDoc = Future.RunInThread(() => {
                var doc = new XmlDocument();
                doc.LoadXml(xml);
                return(doc);
            });

            yield return(fDoc);

            var    root     = fDoc.Result.FirstChild;
            var    toJID    = new JabberID(root.Attributes["to"].InnerText);
            var    fromJID  = new JabberID(root.Attributes["from"].InnerText);
            string packetID = root.Attributes["id"].InnerText;

            Packet packet = new SoapboxCore.IQ.IQResultResponse(
                fromJID, toJID, packetID, socketID
                );

            yield return(session.AsyncSend(packet));
        }
 public void InitMessageGrabber(XmppClientConnection connection, JabberID jid)
 {
     _connection     = connection;
     _messageGrabber = new MessageGrabber(_connection);
     _messageGrabber.Add(jid, OnMessage);
     //contact.Conversation.MessageGrabber = new MessageGrabber(connection)
     //    .Add(new JabberID(PartnerJid), OnMessage);
 }
Esempio n. 12
0
        public void Parse_WithResource()
        {
            JabberID jid = JabberID.Parse("abc@def/ghi");

            Assert.IsNotNull(jid);
            Assert.AreEqual("abc", jid.Node);
            Assert.AreEqual("def", jid.Domain);
            Assert.AreEqual("ghi", jid.Resource);
        }
Esempio n. 13
0
        public Message(string from, string to, string msg) : this()
        {
            _from = new JabberID(from);
            _to   = new JabberID(to);
            _body = msg;

            XmlData = XmlData.Replace(DataTemplate, msg).
                      Replace(TagToTemplate, to).
                      Replace(TagFromTemplate, from);
        }
Esempio n. 14
0
        internal void SelectContact(JabberID contactID)
        {
            if (contactID == null)
                return;

            if (cbContactname.Items.Contains(contactID.UserName))
            {
                cbContactname.SelectedIndex = cbContactname.FindString(contactID.UserName);
            }
        }
Esempio n. 15
0
        public async Task Execute(AuthorizeClientRequestParams requestParams)
        {
            Contract.Requires(requestParams != null);
            if (!JabberID.ValidateJid(_requestParams.AuthorizeCredentials.Jid))
            {
                MessageBox.Show("Введен некорректный идентификатор пользователя.");
                return;
            }

            XmppClientConnection connection = requestParams.Connection;
            ClientVModel         client     = requestParams.Client;
            //ConversationVModel conversation = requestParams.Conversation;
            ConnectionStateVModel connectionState = requestParams.ConnectionState;
            AuthorizationVModel   credentials     = requestParams.AuthorizeCredentials;
            ReadOnlyObservableCollection <RosterContactVModel> contacts = requestParams.Contacts;

            JabberID id = new JabberID(credentials.Jid);

            connection = new XmppClientConnection(id, credentials.Password);

            await connection.LoginAsync();

            if (connection.Connected && connection.Authenticated)
            {
                MessageBox.Show("Вы успешно авторизованы.");
                client.JabberId           = id;
                client.Password           = credentials.Password;
                connectionState.Connected = true;

                //TODO: Всем контактам передать ссылку на текущее соединение
                //conversation.Connection = connection;
                foreach (var contact in contacts)
                {
                    contact.Conversation.InitMessageGrabber(connection, contact.JabberId);
                    //contact.Conversation.Connection = connection;
                    //contact.Conversation.MessageGrabber = new MessageGrabber(connection)
                    //    .Add(new JabberID(PartnerJid), OnMessage);
                }
            }
            else
            {
                MessageBox.Show("Произошла ошибка, попробуйте еще раз");
                return;
            }

            SendMessageCommand       sendMessageCommand = _requestParams.SendMessageCommand;
            SendMessageRequestParams parameters         = new SendMessageRequestParams(connection, client);

            sendMessageCommand.ExecuteParams = parameters;

            connection.Send(new Presence(ShowType.Show));
        }
Esempio n. 16
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            Contact delContact = AppController.Instance.Contacts[cbUsername.SelectedItem.ToString()];
            JabberID Jid =
                new JabberID(delContact.UserName.ToString(), delContact.ServerName.ToString(), Settings.Default.Resource);

            UnsubscribedResponse resp = new UnsubscribedResponse(Jid);
            AppController.Instance.SessionManager.Send(resp);
            AppController.Instance.SessionManager.BeginSend(new RosterRemove(Jid, cbUsername.SelectedItem.ToString()));
            AppController.Instance.Contacts.Remove(delContact);
            AppController.Instance.MainWindow.UpdateContactList();
            Hide();
        }
Esempio n. 17
0
        public static string GetSafeFileName(JabberID contact)
        {
            string safe = contact.full;

            foreach (char lDisallowed in System.IO.Path.GetInvalidFileNameChars())
            {
                safe = safe.Replace(lDisallowed.ToString(), "");
            }
            foreach (char lDisallowed in System.IO.Path.GetInvalidPathChars())
            {
                safe = safe.Replace(lDisallowed.ToString(), "");
            }
            return(safe);
        }
Esempio n. 18
0
        public ChatRoomTabPage(JabberID occupantJID, MultiUserChatForm form, SessionManager sm)
            : base(occupantJID.BareJID.ToString())
        {
            _occupant = occupantJID;
            _form = form;
            _sm = sm;

            _sm.Session.AddHandler(typeof(MessageErrorPacket), new Session.PacketReceivedDelegate(IncomingMessage));
            _sm.Session.AddHandler(typeof(GroupChatMessage), new Session.PacketReceivedDelegate(IncomingMessage));
            _sm.Session.AddHandler(typeof(ChangeSubjectMessage), new Session.PacketReceivedDelegate(IncomingMessage));
            _sm.Session.AddHandler(typeof(AvailableRequest), new Session.PacketReceivedDelegate(IncomingPresence));
            _sm.Session.AddHandler(typeof(ErrorResponse), new Session.PacketReceivedDelegate(IncomingPresence));
            _sm.Session.AddHandler(typeof(OccupantAvailableResponse), new Session.PacketReceivedDelegate(IncomingPresence));
            _sm.Session.AddHandler(typeof(OccupantUnavailableResponse), new Session.PacketReceivedDelegate(IncomingPresence));
        }
Esempio n. 19
0
        public Session getSession(JabberID jabberID)
        {
            String  jidString = jabberID.ToString();
            Session session   = null;

            try {
                session = jidIndex[jidString];
                return(session);
            } catch (Exception ex) {
                try {
                    List <Session> resources = userIndex[jabberID.User];
                    return(resources[0]);
                } catch (Exception e) {
                    return(null);
                }
            }
        }
Esempio n. 20
0
        public Message(string xml) : this()
        {
            Match from = _fromPattern.Match(xml);
            Match to   = _toPattern.Match(xml);
            Match body = _bodyPattern.Match(xml);

            if (from.Success && to.Success && body.Success)
            {
                _from = new JabberID(from.Groups[0].Value.Replace("from='", "").Replace(" to", ""));
                _to   = new JabberID(to.Groups[0].Value.Replace("to='", "").Replace(" xml:lang=", ""));
                _body = body.Groups[0].Value.Replace("<body>", "").Replace("</body>", "");
            }

            XmlData = XmlData.Replace(DataTemplate, _body).
                      Replace(TagToTemplate, _to.Full).
                      Replace(TagFromTemplate, _from.Full);
        }
Esempio n. 21
0
        public void handleChatMessage(Packet packet)
        {
            JabberID recipient = new JabberID(packet.To);
            Group    group     = this[recipient.User];

            packet.From = group.JabberID + "/" + group.jid2nick[packet.From];

            if (recipient.Resource == null)
            {
                deliverToGroup(group, packet);
            }
            else
            {
                packet.To = group.nick2jid[recipient.Resource];
                MessageHandler.deliverPacket(packet);
            }
        }
Esempio n. 22
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (ValidateInput() == false)
            {
                DialogResult = DialogResult.None;
                return;
            }

            JabberID JID = null;
            string message = "The User ID you entered is not valid. Please enter a valid User ID";
            try
            {
                JID = new JabberID(tbUserName.Text.ToString(), tbServerName.Text.ToString(), Settings.Default.Resource);
                if (JID.UserName.Length == 0 ||
                    JID.Server.Length == 0)
                {
                    MessageBox.Show(message, "Invalid UserID");
                    DialogResult = DialogResult.None;
                    return;
                }
            }
            catch
            {
                MessageBox.Show(message, "Invalid UserID");
                DialogResult = DialogResult.None;
                return;
            }
            Contact newContact = new Contact(JID, tbGroupName.Text.Trim(), LoginState.Offline);
            foreach (Contact contact in AppController.Instance.Contacts)
            {
                if (contact.Equals(newContact))
                {
                    MessageBox.Show("Contact already exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    DialogResult = DialogResult.None;
                    return;
                }
            }

            SubscribeRequest subscribeRequest = new SubscribeRequest(JID);
            AppController.Instance.SessionManager.Send(subscribeRequest);
            AppController.Instance.SessionManager.BeginSend(
                new RosterAdd(JID, tbUserName.Text.Trim(), tbGroupName.Text.Trim()));
            AppController.Instance.Contacts.Add(newContact);
            AppController.Instance.MainWindow.UpdateContactList();
        }
Esempio n. 23
0
        public void handleChatPresence(Packet packet)
        {
            JabberID recipient = new JabberID(packet.To);

            if (!isChatPacket(packet))
            {
                return;
            }

            Group  group = this[recipient.User];
            String nick  = recipient.Resource;
            String jid   = packet.From;

            if (String.IsNullOrEmpty(nick))
            {
                sendEmptyNicknameError(packet);
                return;
            }


            if (group.nick2jid.ContainsKey(nick))
            {
                if (group.nick2jid[nick] == packet.From)
                {
                    updatePresence(group, packet);
                }
                else
                {
                    sendConflictingNicknameError(packet);
                }
            }
            else
            {
                if (group.jid2nick.ContainsKey(jid))
                {
                    sendConflictingUserError(packet);
                }
                else
                {
                    joinGroup(group, packet);
                }
            }
        }
Esempio n. 24
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            Hide();
            ArrayList editgroup = new ArrayList();

            if (ValidateInput() == false)
            {
                DialogResult = DialogResult.None;
                return;
            }

            foreach (Contact contact in AppController.Instance.Contacts)
            {
                if (contact.GroupName.Equals(cbOldgroup.SelectedItem.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    editgroup.Add(contact.UserName);
                }
            }

            for (int i = 0; i < editgroup.Count; i++)
            {
                Contact editGp = AppController.Instance.Contacts[editgroup[i].ToString()];
                JabberID Jid =
                    new JabberID(editGp.UserName.ToString(), editGp.ServerName.ToString(), Settings.Default.Resource);

                Contact delContact = new Contact(Jid, editGp.GroupName.ToString(), LoginState.Offline);
                Contact editContact = new Contact(Jid, tbNewGroup.Text.Trim(), LoginState.Offline);

                UnsubscribedResponse resp = new UnsubscribedResponse(Jid);
                AppController.Instance.SessionManager.Send(resp);
                AppController.Instance.SessionManager.BeginSend(new RosterRemove(Jid, editGp.UserName.ToString()));
                AppController.Instance.Contacts.Remove(delContact);

                SubscribeRequest p = new SubscribeRequest(Jid);
                AppController.Instance.SessionManager.Send(p);
                AppController.Instance.SessionManager.BeginSend(
                    new RosterAdd(Jid, editGp.UserName.ToString(), tbNewGroup.Text.ToString()));
                AppController.Instance.Contacts.Add(editContact);

                AppController.Instance.MainWindow.UpdateContactList();
            }
        }
Esempio n. 25
0
        public void joinGroup(Group group, Packet packet)
        {
            JabberID jid    = new JabberID(packet.To);
            String   sender = packet.From;

            group.jid2nick.Add(sender, jid.Resource);
            group.nick2jid.Add(jid.Resource, sender);
            updatePresence(group, packet);

            foreach (KeyValuePair <String, Packet> pair in group.jid2presence)
            {
                Packet p = pair.Value;
                if (p.From != jid.ToString())
                {
                    p.To = sender;
                    MessageHandler.deliverPacket(p);
                }
            }
            serverMessage(group, jid.Resource + " has joined the group");
        }
Esempio n. 26
0
        public void TestSendManyMessages()
        {
            Presence presence = new Presence(ShowType.Show);

            JabberID from    = new JabberID(myJid);
            JabberID to      = new JabberID(partnerJid);
            string   msg     = "Hello";
            Message  message = new Message(from, to, msg);

            XmppClientConnection connection = new XmppClientConnection(
                new JabberID(myJid), password);

            connection.Login();
            connection.Send(presence);

            for (int i = 0; i < 500; i++)
            {
                Assert.DoesNotThrow(() => { connection.Send(new Message(from, to, i.ToString())); });
                Thread.Sleep(100);
            }
        }
Esempio n. 27
0
        public async Task TestSendPresenceAndMessageAsync()
        {
            Presence presence = new Presence(ShowType.Show);

            JabberID from    = new JabberID(myJid);
            JabberID to      = new JabberID(partnerJid);
            string   msg     = "Hello";
            Message  message = new Message(from, to, msg);

            XmppClientConnection connection = new XmppClientConnection(
                new JabberID(myJid), password);
            await connection.LoginAsync();

            if (!connection.Connected || !connection.Authenticated)
            {
                throw new Exception("Not authenticate");
            }

            Assert.DoesNotThrow(() => { connection.Send(presence); });
            Assert.DoesNotThrow(() => { connection.Send(message); });
        }
        public static string DigestMD5AuthAlgo(string xml, JabberID jid, string password)
        {
            var    realm     = jid.Server;
            var    digestUri = "xmpp/" + jid.Server;
            string uniqData  = StanzaManager.ParseChallenge(xml);
            Regex  reg       = new Regex("nonce=\"[0-9]*\"");
            Match  m         = reg.Match(uniqData);
            string nonce     = string.Empty;

            if (m.Success)
            {
                nonce = m.Groups[0].Value;
                nonce = nonce.Replace("nonce=\"", "").Replace("\"", "");
            }

            string cNonce     = Environment.MachineName; //GetUniqCNonce();
            string clientHash = GenerateClientHash(jid.Username, password, nonce, cNonce, realm, digestUri);
            string value      = GetAuthenticationString(jid.Username, password, nonce, cNonce, clientHash, realm, digestUri);

            string baseResponse = Convert.ToBase64String(Encoding.UTF8.GetBytes(value));

            return(baseResponse);
        }
Esempio n. 29
0
        public bool isChatPacket(Packet packet)
        {
            JabberID recipient;

            if (packet.To == null)
            {
                return(false);
            }
            recipient = new JabberID(packet.To);

            //try {
            //    recipient = new JabberID(packet.To);
            //} catch (Exception ex) {
            //    return false;
            //}

            String user = recipient.User;

            if (user == null)
            {
                return(false);
            }
            return(user.EndsWith(".group") && recipient.equalsDomain(JabberServer.server_name));
        }
Esempio n. 30
0
        }//getPacket

        public void updateRoster(Packet packet)
        {
            //Extract the query packet
            Packet rosterQuery = packet.getFirstChild("query");

            rosterQuery.setAttribute("xmlns", "jabber:iq:roster");
            foreach (object rosterItems in rosterQuery.getChildren())
            {
                //for each <item> packet in the query
                Object child = rosterItems;
                if (child is Packet)
                {
                    Packet itemPacket = child as Packet;
                    String subJID     = itemPacket.getAttribute("jid");



                    //create Subscriber object if needed
                    //Subscriber sendersSubscriberItem = this.subscribers[subJID] as Subscriber;
                    if ((Server.JabberServer.RosterHashtable[this.user] as UserRoster) == null)
                    {
                        Server.JabberServer.RosterHashtable[this.user] = new UserRoster();
                    }
                    Subscriber sub = (Server.JabberServer.RosterHashtable[this.user] as UserRoster).subscribers[subJID] as Subscriber;
                    if (sub == null)
                    {
                        sub = new Subscriber();
                        sub.subscription = "none";
                        sub.ask          = null;
                        (Server.JabberServer.RosterHashtable[this.user] as UserRoster).subscribers.Add(subJID, sub);
                    }

                    if (itemPacket.getAttribute("subscription") != null)
                    {
                        //signal to remove
                        if (itemPacket.getAttribute("subscription").Equals("remove"))
                        {
                            //remove from subscribers item
                            JabberID otherID = new JabberID(subJID);
                            (Server.JabberServer.RosterHashtable[this.user] as UserRoster).subscribers.Remove(otherID.ToString());
                            if ((Server.JabberServer.RosterHashtable[this.user] as UserRoster).items.ContainsKey(subJID))
                            {
                                //remove <item> packet
                                (Server.JabberServer.RosterHashtable[this.user] as UserRoster).items.Remove(subJID);
                            }

                            if ((Server.JabberServer.RosterHashtable[otherID.User] as UserRoster) == null)
                            {
                                Server.JabberServer.RosterHashtable[otherID.User] = new UserRoster();
                            }
                            //set only subscription=none from other item
                            sub = ((Server.JabberServer.RosterHashtable[otherID.User] as UserRoster).subscribers[this.user + "@" + Server.JabberServer.server_name]) as Subscriber;
                            if (sub == null)
                            {
                                sub = new Subscriber();
                            }
                            sub.subscription = "none";
                            sub.ask          = null;
                            (Server.JabberServer.RosterHashtable[otherID.User] as UserRoster).subscribers[this.user + "@" + Server.JabberServer.server_name] = sub;
                            //(Server.JabberServer.RosterHashtable[subJID] as UserRoster).subscribers.Add(subJID, sendersSubscriberItem);
                            //}
                            if ((Server.JabberServer.RosterHashtable[otherID.User] as UserRoster).items.ContainsKey(this.user + "@" + Server.JabberServer.server_name))
                            {
                                //update <item> packet
                                //itemPacket.removeAttribute("subscription");

                                Packet mypacket = (Server.JabberServer.RosterHashtable[otherID.User] as UserRoster).items[this.user + "@" + Server.JabberServer.server_name] as Packet;
                                mypacket.setAttribute("subscription", "none");
                                mypacket.setAttribute("ask", null);
                                (Server.JabberServer.RosterHashtable[otherID.User] as UserRoster).items[this.user + "@" + Server.JabberServer.server_name] = mypacket;
                            }
                        }
                    }
                    else
                    {
                        //update <item> with the subscriber info for roster push
                        itemPacket.setAttribute("subscription", sub.subscription);
                        itemPacket.setAttribute("ask", sub.ask);

                        //Packet test = items[subJID];
                        if (!(Server.JabberServer.RosterHashtable[this.user] as UserRoster).items.ContainsKey(subJID))
                        {
                            //store updated <item> packet
                            (Server.JabberServer.RosterHashtable[this.user] as UserRoster).items.Add(subJID, itemPacket);
                        }
                        else
                        {
                            (Server.JabberServer.RosterHashtable[this.user] as UserRoster).items[subJID] = itemPacket;
                        }
                    }
                }
            }
            //Roster push
            packet.Type = "set";
            JabberID jidTo = packet.getSession().getJID();

            packet.To = jidTo.User + "@" + jidTo.Domain;
            packet.removeAttribute("from");
            //needs to be verified
            MessageHandler.deliverPacket(packet);
        }//update roster
Esempio n. 31
0
        private ChatServerMenuItem AddChatServerMenuItem(JabberID jid, ChatServerMenuItem parent)
        {
            ChatServerMenuItem itm = new ChatServerMenuItem(jid, this);
            if (parent == null)
                mnuJoinRoom.MenuItems.Add(itm);
            else
            {
                //make sure we can still output the template for the service
                if (parent.MenuItems.Count == 0)
                {
                    parent.MenuItems.Add(new ChatServerMenuItem(jid.ServerJID, this));
                    parent.MenuItems.Add("-");
                }

                //add this room as a subitem
                parent.MenuItems.Add(itm);
            }

            return itm;
        }
Esempio n. 32
0
 private ChatServerMenuItem AddChatServerMenuItem(JabberID jid)
 {
     return AddChatServerMenuItem(jid, null);
 }
Esempio n. 33
0
        public void SetupJoinRoomCommand(JabberID server)
        {
            string room = null;

            if (server.IsBareJID())
            {
                int resourceLoc = RoomCommands.Join.Length + server.ToString().Length + 1;

                room = string.Concat(server.ToString(), "/", _sm.LocalUser.UserName);
                txtOutgoingMessage.Text = string.Concat(RoomCommands.Join, room);
                txtOutgoingMessage.Select(resourceLoc, _sm.LocalUser.UserName.Length);
            }
            else if (server.IsServerJID())
            {
                room = string.Concat("@", server.ToString(), "/", _sm.LocalUser.UserName);
                txtOutgoingMessage.Text = string.Concat(RoomCommands.Join, room);
                txtOutgoingMessage.Select(RoomCommands.Join.Length, 0);
            }
            else if (server.IsFullJID())
            {
                room = server.ToString();
                int resourceLoc = room.LastIndexOf("/") + 1;

                txtOutgoingMessage.Text = string.Concat(RoomCommands.Join, room);
                txtOutgoingMessage.Select(resourceLoc, server.Resource.Length);
            }

            txtOutgoingMessage.Focus();
        }
Esempio n. 34
0
        public void LeaveRoom(JabberID occupantJID)
        {
            if ( _rooms.Count == 0 ) return;

            ChatRoomTabPage t = (ChatRoomTabPage)_rooms[occupantJID.ToString().ToLower()];
            t.LeaveRoom();
        }
Esempio n. 35
0
 public void Remove(JabberID jid)
 {
     try { base.Remove(jid.ToString().ToLower()); }
     catch { }
 }
Esempio n. 36
0
        private new bool Validate()
        {
            UserNameTextBox.Text = UserNameTextBox.Text.Trim();
            PasswordTextBox.Text = PasswordTextBox.Text.Trim();
            ResourceTextBox.Text = ResourceTextBox.Text.Trim();
            ServerNameTextBox.Text = ServerNameTextBox.Text.Trim();

            if (UserNameTextBox.Text.IndexOfAny(new Char[] { '@', ' ', '/', '\\'} ) > -1)
            {
                MessageBox.Show("Your user name is not formatted correctly. Please use a different user name.\nExamples of a valid user name are: 'ViewsonicUser', 'CertificationUser', 'JohnDoe'", "Invalid Characters");
                return false;
            }

            if (UserNameTextBox.Text.Trim().Length == 0)
            {
                MessageBox.Show("You must enter a user name to login.", "Empty User Name");
                return false;
            }

            if (PasswordTextBox.Text.Trim().Length == 0)
            {
                MessageBox.Show("You must enter a password to login.", "Empty Password");
                return false;
            }

            if (ResourceTextBox.Text.Trim().Length == 0)
            {
                MessageBox.Show("You must enter a resource Name to login.", "Empty Resource");
                return false;
            }

            if (ServerNameTextBox.Text.Trim().Length == 0)
            {
                MessageBox.Show("You must enter a Server Name to login.", "Empty Server Name");
                return false;
            }

            try { JabberID j = new JabberID(ServerNameTextBox.Text, ServerNameTextBox.Text, ResourceTextBox.Text); }
            catch
            {
                MessageBox.Show("Your user name is not formatted correctly. Please use a different user name.\nExamples of a valid user name are: 'ViewsonicUser', 'CertificationUser', 'JohnDoe'", "Invalid Characters");
                return false;
            }

            string hostName = ServerNameTextBox.Text;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                this.Text = string.Format("{0}  -  Validating Server Name", _baseText);
                System.Net.IPHostEntry IP = System.Net.Dns.GetHostByName(hostName);
            }
            catch
            {
                MessageBox.Show("The Server name you entered cannot be found. Please try a different server.", "Unknown Host Name");
                return false;
            }
            finally
            {
                this.Text = _baseText;
                this.Cursor = Cursors.Default;
            }

            return true;
        }
Esempio n. 37
0
        //Gets the registration info from the specified server
        //based on the specified JabberID
        //The Jabber server doesn't do much with this, but it is part of the protocol
        //and some of the transports actually require the Key value that is returned here
        //in order to complete registration.
        private RegisterInfoResponse GetRegistrationInfo(JabberID JID)
        {
            //get registration info
            RegisterInfoRequest IQRegisterInfo = new RegisterInfoRequest(new JabberID(ServerNameTextBox.Text));

            Packet response = _SessionManager.Send(IQRegisterInfo, 30000);
            return WConvert.ToRegisterInfoResponse(response);
        }
Esempio n. 38
0
 public MessageForm Show(JabberID RemoteUserJID, MessagePacket initialMessage)
 {
     return GetMessageWindow(RemoteUserJID, initialMessage);
 }
Esempio n. 39
0
 private ListViewRosterItem GetListViewRosterItem(JabberID jid)
 {
     foreach (ListViewRosterItem lvri in lvRoster.Items)
     {
         if (lvri.RosterItem.JID.Equals(jid, JabberID.JabberIDCompareEnum.JabberIDCompareNoResource))
         {
             return lvri;
         }
     }
     return null;
 }
Esempio n. 40
0
        public void notify(Packet packet)
        {
            try
            {
                //      Log.trace("Closing session");
                Session session = packet.Session;

                session.Writer.Write("</stream:stream> ");
                session.Writer.Flush();

                //notify other subscribers that user is unavailble
                //by Marko
                //begin
                JabberID userid = session.getJID();

                Packet unavailiblePacket = new Packet("presence");
                unavailiblePacket.setFrom(userid.ToString());
                unavailiblePacket.setAttribute("type", "unavailable");
                userIndex.getUser(userid.User).getRoster().updateSubscribers(unavailiblePacket);
                //it is not tested, but it should work
                //end

                //send groupchat presence unavailable & remove from groups
                String jid = userid.ToString();

                Packet presence = new Packet("presence");
                presence.Type = "unavailable";
                foreach (KeyValuePair <String, GroupChatManager.Group> kvp in GroupChatManager.Manager.groups)
                {
                    GroupChatManager.Group group = kvp.Value;
                    try
                    {
                        String nick = group.jid2nick[jid];               // test whether the user is in the group
                        presence.From = group.JabberID + "/" + nick;
                        GroupChatManager.Manager.removeUser(group, jid); // first remove then deliver so that the packet does not come back
                        GroupChatManager.Manager.deliverToGroup(group, presence);
                    }
                    catch (Exception ex)
                    {
                    }
                }
                // end groupchar clean-up



                //session.Socket.Close();
                userIndex.removeSession(session);
                //      Log.trace("Closed session");
            }
            catch (Exception ex)
            {
                JabberServer.output.WriteLine(ex.ToString());
                //      Log.error("CloseStreamHandler: ",ex);
//              packet.Session.Socket.Close();
//              userIndex.removeSession(packet.Session);
                //      Log.trace("Exception closed session");
            }
            finally
            {
                packet.Session.Socket.Close();
            }
        }
 //--------------------------------------------------------------------------------------------
 public override string GetDigestMD5AuthHashAsHexString(string user, string realm)
 {
     JabberID jid = new JabberID(user, realm, string.Empty);
     // Normally, we would go out to the database here and pull in the
     // password hash that was saved when the users account was created.
     // For this example, I'm hardcoding the password, and generating
     // the hash on the fly.
     string password = "";
     string hash = DigestMD5AuthMechanism.CreateUserRealmSecretHashAsHexString(jid.UserName, jid.Server, password);
     return hash;
 }
Esempio n. 42
0
        public void notify(Packet packet)
        {
            String from = packet["from"];


            String type = packet["type"];

            if (type == null)
            {
                type = "available";
            }

            String show = packet.getChildValue("show");

            if (show == null)
            {
                show = "chat";
            }

            String statusMessage = packet.getChildValue("status");

            //test whether the presence is a groupchat presence or regular presence
            JabberID jid  = new JabberID(from);
            String   user = jid.User;

            if (user != null && user.EndsWith(".group"))      // groupchat presence
            {
                Packet error = packet.getFirstChild("error"); // possible error packet
                if (error != null)                            // there was an error
                {
                    String code                 = error["code"];
                    String description          = error.getValue();
                    ShowGroupErrorDelegate sged = new ShowGroupErrorDelegate(model.gui.ShowGroupError);
                    model.gui.Invoke(sged, new Object[] { code, description });
                    //delegate : ShowError(String code, String description);
                    return;
                }

                // delegate signature : void UpdateGroupPresence(String groupJID, String userNick, Show show, String statusMessage)
                UpdateGroupPresenceDelegate ugpd = new UpdateGroupPresenceDelegate(model.gui.UpdateGroupPresence);

                Goodware.Jabber.GUI.Show showStatus = Show.chat;
                String groupName = user.Substring(0, user.LastIndexOf(".group"));
                String userNick  = jid.Resource;


                if (show.Equals("chat"))
                {
                    showStatus = Show.chat;
                }
                else if (show.Equals("away"))
                {
                    showStatus = Show.away;
                }
                else if (show.Equals("xa"))
                {
                    showStatus = Show.xa;
                }
                else if (show.Equals("dnd"))
                {
                    showStatus = Show.dnd;
                }


                if (type.Equals("available"))
                {
                    // UpdateGroupPresence(groupName, userNick, showStatus, statusMessage);
                    model.gui.Invoke(ugpd, new Object[] { groupName, userNick, showStatus, statusMessage });
                    // UpdateGroupPresence(groupName, userNick, showStatus, statusMessage);
                }
                else if (type.Equals("unavailable"))
                {
                    RemoveGroupMemberDelegate rgmd = new RemoveGroupMemberDelegate(model.gui.RemoveGroupMember);
                    model.gui.Invoke(rgmd, new Object[] { groupName, userNick });
                    // RemoveGroupMember(groupName, userNick);
                }
            }
            else                 // regular presence


            {
                GetContactDelegate del     = new GetContactDelegate(model.gui.GetContact);
                Contact            contact = (Contact)model.gui.Invoke(del, new Object[] { from });

                UpdateContactPresenceDelegate ucpd = new UpdateContactPresenceDelegate(model.gui.UpdateContactPresence);

                //two cases : presence update & presence subscription
                if (type.Equals("available") || type.Equals("unavailable"))                    // presence update
                {
                    Status status;

                    if (type.Equals("unavailable"))
                    {
                        status = Status.unavailable;
                    }
                    else if (show.Equals("chat"))
                    {
                        status = Status.chat;
                    }
                    else if (show.Equals("away"))
                    {
                        status = Status.away;
                    }
                    else if (show.Equals("xa"))
                    {
                        status = Status.xa;
                    }
                    else if (show.Equals("dnd"))
                    {
                        status = Status.dnd;
                    }
                    else
                    {
                        status = Status.unavailable;                                      // some default - execution should never come to this case
                    }
                    model.gui.Invoke(ucpd, new Object[] { from, status, statusMessage }); //delegate : UpdateContactPresence(from, Status.unavailable, null)
                }
                else                                                                      // presence subscription or unsubscription

                {
                    if (type.Equals("subscribe"))
                    {
                        if (contact == null)                           // this is the first invitation
                        {
                            AcceptInvitationDelegate aid = new AcceptInvitationDelegate(model.gui.AcceptInvitation);
                            if ((bool)model.gui.Invoke(aid, new Object[] { from }))                               //invitation accepted
                            {
                                model.sendPresence(from, "subscribed", null, null, null);
                                model.sendPresence(from, "subscribe", null, null, null);
                            }
                            else                                 //invitation refused
                            {
                                model.sendPresence(from, "unsubscribed", null, null, null);
                            }
                        }
                        else                              // the contact is already invited
                        {
                            model.sendPresence(from, "subscribed", null, null, null);
                            //contact.Status = Status.unavailable;
                            model.gui.Invoke(ucpd, new Object[] { from, Status.unavailable, null });                                    //delegate : UpdateContactPresence(from, Status.unavailable, null)
                            model.sendPresence(model.Me.Status, model.Me.StatusMessage);
                            //model.sendPresence - presence packet with current presence information for the user (type, status, show)
                        }
                    }
                    else if (type.Equals("subscribed"))
                    {
                        Status status = contact.Status;
                        if (status == Status.inviteSent)                           //the second stage in the "three-way handshake"
                        // do Nothing : immediately after this packet comes a "subscribe" packet and then things are handled
                        {
                        }
                        else if (status == Status.inviteAccepted)                             // the third stage in the "three-way handshake"
                        //contact.Status = Status.unavailable;
                        {
                            model.gui.Invoke(ucpd, new Object[] { from, Status.unavailable, null });                               // delegate : UpdateContactPresence(from, Status.unavailable, null)
                        }
                    }
                    else if (type.Equals("unsubscribe"))
                    {
                        // do Nothing : immediately after this packet comes an "unsubscribed" packet and then things are handled
                    }
                    else if (type.Equals("unsubscribed"))
                    {
                        RemoveContactDelegate rcd = new RemoveContactDelegate(model.gui.RemoveContact);
                        model.gui.Invoke(rcd, new Object[] { from });

                        // delegate : void removeContact(String jid) - actual invocation : removeContact(from)
                        // removes the contact <jid> from the structures containing the contacts
                    }     // type of presence
                }         // presence update or subscription
            }             // groupchat presence or regular presence
        }
Esempio n. 43
0
        }//update roster

        public void informSubscriber()
        {
            //needs to be checked!
            if ((Server.JabberServer.RosterHashtable[this.user] as UserRoster) != null)
            {
                foreach (object obj in (Server.JabberServer.RosterHashtable[this.user] as UserRoster).subscribers.Keys)
                {
                    Subscriber sub = (Server.JabberServer.RosterHashtable[this.user] as UserRoster).subscribers[obj] as Subscriber;
                    if (sub.subscription.Equals("from") || sub.subscription.Equals("both")) //inform sender of his subscribers status!
                    {
                        JabberID myid = new JabberID(obj.ToString());                       //other's subscribers id
                        if (myid.Domain.Equals(Server.JabberServer.server_name))            //if from this server
                        {
                            //new code!



                            if (Server.JabberServer.getUserIndex().getUser(myid.User).getSessions().Values == null)
                            {
                                // if Server.JabberServer.getUserIndex().getUser(myid.User).getSessions()
                                //user is offline
                                Packet presencePacket = new Packet("presence");
                                presencePacket.From = myid.ToString();
                                presencePacket.To   = new JabberID(this.user + "@" + Server.JabberServer.server_name).ToString();
                                presencePacket.setAttribute("type", "unavailable");
                                MessageHandler.deliverPacket(presencePacket);
                            }// if (Server.JabberServer.getUserIndex().getUser(myid.User).getSessions().Values!=null)
                            else
                            {
                                foreach (Object obj2 in (Server.JabberServer.getUserIndex().getUser(myid.User).getSessions().Values))
                                {//for each active session
                                    Session sess = obj2 as Session;

                                    Packet presencePacket = new Packet("presence");
                                    presencePacket.From = myid.ToString();
                                    presencePacket.To   = new JabberID(this.user + "@" + Server.JabberServer.server_name).ToString();
                                    if (sess.getPresence().isAvailible())
                                    {
                                        presencePacket.setAttribute("type", "available");
                                        if (sess.getPresence().getShow() != null)
                                        {
                                            presencePacket.Children.Add(new Packet("show", sess.getPresence().getShow()));
                                        }


                                        if (sess.getPresence().getStatus() != null)
                                        {
                                            presencePacket.Children.Add(new Packet("status", sess.getPresence().getStatus()));
                                        }


                                        if (sess.getPresence().getPriority() != null)
                                        {
                                            presencePacket.Children.Add(new Packet("priority", sess.getPresence().getPriority()));
                                        }

                                        //other info may be added!
                                    }
                                    else
                                    {
                                        presencePacket.setAttribute("type", "unavailable");
                                    }
                                    MessageHandler.deliverPacket(presencePacket);
                                } //for each active session
                            }
                        }         //  if(myid.Domain.Equals(Server.JabberServer.server_name))
                        else
                        {
                            //generate probe for S2S communication!@TODO
                        }
                    } //if (sub.subscription.Equals("from") || sub.subscription.Equals("both"))
                }     //foreach (object obj in (Server.JabberServer.RosterHashtable[this.user] as UserRoster).subscribers.Keys)
            }         //if ((Server.JabberServer.RosterHashtable[this.user] as UserRoster) != null)
        }
Esempio n. 44
0
 public Message(JabberID from, JabberID to, string msg) : this(from.Full, to.Full, msg)
 {
 }
        //--------------------------------------------------------------------------------------------
        /// <summary>
        /// Called when a user attempts to authenticate using an a 'plain-text' format. This format means
        /// the password itself was passed over the wire, and must now be authenticated. While not 
        /// particularly secure, many authentication protocols require having the actual text password,
        /// and thus a Hash+Salt value can't be used. Normally a server setup to use this protocol
        /// requires TLS, which keeps the credentials from being passed over an unencrypted link.
        /// </summary>
        /// <param name="userID">The full username to be authenticated.</param>
        /// <param name="password">The users password to check.</param>
        /// <returns>
        /// A SoapBoxPrincipal, with the authentication bit properly set. If the user is 
        /// properly authenticated then roles are returned in the SoapBox Identity nested in the principal.
        /// </returns>
        public override IPrincipal AuthUserPlain(JabberID userID, string password)
        {
            SoapBoxIdentity soapBoxID = new SoapBoxIdentity(userID);
            SoapBoxPrincipal soapBoxP = new SoapBoxPrincipal(soapBoxID);

            string[] myRoles;
            if (Drupal.CheckUser(userID.FullJabberID, password, out myRoles))
            {
                 soapBoxID.SetAuthenticated();
                 soapBoxP.AddRoles(myRoles);
            }
            return soapBoxP;
        }
Esempio n. 46
0
        public void updatePresence(Packet presence)
        {
            String   type            = presence.Type;
            Session  session         = presence.Session;
            Presence sessionPresence = session.getPresence();
            String   recipient       = presence.To;
            JabberID recipientID;
            Boolean  isUserSent;//it is not used yet, may be used in S2S comunication

            //packet filling begins
            if (recipient == null)
            {   //directed to server
                //server name
                recipientID = new JabberID(Server.JabberServer.server_name);
                isUserSent  = true;
            }
            else
            {
                recipientID = new JabberID(recipient);
                if (user.Equals(recipientID.User))
                {
                    isUserSent = false;
                }
                else
                {
                    isUserSent = true;
                }
            }
            String   sender = presence.From;
            JabberID SenderID;

            if (sender == null)
            {
                SenderID = session.JID;
            }
            else
            {
                SenderID = new JabberID(sender);
            }
            //added by marko
            presence.From = SenderID.User + "@" + SenderID.Domain;

            //original line:
            //String subscriber = isUserSent ? recipientID.ToString() : SenderID.ToString();
            String subscriber = recipientID.ToString();

            if (type == null)
            {
                type = "available";
            }
            //packet filling ends


            //packet routing begins
            if (type.Equals("available") || type.Equals("unavailable"))
            {
                //user-managed presence updates are delivered untouched
                if (!recipientID.ToString().Equals(Server.JabberServer.server_name))
                {
                    //may need some work;
                    MessageHandler.deliverPacket(presence);
                    return;
                }


                //Server-managed presence updates are forwarded only to subscribers

                //update the session's presence status

                sessionPresence.Availible = type.Equals("available");
                sessionPresence.Show      = presence.getChildValue("show");
                sessionPresence.Status    = presence.getChildValue("status");
                String priority = presence.getChildValue("priority");
                sessionPresence.Priority = priority;
                if (priority != null)
                {
                    //some code to set the priority of the session

                    try
                    {
                        session.setPriority(int.Parse(priority));
                    }
                    catch (Exception ex)
                    {
                        JabberServer.output.WriteLine("Error in incoming priority, setting priority to default: 1");
                        session.setPriority(0);
                    }
                }

                //deliver to all users presence subscribers
                updateSubscribers(presence);
                informSubscriber();
                return;
            }

            if (type.Equals("probe"))
            {
                //needed for server to server communication!!!!
                JabberServer.output.WriteLine("Roster: We don't handle probes yet " + presence.ToString());
                return;
            }



            //Marko believes it is checked for exceptions
            //Subscriber sendersSubscriberItem = (Subscriber)subscribers[subscriber];
            Subscriber sendersSubscriberItem = new Subscriber();

            Hashtable Rosters = JabberServer.RosterHashtable;//get reference to rosters


            //prepare sender's roster
            UserRoster senderRoster = Rosters[this.user] as UserRoster;//getting senders roster

            if (senderRoster == null)
            {
                senderRoster      = new UserRoster();
                senderRoster.user = this.user;
            }
            if (!Rosters.ContainsKey(this.user))
            {
                Rosters.Add(this.user, senderRoster);
            }

            //prepare recipients roster
            UserRoster recipientRoster = Rosters[recipientID.User] as UserRoster;//getting recipients roster

            if (recipientRoster == null)
            {
                recipientRoster      = new UserRoster();
                recipientRoster.user = recipientID.User;
            }
            if (!Rosters.ContainsKey(recipientID.User))
            {
                Rosters.Add(recipientID.User, recipientRoster);
            }

            sendersSubscriberItem = senderRoster.subscribers[subscriber] as Subscriber;//extra

            if (sendersSubscriberItem == null)
            {
                //create subscription item
                sendersSubscriberItem = new Subscriber();
                sendersSubscriberItem.subscription = "none";
                senderRoster.subscribers.Add(recipient, sendersSubscriberItem);
                Packet itempacket = new Packet("item");
                itempacket.setAttribute("jid", subscriber);
                senderRoster.items.Add(subscriber, itempacket);
            }

            //begin subscription managment
            if (type.Equals("subscribe"))
            {
                sendersSubscriberItem.ask = type; //set up subscription status
            }
            else if (type.Equals("subscribed"))   //if subscription accepted
            {
                sendersSubscriberItem.ask = null;
                if (sendersSubscriberItem.subscription.Equals("from"))
                {
                    sendersSubscriberItem.subscription = "both";
                }
                else if (sendersSubscriberItem.subscription.Equals("none"))
                {
                    sendersSubscriberItem.subscription = "to";
                }
            }
            else if (type.Equals("unsubscribed"))
            {//sender does not want to give presence updates to recipient
                sendersSubscriberItem.ask = null;

                if (sendersSubscriberItem.subscription.Equals("to"))
                {
                    sendersSubscriberItem.subscription = "none";
                }

                else if (sendersSubscriberItem.subscription.Equals("both"))
                {
                    sendersSubscriberItem.subscription = "from";
                }


                //notify recipient of sender's unavailble status:
                Packet unavailiblePacket = new Packet("presence");
                unavailiblePacket.setFrom(presence.From);
                unavailiblePacket.To = presence.To;
                unavailiblePacket.setAttribute("type", "unavailable");
                MessageHandler.deliverPacket(unavailiblePacket);
            }
            else if (type.Equals("unsubscribe"))
            {//sender no longer interested in recieving presence updates from recipient
                sendersSubscriberItem.ask = null;

                if (sendersSubscriberItem.subscription.Equals("both"))
                {
                    sendersSubscriberItem.subscription = "to";
                }
                else if (sendersSubscriberItem.subscription.Equals("from"))
                {
                    sendersSubscriberItem.subscription = "none";
                }
            }
            //update the corresponding changes in <items> table in sender's record used for delivery
            Packet item = (Packet)senderRoster.items[subscriber];

            if (item != null)
            {
                item.setAttribute("subscription", sendersSubscriberItem.subscription);
                item.setAttribute("ask", sendersSubscriberItem.ask);
                Packet iq = new Packet("iq");
                iq.Type = "set";
                Packet query = new Packet("query");
                query.setAttribute("xmlns", "jabber:iq:roster");
                query.setParent(iq);
                item.setParent(query);
                iq.To = this.user + "@" + Server.JabberServer.server_name;

                //Forward the subscription packet to recipient
                MessageHandler.deliverPacketToAll(user, iq);//may need some correction!
            }

            //processing of recipients roster begins
            if (sendersSubscriberItem.ask == null)
            {
                //the recipient user rosters update!
                Subscriber recipientsSubscriberItem = recipientRoster.subscribers[user + "@" + JabberServer.server_name] as Subscriber;//extra
                if (recipientsSubscriberItem == null)
                {
                    //create subscription item
                    recipientsSubscriberItem = new Subscriber();
                    recipientsSubscriberItem.subscription = "none";
                    recipientRoster.subscribers.Add(user + "@" + JabberServer.server_name, recipientsSubscriberItem);
                }

                //if type is subscribe, changes in this roster are not needed!!!

                if (type.Equals("subscribed"))//if subscription accepted
                {
                    recipientsSubscriberItem.ask = null;
                    if (recipientsSubscriberItem.subscription.Equals("none"))
                    {
                        recipientsSubscriberItem.subscription = "from";
                    }

                    else if (recipientsSubscriberItem.subscription.Equals("to"))
                    {
                        recipientsSubscriberItem.subscription = "both";
                    }
                }
                else if (type.Equals("unsubscribed"))
                {//sender no longer interested in giving presence updates to recipient
                    recipientsSubscriberItem.ask = null;
                    if (recipientsSubscriberItem.subscription.Equals("both"))
                    {
                        recipientsSubscriberItem.subscription = "to";
                    }
                    else if (recipientsSubscriberItem.subscription.Equals("from"))
                    {
                        recipientsSubscriberItem.subscription = "none";
                    }
                }
                else if (type.Equals("unsubscribe"))
                {//sender no longer interested in recieving presence updates from recipient
                    recipientsSubscriberItem.ask = null;
                    if (recipientsSubscriberItem.subscription.Equals("to"))
                    {
                        recipientsSubscriberItem.subscription = "none";
                    }

                    else if (recipientsSubscriberItem.subscription.Equals("both"))
                    {
                        recipientsSubscriberItem.subscription = "from";
                    }

                    //notify sender of unavailble status:
                    Packet unavailiblePacket = new Packet("presence");
                    unavailiblePacket.setFrom(presence.To);
                    unavailiblePacket.To = presence.From;
                    unavailiblePacket.setAttribute("type", "unavailable");
                    MessageHandler.deliverPacket(unavailiblePacket);
                }

                //update the corresponding changes in <items> table in sender's record used for delivery
                Packet item2 = (Packet)recipientRoster.items[user + "@" + JabberServer.server_name];
                if (item2 != null)
                {
                    item2.setAttribute("subscription", recipientsSubscriberItem.subscription);
                    item2.setAttribute("ask", recipientsSubscriberItem.ask);
                    Packet iq = new Packet("iq");
                    iq.Type = "set";
                    Packet query = new Packet("query");
                    query.setAttribute("xmlns", "jabber:iq:roster");
                    query.setParent(iq);
                    item2.setParent(query);
                    iq.To = recipientID.User + "@" + recipientID.Domain;
                    //Forward the subscription packet to recipient
                    MessageHandler.deliverPacketToAll(user, iq);//may need some correction!
                }
            }

            MessageHandler.deliverPacket(presence);
        }//UpdatePresense
        //--------------------------------------------------------------------------------------------
        /// <summary>
        /// Called when a user attempts to authenticate using an a 'digest' format. This format means
        /// the a hash of the password and the SessionId was passed over the wire and must now be 
        /// authenticated. This is signifigantly more secure than a plain-text authentication, but still
        /// not considered truly 'secure'. 
        /// </summary>
        /// <param name="userID">The full username to be authenticated.</param>
        /// <param name="sessionID">
        /// The Session ID associated with this user upon stream initiation. 
        /// The password hash (digest) is built using this as a Salt value.
        /// </param>
        /// <param name="userDigest">The hash of the users password and the Session Id</param>
        /// <returns>
        /// A SoapBoxPrincipal, with the authentication bit properly set. If the user is 
        /// properly authenticated then roles are returned in the SoapBox Identity nested in the principal.
        /// </returns>
        //public override IPrincipal AuthUserNonSASLDigest(JabberID userID, string sessionID, Digest userDigest)
        //{
        //    if (userDigest == null) throw new ArgumentNullException("userDigest");
        //    SoapBoxIdentity soapBoxID = new SoapBoxIdentity(userID);
        //    SoapBoxPrincipal soapBoxP = new SoapBoxPrincipal(soapBoxID);
        //    // Normally the line below would be a database dip to lookup
        //    // the actual password for the user who is attempting to
        //    // authenticate. Here, I'm skipping that and mandating the
        //    // password to be "Coversant".
        //    string textPassword = "******";
        //    // Create a Digest (using the proper algorithm) of the actual password
        //    // and the session ID
        //    Digest x = new Digest(textPassword, sessionID);
        //    // Compare the two digest values and see if they match
        //    if (string.Equals(x.DigestValue, userDigest.DigestValue,
        //                            StringComparison.OrdinalIgnoreCase))
        //    {
        //        // Normally this role lookup involves a database dip of some
        //        // sort to determine what roles the user has. In this
        //        // example, I'm just hardcoding them.
        //        string[] myRoles = new string[] { "Administrator", "User" };
        //        //soapBoxP.AddRoles(myRoles);
        //        //soapBoxID.SetAuthenticated();
        //    }
        //    return soapBoxP;
        //}
        //--------------------------------------------------------------------------------------------
        /// <summary>
        /// Provides a mechanism for the user manager to lookup a principal for a user at any time. This is 
        /// required by the DigestMD5 SASL algorithm. If you don't need to suppor this algorithm, then this 
        /// method isn't needed.
        /// </summary>
        /// <param name="userID">The full username to build a principal for.</param>
        /// <param name="authenticated">The authenticated state for the user</param>
        /// <returns></returns>
        public override IPrincipal GetPrincipal(JabberID userID, bool authenticated)
        {
            SoapBoxIdentity soapBoxID = new SoapBoxIdentity(userID);
            SoapBoxPrincipal soapBoxP = new SoapBoxPrincipal(soapBoxID);

            if (authenticated)
            {
                // Normally this role lookup involves a database dip of
                // some sort to determine what roles the
                // user has. In this example, I'm just hardcoding them.
                string[] myRoles = new string[] { "Administrator", "User" };
                soapBoxP.AddRoles(myRoles);

                soapBoxID.SetAuthenticated();
            }

            return soapBoxP;
        }
Esempio n. 48
0
 /// <summary>
 /// Sends the current presence information to the specified JabberID
 /// </summary>
 /// <param name="ToUser"></param>
 public void SendCurrentPresence(JabberID ToUser)
 {
     Packet p;
     if (m_currentPresence == null)
     {
         p = new UnavailableRequest();
         m_sessionMgr.BeginSend(p);
     }
     else
     {
         AvailableRequest userSpecificPresence = (AvailableRequest) m_currentPresence.Clone();
         userSpecificPresence.To = ToUser;
         userSpecificPresence.From = m_sessionMgr.LocalUser;
         p = (Packet) userSpecificPresence;
         m_sessionMgr.BeginSend(p);
     }
 }
Esempio n. 49
0
        //Handles AddButton.Click
        //The user wants to add a new user to their Roster
        //Prompt for the information.
        //Submit the new roster item and presence subscription request.
        //Refresh the local copy of the Roster from the server.
        //Send the server the current presence,
        private void AddButton_Click(object sender, System.EventArgs e)
        {
            ContactListUserAddForm addForm = new ContactListUserAddForm();
            if (addForm.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            JabberID jid = new JabberID(addForm.JabberIDTextBox.Text.Trim());
            SubscribeRequest p = new SubscribeRequest(jid);
            _SessionManager.Send(p);
        }
Esempio n. 50
0
        private void InitializeSessionManager(String userName, String password, String serverName)
        {
            try
            {
                JabberID jd = new JabberID(userName);

                // Create a session using user credentials
                ConnectionOptions opts = new ConnectionOptions(serverName, jd.Server);
                //Session session = Session.Login(userName, password, Resource, serverName, Thread.CurrentThread.CurrentCulture);
                Session session = Session.Login(jd.UserName, password, Resource, true, opts);
                m_sessionMgr = new SessionManager(session);
            }
            catch (PacketException ex)
            {
                MessageBox.Show(string.Concat("Unable to Login :"******"Login Error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            catch (StreamException ex)
            {
                MessageBox.Show(string.Concat("Unable to Login :"******"Login Error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            catch
            {
                MessageBox.Show("Login failed. Please check the username and password and try again.", "Login Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                ResetSession();
            }
        }
Esempio n. 51
0
 public MessagingWindow GetMessagingWindow(JabberID jabberId)
 {
     MessagingWindow msgWindow = null;
     string strJabberId = jabberId.JabberIDNoResource;
     if (m_ActiveChatUsers.ContainsKey(strJabberId))
     {
         msgWindow = (MessagingWindow) m_ActiveChatUsers[strJabberId];
         msgWindow.Activate();
     }
     else
     {
         msgWindow = new MessagingWindow();
         msgWindow.RemoteUserJabberId = jabberId;
         msgWindow.Show();
         m_ActiveChatUsers.Add(strJabberId, msgWindow);
     }
     return msgWindow;
 }
Esempio n. 52
0
 public MessageForm Show(JabberID RemoteUserJID)
 {
     return GetMessageWindow(RemoteUserJID);
 }
Esempio n. 53
0
 internal bool Login(string UserName, string Password, string ServerName)
 {
     InitializeSessionManager(UserName, Password, ServerName);
     if (m_sessionMgr != null)
     {
         m_currentUser = m_sessionMgr.LocalUser;
         return true;
     }
     else
     {
         return false;
     }
 }
Esempio n. 54
0
        public void process(Session session)
        {
            //Assembly assem = Assembly.LoadFrom(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\SaxExpat.dll");
            //IXmlReader reader = SaxReaderFactory.CreateReader(assem, null);
            //reader.ContentHandler = this;
            this.session = session;
            //reader.Parse(new ReaderInputSource(session.getReader()));

            XmlReader reader = XmlReader.Create(session.Reader);


            JabberServer.output.WriteLine("JIH:server version");

            reader.MoveToContent();


            try {
                do
                {
                    switch (reader.Depth)
                    {
                    case 0:
                        switch (reader.NodeType)
                        {
                        case XmlNodeType.Element:
                            if (reader.Name == "stream:stream")
                            {
                                Dictionary <String, String> atts = getAttributes(reader);
                                Packet openPacket = new Packet(null, reader.Name, reader.NamespaceURI, atts);
                                openPacket.Session = (session);
                                String from = atts["from"];
                                session.JID = (new JabberID(from));
                                packetQ.enqueue(openPacket);
                            }
                            else
                            {
                                throw new XmlException("Root node must be <stream:stream>");
                            }
                            break;

                        case XmlNodeType.EndElement:
                            Packet closePacket = new Packet("/stream:stream");
                            closePacket.Session = (session);
                            packetQ.enqueue(closePacket);
                            break;
                        }
                        break;

                    case 1:
                        switch (reader.NodeType)
                        {
                        case XmlNodeType.Element:
                            Dictionary <String, String> atts = getAttributes(reader);
                            packet         = new Packet(null, reader.Name, reader.NamespaceURI, atts);
                            packet.Session = (session);
                            if (reader.IsEmptyElement)
                            {
                                goto case XmlNodeType.EndElement;
                            }
                            break;

                        case XmlNodeType.EndElement:
                            packetQ.enqueue(packet);
                            break;
                        }
                        break;

                    default:
                        switch (reader.NodeType)
                        {
                        case XmlNodeType.Element:
                            Dictionary <String, String> atts = getAttributes(reader);
                            Packet child = new Packet(packet, reader.Name, reader.NamespaceURI, atts);
                            packet = child;
                            if (reader.IsEmptyElement)
                            {
                                goto case XmlNodeType.EndElement;
                            }
                            break;

                        case XmlNodeType.EndElement:
                            packet = packet.Parent;
                            break;

                        case XmlNodeType.Text:
                            packet.Children.Add(reader.Value);
                            break;
                        }
                        break;
                    }
                } while (reader.Read());
            } catch (Exception ex) {
                //JabberServer.output.WriteLine(ex.ToString());
                // Bilokakov problem so xml stream-ot
                // io-exception, invalid xml, zatvoren socket i sl.
                // treba da se napravi clean-up : zatvori stream </stream:stream>, zatvori socket, trgni Session object i sl.

                // Ne sekogas znaci greska : posle </stream:stream> se zatvara socket-ot i ne treba da se pravi nisto



                UserIndex userIndex = JabberServer.getUserIndex();
                if (!userIndex.containsSession(session))
                {
                    return;
                }
                //clean-up code (copied from CloseStreamHandler)
                try
                {
                    //      Log.trace("Closing session");
                    //Session session = packet.Session;

                    //session.Writer.Write("</stream:stream> ");
                    //session.Writer.Flush();

                    //notify other subscribers that user is unavailble
                    //by Marko
                    //begin
                    JabberID userid = session.getJID();

                    Packet unavailiblePacket = new Packet("presence");
                    unavailiblePacket.setFrom(userid.ToString());
                    unavailiblePacket.setAttribute("type", "unavailable");
                    userIndex.getUser(userid.User).getRoster().updateSubscribers(unavailiblePacket);
                    //it is not tested, but it should work
                    //end



                    //send groupchat presence unavailable & remove from groups
                    String jid = userid.ToString();

                    Packet presence = new Packet("presence");
                    presence.Type = "unavailable";
                    foreach (KeyValuePair <String, GroupChatManager.Group> kvp in GroupChatManager.Manager.groups)
                    {
                        GroupChatManager.Group group = kvp.Value;
                        try {
                            String nick = group.jid2nick[jid];                                       // test whether the user is in the group
                            presence.From = group.JabberID + "/" + nick;
                            GroupChatManager.Manager.removeUser(group, jid);                         // first remove then deliver so that the packet does not come back
                            GroupChatManager.Manager.deliverToGroup(group, presence);
                        } catch (Exception e) {
                        }
                    }
                    // end groupchar clean-up

                    //session.Socket.Close();
                    userIndex.removeSession(session);
                    //      Log.trace("Closed session");
                }
                catch (Exception e)
                {
                    //      Log.error("CloseStreamHandler: ",ex);
                    userIndex.removeSession(packet.Session);
                    //      Log.trace("Exception closed session");
                }
            }
        }
Esempio n. 55
0
        private void ResetSession()
        {
            m_currentUser = null;
            CurrentActiveWindow = null;
            Contacts.Clear();
            m_ActiveChatUsers.Clear();

            if (null != m_mainWindow)
            {
                m_mainWindow.Dispose();
                m_mainWindow = null;
            }
            if (m_sessionMgr != null)
            {
                m_sessionMgr.Dispose();
                m_sessionMgr = null;
            }
        }
Esempio n. 56
0
        public void JoinRoom( JabberID occupantJID)
        {
            if ( _rooms.Contains(occupantJID.ToString().ToLower()) )
            {
                ChatRoomTabPage t = (ChatRoomTabPage)_rooms[occupantJID.ToString().ToLower()];
                tabRooms.SelectedTab = t;
            }
            else
            {
                ChatRoomTabPage t = new ChatRoomTabPage(occupantJID, this, _sm);
                tabRooms.TabPages.Add(t);
                _rooms.Add(occupantJID.ToString().ToLower(), t);

                lblNotInRoom.Visible = false;

                t.LeftRoom += new ChatRoomTabPage.LeftRoomDelegate(t_LeftRoom);
                t.ChangedNickName += new ChatRoomTabPage.ChangedNickNameDelegate(t_ChangedNickName);
                t.JoinRoom();
            }
        }
Esempio n. 57
0
        //Attempts to register a user based on the information on the form.
        //RegisterInfo is collected.
        //Then the registration is attempted.
        //The response is passed back on the response paramater.
        private void RegisterUser()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                JabberID JID = new JabberID(UserNameTextBox.Text, ServerNameTextBox.Text, ResourceTextBox.Text);

                //get registration info
                RegisterInfoResponse IQRegisterInfoResponse = GetRegistrationInfo(JID);
                RegisterRequest IQRegister = new RegisterRequest(new JabberID(ServerNameTextBox.Text), JID.UserName, PasswordTextBox.Text, IQRegisterInfoResponse.Key);
                _SessionManager.Send(IQRegister, 30000);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
Esempio n. 58
0
 public void JoinRoomThreadSafe( JabberID occupantJID )
 {
     this.BeginInvoke(new JoinRoomDelegate(JoinRoom), new object[] {occupantJID});
 }
Esempio n. 59
0
        public System.IO.StreamWriter getWriter(JabberID jabberID)
        {
//			String resource = jabberID.Resource;
//			User user = getUser(jabberID.User);
            return(getUser(jabberID.getUser()).getWriter(jabberID.getResource()));
        }
Esempio n. 60
0
 protected static void HandleIncomingMessage(JabberGateway gateway, string endpointName, JabberID from, string body)
 {
     try {
         var si = Program.GetScriptInstance <Common>("Common.Script.dll");
         if (si != null)
         {
             var mdata = new ShootBlues.Script.Common.MessageData(
                 null, new Dictionary <string, object> {
                 { "__name__", "JabberMessage" },
                 { "endpoint", endpointName },
                 { "from", from.FullJabberID },
                 { "text", body }
             }
                 );
             si.OnNewMessage(gateway, mdata);
         }
     } catch (Exception ex) {
         Program.Scheduler.OnTaskError(ex);
     }
 }