Пример #1
0
 /// <summary>
 /// Constructor, used internally by the library.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="guid"></param>
 /// <param name="isFavorite"></param>
 /// <param name="nsMessageHandler"></param>
 internal ContactGroup(string name, string guid, NSMessageHandler nsMessageHandler, bool isFavorite)
 {
     this.name = name;
     this.guid = guid;
     this.isFavorite = isFavorite;
     this.nsMessageHandler = nsMessageHandler;
 }
Пример #2
0
 /// <summary>
 /// Constructor, used internally by the library.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="guid"></param>
 /// <param name="isFavorite"></param>
 /// <param name="nsMessageHandler"></param>
 internal ContactGroup(string name, string guid, NSMessageHandler nsMessageHandler, bool isFavorite)
 {
     this.name             = name;
     this.guid             = guid;
     this.isFavorite       = isFavorite;
     this.nsMessageHandler = nsMessageHandler;
 }
Пример #3
0
        internal static void RenewIfExpired(NSMessageHandler nsMessageHandler, SSOTicketType renew)
        {
            CheckCleanup();

            if (nsMessageHandler == null || nsMessageHandler.Credentials == null)
            {
                return;
            }

            string authUser     = nsMessageHandler.Credentials.Account;
            string authPassword = nsMessageHandler.Credentials.Password;

            if (String.IsNullOrEmpty(authUser) || String.IsNullOrEmpty(authPassword))
            {
                return;
            }

            string      sha256key = MSNTicket.ComputeSHA(authUser, authPassword);
            MSNTicket   ticket    = GetFromCacheOrCreateNewWithLock(sha256key, nsMessageHandler.Credentials);
            ExpiryState es        = ticket.Expired(renew);

            if (es == ExpiryState.NotExpired)
            {
                nsMessageHandler.MSNTicket = ticket;
            }
            else if (es == ExpiryState.Expired || es == ExpiryState.WillExpireSoon)
            {
                Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Re-new ticket: " + renew, "SingleSignOnManager");

                SingleSignOn sso = new SingleSignOn(nsMessageHandler, ticket.Policy);

                sso.AddAuths(renew);

                if (es == ExpiryState.WillExpireSoon)
                {
                    nsMessageHandler.MSNTicket = ticket;

                    // The ticket is in cache but it will expire soon.
                    // Do ASYNC call.
                    sso.Authenticate(ticket,
                                     delegate(object sender, EventArgs e)
                    {
                        AddToCacheWithLock(ticket);
                    },
                                     delegate(object sender, ExceptionEventArgs e)
                    {
                        DeleteFromCacheWithLock(sha256key);
                    }
                                     );
                }
                else
                {
                    // The ticket expired but we need this ticket absolutely.
                    // Do SYNC call.
                    AuthenticateRetryAndUpdateCacheSync(sso, ticket, sha256key, 3);

                    nsMessageHandler.MSNTicket = ticket;
                }
            }
        }
Пример #4
0
 public void Dispose()
 {
     if (nsMessageHandler != null)
     {
         DetachNSEvents();
         nsMessageHandler = null;
     }
 }
Пример #5
0
        public ContactList(Guid abId, Owner owner, Contact gateway, NSMessageHandler handler)
        {
            Reset();

            this.gateway          = gateway;
            this.addressBookId    = abId;
            this.nsMessageHandler = handler;
            this.owner            = owner;
        }
Пример #6
0
        protected RoutingInfo(Contact sender, Contact senderGateway, Contact receiver, Contact receiverGateway, NSMessageHandler nsMessageHandler)
        {
            Sender = sender;
            SenderGateway = senderGateway;

            Receiver = receiver;
            ReceiverGateway = receiverGateway;

            this.NSMessageHandler = nsMessageHandler;
        }
Пример #7
0
        protected RoutingInfo(Contact sender, Contact senderGateway, Contact receiver, Contact receiverGateway, NSMessageHandler nsMessageHandler)
        {
            Sender        = sender;
            SenderGateway = senderGateway;

            Receiver        = receiver;
            ReceiverGateway = receiverGateway;

            this.NSMessageHandler = nsMessageHandler;
        }
Пример #8
0
        public ShellContact(Contact coreContact, IMAddressInfoType type, string objectID, NSMessageHandler handler)
            : base(coreContact.AddressBookId, objectID, type, 0, handler)
        {
            CoreContact = coreContact;
            SetName(CoreContact.Name);
            SetNickName(CoreContact.NickName);
            SetList(RoleLists.Forward);
            PersonalMessage = CoreContact.PersonalMessage;

            CoreContact.ScreenNameChanged += new EventHandler<EventArgs>(CoreContact_ScreenNameChanged);
            CoreContact.PersonalMessageChanged += new EventHandler<EventArgs>(CoreContact_PersonalMessageChanged);
        }
Пример #9
0
        private static Contact GetGatewayFromAccountString(string accountString, NSMessageHandler nsMessageHandler)
        {
            IMAddressInfoType gatewayAddressType = IMAddressInfoType.None;
            string            gatewayAccount     = string.Empty;
            IMAddressInfoType ignoreAddressType  = IMAddressInfoType.None;
            string            ignoreAccount      = string.Empty;

            Contact.ParseFullAccount(accountString,
                                     out gatewayAddressType, out gatewayAccount,
                                     out ignoreAddressType, out ignoreAccount);

            return(GetGateway(gatewayAccount, gatewayAddressType, nsMessageHandler));
        }
Пример #10
0
        /// <summary>
        /// Sign the owner out from the specificed place.
        /// </summary>
        /// <param name="endPointID">The EndPoint guid to be signed out</param>
        public void SignoutFrom(Guid endPointID)
        {
            if (endPointID == Guid.Empty)
            {
                SignoutFromEverywhere();
                return;
            }

            if (EndPointData.ContainsKey(endPointID))
            {
                NSMessageHandler.SignoutFrom(endPointID);
            }
            else
            {
                Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, "Invalid place (signed out already): " + endPointID.ToString("B"), GetType().Name);
            }
        }
Пример #11
0
        /// <summary>
        /// Set the scene image and the scheme color for the owner.
        /// </summary>
        /// <param name="imageScene">Set this to null or the default display image if you want the default MSN scene.</param>
        /// <param name="schemeColor"></param>
        /// <returns>
        /// The result will return false if the image scene and color are the same, compared to the current one.
        /// </returns>
        public bool SetScene(Image imageScene, Color schemeColor)
        {
            if (imageScene == SceneImage.Image && schemeColor == ColorScheme)
            {
                return(false);
            }

            ColorScheme = schemeColor;
            if (imageScene != SceneImage.Image)
            {
                if (imageScene != null)
                {
                    MemoryStream sms = new MemoryStream();
                    imageScene.Save(sms, imageScene.RawFormat);

                    SceneImage = new SceneImage(NSMessageHandler.Owner.Account.ToLowerInvariant(), sms);
                }
                else
                {
                    SceneImage = new SceneImage(NSMessageHandler.Owner.Account.ToLowerInvariant(), true);
                }

                SaveOriginalSceneImageAndFireSceneImageChangedEvent(
                    new SceneImageChangedEventArgs(SceneImage, DisplayImageChangedType.TransmissionCompleted, false));
            }
            else
            {
                NSMessageHandler.ContactService.Deltas.Save(true);
            }

            if (NSMessageHandler != null)
            {
                NSMessageHandler.SetSceneData(SceneImage, ColorScheme);
            }

            return(true);
        }
Пример #12
0
        private static void ProcessDCRespInvite(SLPMessage message, NSMessageHandler ns, P2PSession startupSession)
        {
            MimeDictionary bodyValues = message.BodyValues;

            // Check the protocol
            if (bodyValues.ContainsKey("Bridge") &&
                bodyValues["Bridge"].ToString() == "TCPv1" &&
                bodyValues.ContainsKey("Listening") &&
                bodyValues["Listening"].ToString().ToLowerInvariant().IndexOf("true") >= 0)
            {
                Contact remote = ns.ContactList.GetContactWithCreate(message.FromEmailAccount, IMAddressInfoType.WindowsLive);
                Guid remoteGuid = message.FromEndPoint;

                DCNonceType dcNonceType;
                Guid remoteNonce = ParseDCNonce(message.BodyValues, out dcNonceType);
                bool hashed = (dcNonceType == DCNonceType.Sha1);
                Guid replyGuid = hashed ? remote.dcPlainKey : remoteNonce;

                IPEndPoint[] selectedPoint = SelectIPEndPoint(bodyValues, ns);

                if (selectedPoint != null && selectedPoint.Length > 0)
                {
                    P2PVersion ver = message.P2PVersion;

                    // We must connect to the remote client
                    ConnectivitySettings settings = new ConnectivitySettings();
                    settings.EndPoints = selectedPoint;
                    remote.DirectBridge = CreateDirectConnection(remote, remoteGuid, ver, settings, replyGuid, remoteNonce, hashed, ns, startupSession);

                    bool needConnectingEndpointInfo;
                    if (bodyValues.ContainsKey("NeedConnectingEndpointInfo") &&
                        bool.TryParse(bodyValues["NeedConnectingEndpointInfo"], out needConnectingEndpointInfo) &&
                        needConnectingEndpointInfo == true)
                    {
                        IPEndPoint ipep = ((TCPv1Bridge)remote.DirectBridge).LocalEndPoint;

                        string desc = "stroPdnAsrddAlanretnI4vPI";
                        char[] rev = ipep.ToString().ToCharArray();
                        Array.Reverse(rev);
                        string ipandport = new string(rev);

                        SLPRequestMessage slpResponseMessage = new SLPRequestMessage(message.Source, MSNSLPRequestMethod.ACK);
                        slpResponseMessage.Source = message.Target;
                        slpResponseMessage.Via = message.Via;
                        slpResponseMessage.CSeq = 0;
                        slpResponseMessage.CallId = Guid.Empty;
                        slpResponseMessage.MaxForwards = 0;
                        slpResponseMessage.ContentType = @"application/x-msnmsgr-transdestaddrupdate";

                        slpResponseMessage.BodyValues[desc] = ipandport;
                        slpResponseMessage.BodyValues["Nat-Trav-Msg-Type"] = "WLX-Nat-Trav-Msg-Updated-Connecting-Port";

                        P2PMessage msg = new P2PMessage(ver);
                        msg.InnerMessage = slpResponseMessage;

                        ns.SDGBridge.Send(null, remote, remoteGuid, msg);
                    }

                    return;
                }
            }

            if (startupSession != null)
                startupSession.DirectNegotiationFailed();
        }
Пример #13
0
        private static TCPv1Bridge ListenForDirectConnection(
            Contact remote,
            Guid remoteGuid,
            NSMessageHandler nsMessageHandler,
            P2PVersion ver,
            P2PSession startupSession,
            IPAddress host, int port, Guid replyGuid, Guid remoteNonce, bool hashed)
        {
            ConnectivitySettings cs = new ConnectivitySettings();
            if (nsMessageHandler.ConnectivitySettings.LocalHost == string.Empty)
            {
                cs.LocalHost = host.ToString();
                cs.LocalPort = port;
            }
            else
            {
                cs.LocalHost = nsMessageHandler.ConnectivitySettings.LocalHost;
                cs.LocalPort = nsMessageHandler.ConnectivitySettings.LocalPort;
            }

            TCPv1Bridge tcpBridge = new TCPv1Bridge(cs, ver, replyGuid, remoteNonce, hashed, startupSession, nsMessageHandler, remote, remoteGuid);

            tcpBridge.Listen(IPAddress.Parse(cs.LocalHost), cs.LocalPort);

            Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Listening on " + cs.LocalHost + ":" + cs.LocalPort.ToString(CultureInfo.InvariantCulture));

            return tcpBridge;
        }
Пример #14
0
 protected internal SingleSignOn(NSMessageHandler nsHandler, string policy)
     : this(nsHandler.Credentials.Account, nsHandler.Credentials.Password, policy)
 {
     this.nsMessageHandler = nsHandler;
 }
Пример #15
0
        internal static void Authenticate(
            NSMessageHandler nsMessageHandler,
            string policy,
            EventHandler onSuccess,
            EventHandler <ExceptionEventArgs> onError)
        {
            CheckCleanup();

            if (nsMessageHandler == null || nsMessageHandler.Credentials == null)
            {
                return;
            }

            string authUser     = nsMessageHandler.Credentials.Account;
            string authPassword = nsMessageHandler.Credentials.Password;

            if (String.IsNullOrEmpty(authUser) || String.IsNullOrEmpty(authPassword))
            {
                return;
            }

            string    sha256key = MSNTicket.ComputeSHA(authUser, authPassword);
            MSNTicket ticket    = GetFromCacheOrCreateNewWithLock(sha256key, nsMessageHandler.Credentials);

            SSOTicketType[] ssos           = (SSOTicketType[])Enum.GetValues(typeof(SSOTicketType));
            SSOTicketType   expiredtickets = SSOTicketType.None;

            foreach (SSOTicketType ssot in ssos)
            {
                if (ExpiryState.NotExpired != ticket.Expired(ssot))
                {
                    expiredtickets |= ssot;
                }
            }

            if (expiredtickets == SSOTicketType.None)
            {
                nsMessageHandler.MSNTicket = ticket;

                if (onSuccess != null)
                {
                    onSuccess(nsMessageHandler, EventArgs.Empty);
                }
            }
            else
            {
                Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Request new tickets: " + expiredtickets, "SingleSignOnManager");

                SingleSignOn sso = new SingleSignOn(nsMessageHandler, policy);
                sso.AddAuths(expiredtickets);

                // ASYNC
                if (onSuccess != null && onError != null)
                {
                    try
                    {
                        sso.Authenticate(ticket,
                                         delegate(object sender, EventArgs e)
                        {
                            try
                            {
                                AddToCacheWithLock(ticket);

                                // Check Credentials again. Owner may sign off while SSOing.
                                if (nsMessageHandler.Credentials != null &&
                                    nsMessageHandler.Credentials.Account == authUser &&
                                    nsMessageHandler.Credentials.Password == authPassword &&
                                    nsMessageHandler.IsSignedIn == false)
                                {
                                    NSMessageProcessor nsmp = nsMessageHandler.MessageProcessor as NSMessageProcessor;

                                    if (nsmp != null && nsmp.Connected)
                                    {
                                        nsMessageHandler.MSNTicket = ticket;

                                        onSuccess(nsMessageHandler, e);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                DeleteFromCacheWithLock(sha256key);
                                onError(nsMessageHandler, new ExceptionEventArgs(ex));
                            }
                        },
                                         delegate(object sender, ExceptionEventArgs e)
                        {
                            DeleteFromCacheWithLock(sha256key);
                            onError(nsMessageHandler, e);
                        });
                    }
                    catch (Exception error)
                    {
                        DeleteFromCacheWithLock(sha256key);
                        onError(nsMessageHandler, new ExceptionEventArgs(error));
                    }
                }
                else
                {
                    // SYNC
                    AuthenticateRetryAndUpdateCacheSync(sso, ticket, sha256key, 3);

                    nsMessageHandler.MSNTicket = ticket;
                }
            }
        }
Пример #16
0
 public MSNDirectoryService(NSMessageHandler nsHandler)
     : base(nsHandler)
 {
 }
Пример #17
0
        internal static void Authenticate(
            NSMessageHandler nsMessageHandler,
            string policy,
            EventHandler onSuccess,
            EventHandler<ExceptionEventArgs> onError)
        {
            CheckCleanup();

            if (nsMessageHandler == null || nsMessageHandler.Credentials == null)
                return;

            string authUser = nsMessageHandler.Credentials.Account;
            string authPassword = nsMessageHandler.Credentials.Password;

            if (String.IsNullOrEmpty(authUser) || String.IsNullOrEmpty(authPassword))
                return;

            string sha256key = MSNTicket.ComputeSHA(authUser, authPassword);
            MSNTicket ticket = GetFromCacheOrCreateNewWithLock(sha256key, nsMessageHandler.Credentials);

            SSOTicketType[] ssos = (SSOTicketType[])Enum.GetValues(typeof(SSOTicketType));
            SSOTicketType expiredtickets = SSOTicketType.None;

            foreach (SSOTicketType ssot in ssos)
            {
                if (ExpiryState.NotExpired != ticket.Expired(ssot))
                    expiredtickets |= ssot;
            }

            if (expiredtickets == SSOTicketType.None)
            {
                nsMessageHandler.MSNTicket = ticket;

                if (onSuccess != null)
                {
                    onSuccess(nsMessageHandler, EventArgs.Empty);
                }
            }
            else
            {
                Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Request new tickets: " + expiredtickets, "SingleSignOnManager");

                SingleSignOn sso = new SingleSignOn(nsMessageHandler, policy);
                sso.AddAuths(expiredtickets);

                // ASYNC
                if (onSuccess != null && onError != null)
                {
                    try
                    {
                        sso.Authenticate(ticket,
                            delegate(object sender, EventArgs e)
                            {
                                try
                                {
                                    AddToCacheWithLock(ticket);

                                    // Check Credentials again. Owner may sign off while SSOing.
                                    if (nsMessageHandler.Credentials != null &&
                                        nsMessageHandler.Credentials.Account == authUser &&
                                        nsMessageHandler.Credentials.Password == authPassword &&
                                        nsMessageHandler.IsSignedIn == false)
                                    {
                                        NSMessageProcessor nsmp = nsMessageHandler.MessageProcessor as NSMessageProcessor;

                                        if (nsmp != null && nsmp.Connected)
                                        {
                                            nsMessageHandler.MSNTicket = ticket;

                                            onSuccess(nsMessageHandler, e);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    DeleteFromCacheWithLock(sha256key);
                                    onError(nsMessageHandler, new ExceptionEventArgs(ex));
                                }
                            },
                            delegate(object sender, ExceptionEventArgs e)
                            {
                                DeleteFromCacheWithLock(sha256key);
                                onError(nsMessageHandler, e);
                            });
                    }
                    catch (Exception error)
                    {
                        DeleteFromCacheWithLock(sha256key);
                        onError(nsMessageHandler, new ExceptionEventArgs(error));
                    }
                }
                else
                {
                    // SYNC
                    AuthenticateRetryAndUpdateCacheSync(sso, ticket, sha256key, 3);

                    nsMessageHandler.MSNTicket = ticket;
                }
            }
        }
Пример #18
0
 public ContactList(string abId, Owner owner, NSMessageHandler handler)
     : this(new Guid(abId), owner, handler)
 {
 }
Пример #19
0
        private static Contact GetGatewayFromAccountString(string accountString, NSMessageHandler nsMessageHandler)
        {
            IMAddressInfoType gatewayAddressType = IMAddressInfoType.None;
            string gatewayAccount = string.Empty;
            IMAddressInfoType ignoreAddressType = IMAddressInfoType.None;
            string ignoreAccount = string.Empty;

            Contact.ParseFullAccount(accountString,
                out gatewayAddressType, out gatewayAccount,
                out ignoreAddressType, out ignoreAccount);

            return GetGateway(gatewayAccount, gatewayAddressType, nsMessageHandler);
        }
Пример #20
0
        private static IPEndPoint[] SelectIPEndPoint(MimeDictionary bodyValues, NSMessageHandler nsMessageHandler)
        {
            List<IPEndPoint> externalPoints = new List<IPEndPoint>();
            List<IPEndPoint> internalPoints = new List<IPEndPoint>();
            bool nat = false;

            #region External

            if (bodyValues.ContainsKey("IPv4External-Addrs") || bodyValues.ContainsKey("srddA-lanretxE4vPI") ||
                bodyValues.ContainsKey("IPv4ExternalAddrsAndPorts") || bodyValues.ContainsKey("stroPdnAsrddAlanretxE4vPI"))
            {
                Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Using external IP addresses");

                if (bodyValues.ContainsKey("IPv4External-Addrs"))
                {
                    string[] addrs = bodyValues["IPv4External-Addrs"].Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    string[] ports = bodyValues["IPv4External-Port"].Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    if (addrs.Length > 0 && ports.Length > 0)
                    {
                        IPAddress ip;
                        int port = 0;
                        int.TryParse(ports[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out port);

                        for (int i = 0; i < addrs.Length; i++)
                        {
                            if (IPAddress.TryParse(addrs[i], out ip))
                            {
                                if (i < ports.Length)
                                    int.TryParse(ports[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out port);

                                if (port > 0)
                                    externalPoints.Add(new IPEndPoint(ip, port));
                            }
                        }
                    }
                }
                else if (bodyValues.ContainsKey("IPv4ExternalAddrsAndPorts"))
                {
                    string[] addrsAndPorts = bodyValues["IPv4ExternalAddrsAndPorts"].Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    IPAddress ip;
                    foreach (string str in addrsAndPorts)
                    {
                        string[] addrAndPort = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        if (IPAddress.TryParse(addrAndPort[0], out ip))
                            externalPoints.Add(new IPEndPoint(ip, int.Parse(addrAndPort[1])));
                    }
                }
                else if (bodyValues.ContainsKey("srddA-lanretxE4vPI"))
                {
                    nat = true;

                    char[] revHost = bodyValues["srddA-lanretxE4vPI"].ToString().ToCharArray();
                    Array.Reverse(revHost);
                    string[] addrs = new string(revHost).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    char[] revPort = bodyValues["troP-lanretxE4vPI"].ToString().ToCharArray();
                    Array.Reverse(revPort);
                    string[] ports = new string(revPort).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    if (addrs.Length > 0 && ports.Length > 0)
                    {
                        IPAddress ip;
                        int port = 0;
                        int.TryParse(ports[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out port);

                        for (int i = 0; i < addrs.Length; i++)
                        {
                            if (IPAddress.TryParse(addrs[i], out ip))
                            {
                                if (i < ports.Length)
                                    int.TryParse(ports[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out port);

                                if (port > 0)
                                    externalPoints.Add(new IPEndPoint(ip, port));
                            }
                        }
                    }
                }
                else if (bodyValues.ContainsKey("stroPdnAsrddAlanretxE4vPI"))
                {
                    nat = true;

                    char[] rev = bodyValues["stroPdnAsrddAlanretxE4vPI"].ToString().ToCharArray();
                    Array.Reverse(rev);
                    string[] addrsAndPorts = new string(rev).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    IPAddress ip;
                    foreach (string str in addrsAndPorts)
                    {
                        string[] addrAndPort = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

                        if (IPAddress.TryParse(addrAndPort[0], out ip))
                            externalPoints.Add(new IPEndPoint(ip, int.Parse(addrAndPort[1])));
                    }
                }

                Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning,
                       String.Format("{0} external IP addresses found:", externalPoints.Count));

                foreach (IPEndPoint ipep in externalPoints)
                {
                    Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "\t" + ipep.ToString());
                }
            }

            #endregion

            #region Internal

            if (bodyValues.ContainsKey("IPv4Internal-Addrs") || bodyValues.ContainsKey("srddA-lanretnI4vPI") ||
                bodyValues.ContainsKey("IPv4InternalAddrsAndPorts") || bodyValues.ContainsKey("stroPdnAsrddAlanretnI4vPI"))
            {
                Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Using internal IP addresses");

                if (bodyValues.ContainsKey("IPv4Internal-Addrs"))
                {
                    string[] addrs = bodyValues["IPv4Internal-Addrs"].Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    string[] ports = bodyValues["IPv4Internal-Port"].Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    if (addrs.Length > 0 && ports.Length > 0)
                    {
                        IPAddress ip;
                        int port = 0;
                        int.TryParse(ports[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out port);

                        for (int i = 0; i < addrs.Length; i++)
                        {
                            if (IPAddress.TryParse(addrs[i], out ip))
                            {
                                if (i < ports.Length)
                                    int.TryParse(ports[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out port);

                                if (port > 0)
                                    internalPoints.Add(new IPEndPoint(ip, port));
                            }
                        }
                    }
                }
                else if (bodyValues.ContainsKey("IPv4InternalAddrsAndPorts"))
                {
                    string[] addrsAndPorts = bodyValues["IPv4InternalAddrsAndPorts"].Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    IPAddress ip;
                    foreach (string str in addrsAndPorts)
                    {
                        string[] addrAndPort = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        if (IPAddress.TryParse(addrAndPort[0], out ip))
                            internalPoints.Add(new IPEndPoint(ip, int.Parse(addrAndPort[1])));
                    }
                }
                else if (bodyValues.ContainsKey("srddA-lanretnI4vPI"))
                {
                    nat = true;

                    char[] revHost = bodyValues["srddA-lanretnI4vPI"].ToString().ToCharArray();
                    Array.Reverse(revHost);
                    string[] addrs = new string(revHost).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    char[] revPort = bodyValues["troP-lanretnI4vPI"].ToString().ToCharArray();
                    Array.Reverse(revPort);
                    string[] ports = new string(revPort).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    if (addrs.Length > 0 && ports.Length > 0)
                    {
                        IPAddress ip;
                        int port = 0;
                        int.TryParse(ports[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out port);

                        for (int i = 0; i < addrs.Length; i++)
                        {
                            if (IPAddress.TryParse(addrs[i], out ip))
                            {
                                if (i < ports.Length)
                                    int.TryParse(ports[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out port);

                                if (port > 0)
                                    internalPoints.Add(new IPEndPoint(ip, port));
                            }
                        }
                    }
                }
                else if (bodyValues.ContainsKey("stroPdnAsrddAlanretnI4vPI"))
                {
                    nat = true;

                    char[] rev = bodyValues["stroPdnAsrddAlanretnI4vPI"].ToString().ToCharArray();
                    Array.Reverse(rev);
                    string[] addrsAndPorts = new string(rev).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    IPAddress ip;
                    foreach (string str in addrsAndPorts)
                    {
                        string[] addrAndPort = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

                        if (IPAddress.TryParse(addrAndPort[0], out ip))
                            internalPoints.Add(new IPEndPoint(ip, int.Parse(addrAndPort[1])));
                    }
                }

                Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning,
                       String.Format("{0} internal IP addresses found:", internalPoints.Count));

                foreach (IPEndPoint ipep in internalPoints)
                {
                    Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "\t" + ipep.ToString());
                }
            }

            #endregion

            if (externalPoints.Count == 0 && internalPoints.Count == 0)
            {
                Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "Unable to find any remote IP addresses");

                // Failed
                return null;
            }

            Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Is NAT: " + nat);

            List<IPEndPoint> ret = new List<IPEndPoint>();

            // Try to find the correct IP
            byte[] localBytes = nsMessageHandler.LocalEndPoint.Address.GetAddressBytes();

            foreach (IPEndPoint ipep in internalPoints)
            {
                if (ipep.Address.AddressFamily == AddressFamily.InterNetwork)
                {
                    // This is an IPv4 address
                    // Check if the first 3 octets match our local IP address
                    // If so, make use of that address (it's on our LAN)

                    byte[] bytes = ipep.Address.GetAddressBytes();

                    if ((bytes[0] == localBytes[0]) && (bytes[1] == localBytes[1]) && (bytes[2] == localBytes[2]))
                    {
                        ret.Add(ipep);
                        break;
                    }
                }
            }

            if (ret.Count == 0)
            {
                foreach (IPEndPoint ipep in internalPoints)
                {
                    if (!ret.Contains(ipep))
                        ret.Add(ipep);
                }
            }

            foreach (IPEndPoint ipep in externalPoints)
            {
                if (!ret.Contains(ipep))
                    ret.Add(ipep);
            }

            return ret.ToArray();
        }
Пример #21
0
        internal void SyncProfileToDeltas()
        {
            if (CoreProfile.ContainsKey(CoreProfileAttributeName.PublicProfile_ResourceId))
            {
                if (NSMessageHandler.ContactService.Deltas.Profile == null)
                {
                    NSMessageHandler.ContactService.Deltas.Profile = new OwnerProfile();
                }

                NSMessageHandler.ContactService.Deltas.Profile.ResourceID = CoreProfile[CoreProfileAttributeName.PublicProfile_ResourceId].ToString();

                if (CoreProfile.ContainsKey(CoreProfileAttributeName.LastModified))
                {
                    NSMessageHandler.ContactService.Deltas.Profile.DateModified = CoreProfile[CoreProfileAttributeName.LastModified].ToString();
                }
            }


            if (CoreProfile.ContainsKey(CoreProfileAttributeName.PictureProfile_UserTileStatic_ResourceId))
            {
                NSMessageHandler.ContactService.Deltas.Profile.Photo.ResourceID = CoreProfile[CoreProfileAttributeName.PictureProfile_UserTileStatic_ResourceId].ToString();
            }

            if (CoreProfile.ContainsKey(CoreProfileAttributeName.UserTileStaticUrl))
            {
                NSMessageHandler.ContactService.Deltas.Profile.Photo.PreAthURL = CoreProfile[CoreProfileAttributeName.UserTileStaticUrl].ToString();
            }



            if (CoreProfile.ContainsKey(CoreProfileAttributeName.ExpressionProfile_ResourceId))
            {
                NSMessageHandler.ContactService.Deltas.Profile.HasExpressionProfile = true;
                if (NSMessageHandler.ContactService.Deltas.Profile.ExpressionProfile == null)
                {
                    NSMessageHandler.ContactService.Deltas.Profile.ExpressionProfile = new ProfileResource();
                }
                NSMessageHandler.ContactService.Deltas.Profile.ExpressionProfile.ResourceID = CoreProfile[CoreProfileAttributeName.ExpressionProfile_ResourceId].ToString();

                if (CoreProfile.ContainsKey(CoreProfileAttributeName.PictureProfile_UserTileStatic_ResourceId))
                {
                    NSMessageHandler.ContactService.Deltas.Profile.Photo.ResourceID = CoreProfile[CoreProfileAttributeName.PictureProfile_UserTileStatic_ResourceId].ToString();
                }



                if (CoreProfile.ContainsKey(CoreProfileAttributeName.ExpressionProfile_DisplayName_LastModified))
                {
                    NSMessageHandler.ContactService.Deltas.Profile.ExpressionProfile.DateModified = CoreProfile[CoreProfileAttributeName.ExpressionProfile_DisplayName_LastModified].ToString();
                }

                if (CoreProfile.ContainsKey(CoreProfileAttributeName.ExpressionProfile_PersonalStatus))
                {
                    NSMessageHandler.ContactService.Deltas.Profile.PersonalMessage = CoreProfile[CoreProfileAttributeName.ExpressionProfile_PersonalStatus].ToString();
                    PersonalMessage newPersonalMessage = PersonalMessage == null ? new PersonalMessage(NSMessageHandler.ContactService.Deltas.Profile.PersonalMessage) : PersonalMessage;
                    newPersonalMessage.Message = NSMessageHandler.ContactService.Deltas.Profile.PersonalMessage;
                    PersonalMessage            = newPersonalMessage;
                }
            }

            NSMessageHandler.ContactService.Deltas.Profile.DisplayName = Name;
            NSMessageHandler.ContactService.Deltas.Save(true);

            if (CoreProfile.ContainsKey(CoreProfileAttributeName.UserTileStaticUrl))
            {
                NSMessageHandler.StorageService.SyncUserTile(CoreProfile[CoreProfileAttributeName.UserTileStaticUrl].ToString(), true,
                                                             delegate(object param)
                {
                    SerializableMemoryStream ms = param as SerializableMemoryStream;
                    if (ms != null)
                    {
                        NSMessageHandler.ContactService.Deltas.Profile.Photo.DisplayImage = ms;
                        NSMessageHandler.ContactService.Deltas.Save(true);
                    }

                    Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Get owner's display image from: " + CoreProfile[CoreProfileAttributeName.UserTileStaticUrl] +
                                      " succeeded.");
                },
                                                             delegate(object param)
                {
                    Exception ex = param as Exception;
                    if (ex != null)
                    {
                        Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "An error occurred while getting owner's display image from:" +
                                          CoreProfile[CoreProfileAttributeName.UserTileStaticUrl] + "\r\n" +
                                          ex.Message);
                    }
                }
                                                             );
            }

            if (Name != PreferredName)
            {
                try
                {
                    NSMessageHandler.SetScreenName(PreferredName);
                    SetName(PreferredName);
                }
                catch (Exception ex)
                {
                    Trace.WriteLineIf(Settings.TraceSwitch.TraceError, ex.Message);
                }
            }
        }
Пример #22
0
 public Owner(Guid abId, string account, long cid, NSMessageHandler handler)
     : base(abId, account, IMAddressInfoType.WindowsLive, cid, handler)
 {
 }
Пример #23
0
 public Owner(string abId, string account, long cid, NSMessageHandler handler)
     : this(new Guid(abId), account, cid, handler)
 {
 }
Пример #24
0
        internal static RoutingInfo FromMultiMimeMessage(MultiMimeMessage multiMimeMessage, NSMessageHandler nsMessageHandler)
        {
            IMAddressInfoType senderAccountAddressType;
            string senderAccount = string.Empty;
            IMAddressInfoType senderGatewayAccountAddressType;
            string senderGatewayAccount = string.Empty;

            IMAddressInfoType receiverAccountAddressType;
            string receiverAccount = string.Empty;
            IMAddressInfoType receiverGatewayAccountAddressType;
            string receiverGatewayAccount = string.Empty;

            if ((false == Contact.ParseFullAccount(multiMimeMessage.From.ToString(),
                out senderAccountAddressType, out senderAccount,
                out senderGatewayAccountAddressType, out senderGatewayAccount))
                ||
                (false == Contact.ParseFullAccount(multiMimeMessage.To.ToString(),
                out receiverAccountAddressType, out receiverAccount,
                out receiverGatewayAccountAddressType, out receiverGatewayAccount)))
            {
                Trace.WriteLineIf(Settings.TraceSwitch.TraceError,
                    "Cannot parse sender or receiver from message: " + multiMimeMessage.From.ToString() + "|" + multiMimeMessage.To.ToString());

                return null;
            }

            Contact sender = null;
            Contact senderGateway = null;

            Contact receiver = null;
            Contact receiverGateway = null;

            if (multiMimeMessage.From.HasAttribute("via"))
                senderGateway = GetGatewayFromAccountString(multiMimeMessage.From["via"], nsMessageHandler);

            if (senderGateway == null && multiMimeMessage.RoutingHeaders.ContainsKey(MIMERoutingHeaders.Via)) //The gateway is sender gateway
                senderGateway = GetGatewayFromAccountString(multiMimeMessage.RoutingHeaders[MIMERoutingHeaders.Via], nsMessageHandler);

            if (multiMimeMessage.To.HasAttribute("via"))
                receiverGateway = GetGatewayFromAccountString(multiMimeMessage.To["via"], nsMessageHandler);

            bool fromMyself = (senderAccount == nsMessageHandler.Owner.Account && senderAccountAddressType == IMAddressInfoType.WindowsLive);

            if (!Contact.IsSpecialGatewayType(senderAccountAddressType))
            {
                if (senderGateway == null)
                    sender = fromMyself ? nsMessageHandler.Owner : nsMessageHandler.ContactList.GetContactWithCreate(senderAccount, senderAccountAddressType);
                else
                {
                    // For facebook, we might need to use GetContact instead of GetContactWithCreate,
                    // that's the official client's behavior. Actually we will get all status notification from
                    // our facebook contacts, however, WLM only display those guys who are also our windows live
                    // contact. For now, those facebook contact doesn't add us as an WLM contact will also show up
                    // in MSNPSharp, their name is the same with the account - all are numbers. I think it doesn't
                    // harm so far, so keep it like this is reasonable, but might change in the future.
                    sender = senderGateway.ContactList.GetContactWithCreate(senderAccount, senderAccountAddressType);
                }
            }
            else
            {
                sender = GetGateway(senderAccount, senderAccountAddressType, nsMessageHandler);
            }

            bool sentToMe = (receiverAccount == nsMessageHandler.Owner.Account && receiverAccountAddressType == IMAddressInfoType.WindowsLive);

            if (!Contact.IsSpecialGatewayType(receiverAccountAddressType))
            {
                if (receiverGateway == null)
                    receiver = sentToMe ? nsMessageHandler.Owner : nsMessageHandler.ContactList.GetContactWithCreate(receiverAccount, receiverAccountAddressType);
                else
                {
                    receiver = receiverGateway.ContactList.GetContactWithCreate(receiverAccount, receiverAccountAddressType);
                }
            }
            else
            {
                receiver = GetGateway(receiverAccount, receiverAccountAddressType, nsMessageHandler);
            }

            RoutingInfo routingInfo = new RoutingInfo(sender, senderGateway, receiver, receiverGateway, nsMessageHandler);
            routingInfo.SenderEndPointID = GetEPID(multiMimeMessage.From);
            routingInfo.SenderAccount = senderAccount;
            routingInfo.SenderType = senderAccountAddressType;

            routingInfo.ReceiverEndPointID = GetEPID(multiMimeMessage.To);
            routingInfo.ReceiverAccount = receiverAccount;
            routingInfo.ReceiverType = receiverAccountAddressType;

            return routingInfo;
        }
Пример #25
0
        private static Contact GetGateway(string gatewayAccount, IMAddressInfoType gatewayType, NSMessageHandler nsMessageHandler)
        {
            Contact gateWay = null;

            if (gatewayType == IMAddressInfoType.Circle)
            {
                gateWay = nsMessageHandler.ContactList.GetCircle(gatewayAccount);
            }
            else if (gatewayType == IMAddressInfoType.TemporaryGroup)
            {
                gateWay = nsMessageHandler.GetMultiparty(gatewayAccount);
            }
            else
            {
                gateWay = nsMessageHandler.ContactList.GetContact(gatewayAccount, gatewayType);
            }

            return(gateWay);
        }
Пример #26
0
 public ContactList(Guid abId, Owner owner, NSMessageHandler handler)
     : this(abId, owner, null, handler)
 {
 }
Пример #27
0
 protected internal SingleSignOn(NSMessageHandler nsHandler, string policy)
     : this(nsHandler.Credentials.Account, nsHandler.Credentials.Password, policy)
 {
     this.nsMessageHandler = nsHandler;
 }
Пример #28
0
 public ContactList(NSMessageHandler handler)
     : this(WebServiceConstants.MessengerIndividualAddressBookId, null, handler)
 {
 }
Пример #29
0
 protected MSNService(NSMessageHandler nsHandler)
 {
     nsMessageHandler = nsHandler;
 }
Пример #30
0
 public ShellContact(Guid addressBookID, string objectID, IMAddressInfoType type, NSMessageHandler handler)
     : base(addressBookID, objectID, type, 0, handler)
 {
     SetList(RoleLists.Forward);
 }
Пример #31
0
 protected internal Contact(string abId, string account, IMAddressInfoType cliType, long cid, NSMessageHandler handler)
     : this(new Guid(abId), account, cliType, cid, handler)
 {
 }
Пример #32
0
 internal ContactGroupList(NSMessageHandler handler)
 {
     nsMessageHandler = handler;
 }
Пример #33
0
        private static string ConnectionType(NSMessageHandler nsMessageHandler, out int netId)
        {
            string connectionType = "Unknown-Connect";
            netId = 0;
            IPEndPoint localEndPoint = nsMessageHandler.LocalEndPoint;
            IPEndPoint externalEndPoint = nsMessageHandler.ExternalEndPoint;

            if (localEndPoint == null || externalEndPoint == null)
            {
            }
            else
            {
                netId = BitConverter.ToInt32(localEndPoint.Address.GetAddressBytes(), 0);

                if (Settings.DisableP2PDirectConnections)
                {
                    connectionType = "Firewall";
                }
                else
                {
                    if (localEndPoint.Address.Equals(externalEndPoint.Address))
                    {
                        if (localEndPoint.Port == externalEndPoint.Port)
                            connectionType = "Direct-Connect";
                        else
                            connectionType = "Port-Restrict-NAT";
                    }
                    else
                    {
                        if (localEndPoint.Port == externalEndPoint.Port)
                        {
                            netId = 0;
                            connectionType = "IP-Restrict-NAT";
                        }
                        else
                            connectionType = "Symmetric-NAT";
                    }
                }
            }

            return connectionType;
        }
Пример #34
0
        internal static RoutingInfo FromMultiMimeMessage(MultiMimeMessage multiMimeMessage, NSMessageHandler nsMessageHandler)
        {
            IMAddressInfoType senderAccountAddressType;
            string            senderAccount = string.Empty;
            IMAddressInfoType senderGatewayAccountAddressType;
            string            senderGatewayAccount = string.Empty;

            IMAddressInfoType receiverAccountAddressType;
            string            receiverAccount = string.Empty;
            IMAddressInfoType receiverGatewayAccountAddressType;
            string            receiverGatewayAccount = string.Empty;

            if ((false == Contact.ParseFullAccount(multiMimeMessage.From.ToString(),
                                                   out senderAccountAddressType, out senderAccount,
                                                   out senderGatewayAccountAddressType, out senderGatewayAccount))
                ||
                (false == Contact.ParseFullAccount(multiMimeMessage.To.ToString(),
                                                   out receiverAccountAddressType, out receiverAccount,
                                                   out receiverGatewayAccountAddressType, out receiverGatewayAccount)))
            {
                Trace.WriteLineIf(Settings.TraceSwitch.TraceError,
                                  "Cannot parse sender or receiver from message: " + multiMimeMessage.From.ToString() + "|" + multiMimeMessage.To.ToString());

                return(null);
            }

            Contact sender        = null;
            Contact senderGateway = null;

            Contact receiver        = null;
            Contact receiverGateway = null;

            if (multiMimeMessage.From.HasAttribute("via"))
            {
                senderGateway = GetGatewayFromAccountString(multiMimeMessage.From["via"], nsMessageHandler);
            }

            if (senderGateway == null && multiMimeMessage.RoutingHeaders.ContainsKey(MIMERoutingHeaders.Via)) //The gateway is sender gateway
            {
                senderGateway = GetGatewayFromAccountString(multiMimeMessage.RoutingHeaders[MIMERoutingHeaders.Via], nsMessageHandler);
            }

            if (multiMimeMessage.To.HasAttribute("via"))
            {
                receiverGateway = GetGatewayFromAccountString(multiMimeMessage.To["via"], nsMessageHandler);
            }

            bool fromMyself = (senderAccount == nsMessageHandler.Owner.Account && senderAccountAddressType == IMAddressInfoType.WindowsLive);

            if (!Contact.IsSpecialGatewayType(senderAccountAddressType))
            {
                if (senderGateway == null)
                {
                    sender = fromMyself ? nsMessageHandler.Owner : nsMessageHandler.ContactList.GetContactWithCreate(senderAccount, senderAccountAddressType);
                }
                else
                {
                    // For facebook, we might need to use GetContact instead of GetContactWithCreate,
                    // that's the official client's behavior. Actually we will get all status notification from
                    // our facebook contacts, however, WLM only display those guys who are also our windows live
                    // contact. For now, those facebook contact doesn't add us as an WLM contact will also show up
                    // in MSNPSharp, their name is the same with the account - all are numbers. I think it doesn't
                    // harm so far, so keep it like this is reasonable, but might change in the future.
                    sender = senderGateway.ContactList.GetContactWithCreate(senderAccount, senderAccountAddressType);
                }
            }
            else
            {
                sender = GetGateway(senderAccount, senderAccountAddressType, nsMessageHandler);
            }

            bool sentToMe = (receiverAccount == nsMessageHandler.Owner.Account && receiverAccountAddressType == IMAddressInfoType.WindowsLive);

            if (!Contact.IsSpecialGatewayType(receiverAccountAddressType))
            {
                if (receiverGateway == null)
                {
                    receiver = sentToMe ? nsMessageHandler.Owner : nsMessageHandler.ContactList.GetContactWithCreate(receiverAccount, receiverAccountAddressType);
                }
                else
                {
                    receiver = receiverGateway.ContactList.GetContactWithCreate(receiverAccount, receiverAccountAddressType);
                }
            }
            else
            {
                receiver = GetGateway(receiverAccount, receiverAccountAddressType, nsMessageHandler);
            }

            RoutingInfo routingInfo = new RoutingInfo(sender, senderGateway, receiver, receiverGateway, nsMessageHandler);

            routingInfo.SenderEndPointID = GetEPID(multiMimeMessage.From);
            routingInfo.SenderAccount    = senderAccount;
            routingInfo.SenderType       = senderAccountAddressType;

            routingInfo.ReceiverEndPointID = GetEPID(multiMimeMessage.To);
            routingInfo.ReceiverAccount    = receiverAccount;
            routingInfo.ReceiverType       = receiverAccountAddressType;

            return(routingInfo);
        }
Пример #35
0
 public WhatsUpService(NSMessageHandler nsHandler)
     : base(nsHandler)
 {
 }
Пример #36
0
        protected P2PApplication(P2PVersion ver, Contact remote, Guid remoteEP)
        {
            if (ver == P2PVersion.None)
                throw new InvalidOperationException(remote.ToString() + " doesn't support P2P");

            this.version = ver;

            this.local = remote.NSMessageHandler.Owner;
            this.localEP = NSMessageHandler.MachineGuid;

            this.remote = remote;
            this.remoteEP = remoteEP;

            this.nsMessageHandler = remote.NSMessageHandler;

            Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo,
                "Application created: " + ver, GetType().Name);
        }
Пример #37
0
 public MSNStorageService(NSMessageHandler nsHandler)
     : base(nsHandler)
 {
 }
Пример #38
0
 protected internal Contact(string account, IMAddressInfoType cliType, NSMessageHandler handler)
     : this(Guid.Empty, account, cliType, 0, handler)
 {
 }
Пример #39
0
        /// <summary>
        /// Creates a new session initiated locally and prepares the invitation message.
        /// The next step must be Invite().
        /// </summary>
        public P2PSession(P2PApplication app)
        {
            p2pApplication = app;
            version = app.P2PVersion;

            localContact = app.Local;
            remoteContact = app.Remote;
            localContactEndPointID = NSMessageHandler.MachineGuid;
            remoteContactEndPointID = app.Remote.SelectBestEndPointId();

            nsMessageHandler = app.Local.NSMessageHandler;
            sessionId = (uint)random.Next(50000, int.MaxValue);

            // These 2 fields are set when optimal bridge found.
            localBaseIdentifier = 0;
            localIdentifier = 0;

            invitation = new SLPRequestMessage(RemoteContactEPIDString, MSNSLPRequestMethod.INVITE);
            invitation.Target = RemoteContactEPIDString;
            invitation.Source = LocalContactEPIDString;
            invitation.ContentType = "application/x-msnmsgr-sessionreqbody";
            invitation.BodyValues["SessionID"] = SessionId.ToString(System.Globalization.CultureInfo.InvariantCulture);
            app.SetupInviteMessage(invitation);

            app.P2PSession = this; // Register events
            remoteContact.DirectBridgeEstablished += RemoteDirectBridgeEstablished;

            Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo,
                String.Format("{0} created (Initiated locally)", SessionId), GetType().Name);

            status = P2PSessionStatus.WaitingForRemote;
            // Next step must be: Invite()
        }
Пример #40
0
        protected internal Contact(Guid abId, string acc, IMAddressInfoType cliType, long cid, NSMessageHandler handler)
        {
            GenerateNewDCKeys();

            NSMessageHandler = handler;
            addressBookId = abId;
            account = acc.ToLowerInvariant();
            clientType = cliType;
            cId = cid;

            SetName(account);
            siblingString = ClientType.ToString() + ":" + account;
            hash = MakeHash(Account, ClientType);

            if (NSMessageHandler != null)
            {
                NSMessageHandler.ContactManager.Add(this);
            }

            displayImage = DisplayImage.CreateDefaultImage(Account);
            sceneImage = SceneImage.CreateDefaultImage(Account);
            personalMessage = new PersonalMessage();

            if (Account == RemoteNetworkGateways.FaceBookGatewayAccount ||
                Account == RemoteNetworkGateways.LinkedInGateway)
            {
                IsHiddenContact = true;
            }
        }
Пример #41
0
        /// <summary>
        /// Creates a new session initiated remotely. If the application cannot be handled, decline message will be sent.
        /// The application will handle all messages automatically and no user interaction is required if AutoAccept is true.
        /// If AutoAccept is false, <see cref="P2PHandler.InvitationReceived"/> event will be fired.
        /// </summary>
        public P2PSession(SLPRequestMessage slp, P2PMessage msg, NSMessageHandler ns, P2PBridge bridge)
        {
            nsMessageHandler = ns;
            invitation = slp;
            version = slp.P2PVersion;

            if (version == P2PVersion.P2PV1)
            {
                localContact = (slp.ToEmailAccount == ns.Owner.Account) ?
                    ns.Owner : ns.ContactList.GetContactWithCreate(slp.ToEmailAccount, IMAddressInfoType.WindowsLive);

                remoteContact = ns.ContactList.GetContactWithCreate(slp.FromEmailAccount, IMAddressInfoType.WindowsLive);
            }
            else
            {
                localContact = (slp.ToEmailAccount == ns.Owner.Account) ?
                    ns.Owner : ns.ContactList.GetContactWithCreate(slp.ToEmailAccount, IMAddressInfoType.WindowsLive);
                localContactEndPointID = slp.ToEndPoint;

                remoteContact = ns.ContactList.GetContactWithCreate(slp.FromEmailAccount, IMAddressInfoType.WindowsLive);
                remoteContactEndPointID = slp.FromEndPoint;
            }

            if (!uint.TryParse(slp.BodyValues["SessionID"].Value, out sessionId))
            {
                Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning,
                    "Can't parse SessionID: " + SessionId, GetType().Name);
            }

            p2pBridge = bridge;
            localBaseIdentifier = bridge.SequenceId;
            localIdentifier = localBaseIdentifier;
            status = P2PSessionStatus.WaitingForLocal;

            Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo,
              String.Format("{0} created (Initiated remotely)", SessionId), GetType().Name);

            remoteContact.DirectBridgeEstablished += RemoteDirectBridgeEstablished;

            if (msg != null)
            {
                // Set remote baseID
                remoteBaseIdentifier = msg.Header.Identifier;
                remoteIdentifier = remoteBaseIdentifier;

                if (version == P2PVersion.P2PV2)
                    remoteIdentifier += msg.V2Header.MessageSize;
            }

            // Create application based on invitation
            uint appId = slp.BodyValues.ContainsKey("AppID") ? uint.Parse(slp.BodyValues["AppID"].Value) : 0;
            Guid eufGuid = slp.BodyValues.ContainsKey("EUF-GUID") ? new Guid(slp.BodyValues["EUF-GUID"].Value) : Guid.Empty;
            p2pApplication = P2PApplication.CreateInstance(eufGuid, appId, this);

            if (p2pApplication != null && p2pApplication.ValidateInvitation(invitation))
            {
                if (p2pApplication.AutoAccept)
                {
                    Accept();
                }
                else
                {
                    ns.P2PHandler.OnInvitationReceived(new P2PSessionEventArgs(this));
                }
            }
            else
            {
                Decline();
            }
        }
Пример #42
0
        private static TCPv1Bridge CreateDirectConnection(Contact remote, Guid remoteGuid, P2PVersion ver, ConnectivitySettings cs, Guid replyGuid, Guid remoteNonce, bool hashed, NSMessageHandler nsMessageHandler, P2PSession startupSession)
        {
            string[] points = new string[cs.EndPoints.Length];

            for (int i = 0; i < points.Length; i++)
            {
                points[i] = cs.EndPoints[i].ToString();
            }

            TCPv1Bridge tcpBridge = new TCPv1Bridge(cs, ver, replyGuid, remoteNonce, hashed, startupSession, nsMessageHandler, remote, remoteGuid);

            Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Trying to setup direct connection with remote hosts " + string.Join(",", points));

            tcpBridge.Connect();

            return tcpBridge;
        }
Пример #43
0
        public ShellContact(Contact coreContact, IMAddressInfoType type, string objectID, NSMessageHandler handler)
            : base(coreContact.AddressBookId, objectID, type, 0, handler)
        {
            CoreContact = coreContact;

            SetName(CoreContact.Name);
            SetNickName(CoreContact.NickName);
            SetList(RoleLists.Forward);
            PersonalMessage = CoreContact.PersonalMessage;

            CoreContact.ScreenNameChanged      += new EventHandler <EventArgs>(CoreContact_ScreenNameChanged);
            CoreContact.PersonalMessageChanged += new EventHandler <EventArgs>(CoreContact_PersonalMessageChanged);
        }
Пример #44
0
        private static void ProcessDCReqInvite(SLPMessage message, NSMessageHandler ns, P2PSession startupSession)
        {
            if (startupSession != null && startupSession.Bridge != null &&
                startupSession.Bridge is TCPv1Bridge)
            {
                return; // We are using a dc bridge already. Don't allow second one.
            }

            if (message.BodyValues.ContainsKey("Bridges") &&
                message.BodyValues["Bridges"].ToString().Contains("TCPv1"))
            {
                SLPStatusMessage slpMessage = new SLPStatusMessage(message.Source, 200, "OK");
                slpMessage.Target = message.Source;
                slpMessage.Source = message.Target;
                slpMessage.Branch = message.Branch;
                slpMessage.CSeq = 1;
                slpMessage.CallId = message.CallId;
                slpMessage.MaxForwards = 0;
                slpMessage.ContentType = "application/x-msnmsgr-transrespbody";
                slpMessage.BodyValues["Bridge"] = "TCPv1";

                Guid remoteGuid = message.FromEndPoint;
                Contact remote = ns.ContactList.GetContactWithCreate(message.FromEmailAccount, IMAddressInfoType.WindowsLive);

                DCNonceType dcNonceType;
                Guid remoteNonce = ParseDCNonce(message.BodyValues, out dcNonceType);
                if (remoteNonce == Guid.Empty) // Plain
                    remoteNonce = remote.dcPlainKey;

                bool hashed = (dcNonceType == DCNonceType.Sha1);
                string nonceFieldName = hashed ? "Hashed-Nonce" : "Nonce";
                Guid myHashedNonce = hashed ? remote.dcLocalHashedNonce : remoteNonce;
                Guid myPlainNonce = remote.dcPlainKey;
                if (dcNonceType == DCNonceType.Sha1)
                {
                    // Remote contact supports Hashed-Nonce
                    remote.dcType = dcNonceType;
                    remote.dcRemoteHashedNonce = remoteNonce;
                }
                else
                {
                    remote.dcType = DCNonceType.Plain;
                    myPlainNonce = remote.dcPlainKey = remote.dcLocalHashedNonce = remote.dcRemoteHashedNonce = remoteNonce;
                }

                // Find host by name
                IPAddress ipAddress = ns.LocalEndPoint.Address;
                int port;

                P2PVersion ver = message.P2PVersion;

                if (Settings.DisableP2PDirectConnections ||
                    false == ipAddress.Equals(ns.ExternalEndPoint.Address) ||
                    (0 == (port = GetNextDirectConnectionPort(ipAddress))))
                {
                    slpMessage.BodyValues["Listening"] = "false";
                    slpMessage.BodyValues[nonceFieldName] = Guid.Empty.ToString("B").ToUpper(CultureInfo.InvariantCulture);
                }
                else
                {
                    // Let's listen
                    remote.DirectBridge = ListenForDirectConnection(remote, remoteGuid, ns, ver, startupSession, ipAddress, port, myPlainNonce, remoteNonce, hashed);

                    slpMessage.BodyValues["Listening"] = "true";
                    slpMessage.BodyValues["Capabilities-Flags"] = "1";
                    slpMessage.BodyValues["IPv6-global"] = string.Empty;
                    slpMessage.BodyValues["Nat-Trav-Msg-Type"] = "WLX-Nat-Trav-Msg-Direct-Connect-Resp";
                    slpMessage.BodyValues["UPnPNat"] = "false";

                    slpMessage.BodyValues["NeedConnectingEndpointInfo"] = "true";

                    slpMessage.BodyValues["Conn-Type"] = "Direct-Connect";
                    slpMessage.BodyValues["TCP-Conn-Type"] = "Direct-Connect";
                    slpMessage.BodyValues[nonceFieldName] = myHashedNonce.ToString("B").ToUpper(CultureInfo.InvariantCulture);
                    slpMessage.BodyValues["IPv4Internal-Addrs"] = ipAddress.ToString();
                    slpMessage.BodyValues["IPv4Internal-Port"] = port.ToString(CultureInfo.InvariantCulture);

                    // check if client is behind firewall (NAT-ted)
                    // if so, send the public ip also the client, so it can try to connect to that ip
                    if (!ns.ExternalEndPoint.Address.Equals(ns.LocalEndPoint.Address))
                    {
                        slpMessage.BodyValues["IPv4External-Addrs"] = ns.ExternalEndPoint.Address.ToString();
                        slpMessage.BodyValues["IPv4External-Port"] = port.ToString(CultureInfo.InvariantCulture);
                    }
                }

                P2PMessage p2pMessage = new P2PMessage(ver);
                p2pMessage.InnerMessage = slpMessage;

                if (ver == P2PVersion.P2PV2)
                {
                    p2pMessage.V2Header.TFCombination = TFCombination.First;
                }
                else if (ver == P2PVersion.P2PV1)
                {
                    p2pMessage.V1Header.Flags = P2PFlag.MSNSLPInfo;
                }

                if (startupSession != null)
                {
                    startupSession.SetupDCTimer();
                    startupSession.Bridge.Send(null, startupSession.Remote, startupSession.RemoteContactEndPointID, p2pMessage);
                }
                else
                {
                    ns.SDGBridge.Send(null, remote, remoteGuid, p2pMessage);
                }
            }
            else
            {
                if (startupSession != null)
                    startupSession.DirectNegotiationFailed();
            }
        }
Пример #45
0
 public ShellContact(Guid addressBookID, string objectID, IMAddressInfoType type, NSMessageHandler handler)
     : base(addressBookID, objectID, type, 0, handler)
 {
     SetList(RoleLists.Forward);
 }
Пример #46
0
        private static void ProcessDirectAddrUpdate(
            SLPMessage message,
            NSMessageHandler nsMessageHandler,
            P2PSession startupSession)
        {
            Contact from = nsMessageHandler.ContactList.GetContactWithCreate(message.FromEmailAccount, IMAddressInfoType.WindowsLive);
            IPEndPoint[] ipEndPoints = SelectIPEndPoint(message.BodyValues, nsMessageHandler);

            if (from.DirectBridge != null && ipEndPoints != null && ipEndPoints.Length > 0)
            {
                ((TCPv1Bridge)from.DirectBridge).OnDestinationAddressUpdated(new DestinationAddressUpdatedEventArgs(ipEndPoints));
            }
        }
Пример #47
0
 public Owner(string abId, string account, long cid, NSMessageHandler handler)
     : this(new Guid(abId), account, cid, handler)
 {
 }
Пример #48
0
        internal static void ProcessDirectInvite(SLPMessage slp, NSMessageHandler ns, P2PSession startupSession)
        {
            switch (slp.ContentType)
            {
                case "application/x-msnmsgr-transreqbody":
                    ProcessDCReqInvite(slp, ns, startupSession);
                    break;

                case "application/x-msnmsgr-transrespbody":
                    ProcessDCRespInvite(slp, ns, startupSession);
                    break;

                case "application/x-msnmsgr-transdestaddrupdate":
                    ProcessDirectAddrUpdate(slp, ns, startupSession);
                    break;
            }
        }
Пример #49
0
 public Owner(Guid abId, string account, long cid, NSMessageHandler handler)
     : base(abId, account, IMAddressInfoType.WindowsLive, cid, handler)
 {
 }
Пример #50
0
        private static Contact GetGateway(string gatewayAccount, IMAddressInfoType gatewayType, NSMessageHandler nsMessageHandler)
        {
            Contact gateWay = null;

            if (gatewayType == IMAddressInfoType.Circle)
            {
                gateWay = nsMessageHandler.ContactList.GetCircle(gatewayAccount);
            }
            else if (gatewayType == IMAddressInfoType.TemporaryGroup)
            {
                gateWay = nsMessageHandler.GetMultiparty(gatewayAccount);
            }
            else
            {
                gateWay = nsMessageHandler.ContactList.GetContact(gatewayAccount, gatewayType);
            }

            return gateWay;
        }
Пример #51
0
 public void Dispose()
 {
     if (nsMessageHandler != null)
     {
         DetachNSEvents();
         nsMessageHandler = null;
     }
 }
Пример #52
0
        /// <summary>
        /// Constructor
        /// </summary>
        public MessageManager(NSMessageHandler nsHandler)
        {
            this.nsMessageHandler = nsHandler;

            AttachNSEvents();
        }
Пример #53
0
 internal ContactGroupList(NSMessageHandler handler)
 {
     nsMessageHandler = handler;
 }
Пример #54
0
 public ContactManager(NSMessageHandler handler)
 {
     nsMessageHandler = handler;
 }
Пример #55
0
 public ContactService(NSMessageHandler nsHandler)
     : base(nsHandler)
 {
 }
Пример #56
0
 public MSNStorageService(NSMessageHandler nsHandler)
     : base(nsHandler)
 {
 }
Пример #57
0
        /// <summary>
        /// Constructor
        /// </summary>
        public MessageManager(NSMessageHandler nsHandler)
        {
            this.nsMessageHandler = nsHandler;

            AttachNSEvents();
        }