Exemplo n.º 1
0
        /// <summary>
        /// Starts publishing the airplay service over Bonjour so that iOS devices can find it.
        /// This only advertises the service, Bonjour doesn't deal with the connections themselves. The connections are dealt with in the Server class.
        /// </summary>
        private void DoPublish()
        {
            publishService = new NetService(domain, type, name, port);

            //add delegates for success/false
            publishService.DidPublishService    += publishService_DidPublishService;
            publishService.DidNotPublishService += publishService_DidNotPublishService;

            //add txtrecord, which gives details of the service. For now we'll just put the version number
            System.Collections.Hashtable dict = new System.Collections.Hashtable();

            /*  dict.Add("deviceid", "FF:FF:FF:FF:FF:FF");
             * dict.Add("features", "0x77");
             * dict.Add("model", "AppleTV2,1");
             * dict.Add("srcvers", "101.10");*/

            dict.Add("deviceid", "58:55:CA:1A:E2:88");
            dict.Add("features", "0x39f7");
            dict.Add("model", "AppleTV2,1");
            dict.Add("protovers", "1.0");
            dict.Add("srcvers", "120.2");

            publishService.TXTRecordData = NetService.DataFromTXTRecordDictionary(dict);

            publishService.Publish();
        }
Exemplo n.º 2
0
        protected override NetService GetNetService()
        {
            Logger.Debug("RAOPEmitter: {0}, {1}, {2}", name, identifier, port);
            Dictionary <string, object> txtRecord = new Dictionary <string, object>();

            txtRecord.Add("txtvers", "1");
            txtRecord.Add("pw", pass.ToString());
            txtRecord.Add("sr", "44100");
            txtRecord.Add("ss", "16");
            txtRecord.Add("ch", "2");
            txtRecord.Add("tp", "UDP");
            txtRecord.Add("sm", "false");
            txtRecord.Add("sv", "false");
            txtRecord.Add("ek", "1");
            txtRecord.Add("et", "0,1");
            txtRecord.Add("cn", "0,1");
            txtRecord.Add("vn", "3");
            txtRecord.Add("md", "0,1,2");
            txtRecord.Add("da", "true");
            txtRecord.Add("am", model);
            txtRecord.Add("vs", "130.14");

            NetService service = new NetService("", TYPE, identifier + "@" + name, port);

            service.TXTRecordData = NetService.DataFromTXTRecordDictionary(txtRecord);
            return(service);
        }
Exemplo n.º 3
0
        private void PrepareService()
        {
            m_publishService = new NetService(DOMAIN, TYPE, m_name, SERVICE_PORT);


            string macAddr = Utils.GetMacAddress();

            // AirPlay now shows everywhere :) not only in "Photos.app" and "Videos.app"
            var dicTXTRecord = new Dictionary <string, string>();

            dicTXTRecord.Add("model", "AppleTV2,1");

            dicTXTRecord.Add("deviceid", "58:55:CA:06:BD:9E");
            //dicTXTRecord.Add("deviceid", macAddr);

            // Bit field -> http://nto.github.com/AirPlay.html#servicediscovery-airplayservice
            dicTXTRecord.Add("features", "0x39f7");

            dicTXTRecord.Add("protovers", "1.0");
            dicTXTRecord.Add("srcvers", "101.10");

            // set to 1 to enable
            dicTXTRecord.Add("pw", "0");
            m_publishService.TXTRecordData = NetService.DataFromTXTRecordDictionary(dicTXTRecord);


            //add delegates for success/false
            m_publishService.DidPublishService    += publishService_DidPublishService;
            m_publishService.DidNotPublishService += publishService_DidNotPublishService;

            m_isPrepared = true;
        }
Exemplo n.º 4
0
        private void monitorMyLocation()
        {
            try {
                while (true)
                {
                    if (discloseLocation)
                    {
                        Trace.WriteLine("DEBUG: Looking up location info..");
                        try {
                            MSE.login();
                            AesMobileStationLocation loc = MSE.queryMAC(myMac);
                            MSE.logout();

                            if (loc != null)
                            {
                                if ((prevLoc == null) || (prevLoc.x != loc.x) || (prevLoc.y != loc.y))
                                {
                                    TXTrecords.Add("locationID", "NOTIMPL" /* loc.x + " x " + loc.y */);
                                    publishService.setTXTRecordData(NetService.DataFromTXTRecordDictionary(TXTrecords));

                                    Trace.WriteLine(" Mac: " + loc.macAddress + " Loc: " + loc.x + "x" + loc.y + " lastHeard " + loc.minLastHeardSecs + " conf " + loc.confidenceFactor);
                                    prevLoc = loc;
                                }
                            }
                        } catch (Exception e) {
                            Trace.WriteLine("DEBUG: Disclose location: " + e.StackTrace);
                        }
                    }
                    Thread.Sleep(5000);
                }
            } catch (Exception e) {
                Trace.WriteLine("Oops - " + e.Message);
            }
        }
        /// <summary>
        /// Publishes the mDNS sevrice to pretend like we are a client device
        /// like an iPod Touch.  Service is "_touch-remote._tcp" and Pair is
        /// the important value here.
        /// </summary>
        private void PublishTouchRemoteService()
        {
            try {
                Console.WriteLine("mDNS: {0}", NetService.DaemonVersion);
                String domain = "";
                String name   = "0000000000000000000000000000000000000001";
                touchRemoteService = new NetService(domain, SERVICE_TYPE, name, PORT);
                touchRemoteService.AllowMultithreadedCallbacks = true;
                touchRemoteService.DidPublishService          += new NetService.ServicePublished(publishService_DidPublishService);
                touchRemoteService.DidNotPublishService       += new NetService.ServiceNotPublished(publishService_DidNotPublishService);

                /* HARDCODE TXT RECORD */
                System.Collections.Hashtable dict = new System.Collections.Hashtable();
                dict.Add("DvNm", this.applicationName + " Client");
                dict.Add("RemV", "10000");
                dict.Add("DvTy", "iPod");
                dict.Add("RemN", "Remote");
                dict.Add("txtvers", "1");
                dict.Add("Pair", "0000000000000001");
                touchRemoteService.TXTRecordData = NetService.DataFromTXTRecordDictionary(dict);
                touchRemoteService.Publish();
            } catch (Exception ex) {
                Console.WriteLine("Error publishing mDNS TouchRemote Service", ex);
            }
        }
Exemplo n.º 6
0
        public void StartServer()
        {
            webServerKayak.StartServer();

            publishService = new NetService(_domain, _serviceName, _hostName, _port);
            publishService.DidPublishService    += new NetService.ServicePublished(publishService_DidPublishService);
            publishService.DidNotPublishService += new NetService.ServiceNotPublished(publishService_DidNotPublishService);
            publishService.TXTRecordData         = NetService.DataFromTXTRecordDictionary(ResponseMessageHelper.GetServerInfo());
            publishService.Publish();
        }
Exemplo n.º 7
0
        public bool Publish()
        {
            // old style services
            foreach (var srv in Installation.GetInstalledServices())
            {
                if (srv.ToWebService() == null || !ZeroconfDiscoverer.serviceTypes.ContainsKey(srv.ToWebService().Value))
                {
                    continue;
                }

                Dictionary <string, string> additionalData = new Dictionary <string, string>();
                additionalData["hwAddr"]       = String.Join(";", NetworkInformation.GetMACAddresses());
                additionalData["netbios-name"] = System.Environment.MachineName;
                if (ExternalAddress.GetAddress() != null)
                {
                    additionalData["external-ip"] = ExternalAddress.GetAddress();
                }

                NetService net = new NetService(ZeroconfDiscoverer.DOMAIN, ZeroconfDiscoverer.serviceTypes[srv.ToWebService().Value], Configuration.Services.GetServiceName(), srv.Port);
                net.AllowMultithreadedCallbacks = true;
                net.TXTRecordData         = NetService.DataFromTXTRecordDictionary(additionalData);
                net.DidPublishService    += new NetService.ServicePublished(PublishedService);
                net.DidNotPublishService += new NetService.ServiceNotPublished(FailedToPublishService);
                net.Publish();
                publishedServices.Add(net);
            }

            // new style service sets
            foreach (WebServiceSet set in Detector.CreateSetComposer().ComposeUnique())
            {
                Log.Debug("Publishing service set {0}", set);
                Dictionary <string, string> additionalData = new Dictionary <string, string>();
                additionalData["mac"]          = String.Join(";", NetworkInformation.GetMACAddresses());
                additionalData["netbios-name"] = Environment.MachineName != null ? Environment.MachineName : String.Empty;
                additionalData["external-ip"]  = ExternalAddress.GetAddress() != null?ExternalAddress.GetAddress() : String.Empty;

                additionalData["meta"]      = WCFUtil.GetCurrentRoot().Remove(WCFUtil.GetCurrentRoot().LastIndexOf("/MPExtended/") + 1);
                additionalData["mas"]       = set.MAS != null ? set.MAS : String.Empty;
                additionalData["masstream"] = set.MASStream != null ? set.MASStream : String.Empty;
                additionalData["tas"]       = set.TAS != null ? set.TAS : String.Empty;
                additionalData["tasstream"] = set.TASStream != null ? set.TASStream : String.Empty;
                additionalData["ui"]        = set.UI != null ? set.UI : String.Empty;

                NetService net = new NetService(ZeroconfDiscoverer.DOMAIN, SET_SERVICE_TYPE, Configuration.Services.GetServiceName(), Configuration.Services.Port);
                net.AllowMultithreadedCallbacks = true;
                net.TXTRecordData         = NetService.DataFromTXTRecordDictionary(additionalData);
                net.DidPublishService    += new NetService.ServicePublished(PublishedService);
                net.DidNotPublishService += new NetService.ServiceNotPublished(FailedToPublishService);
                net.Publish();
                publishedServices.Add(net);
            }

            return(true);
        }
Exemplo n.º 8
0
 //Hack for IOS 7 detection, periodically update the TXTRecord to force redetection
 void timerCallback(object o)
 {
     lock (timerSync)
     {
         if (timer != null && CurrentService != null)
         {
             dummyVal                     = !dummyVal;
             txtRecord["dummy"]           = dummyVal.ToString();
             CurrentService.TXTRecordData = NetService.DataFromTXTRecordDictionary(txtRecord);
         }
     }
 }
Exemplo n.º 9
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void myName_TextChanged(object sender, EventArgs e)
 {
     using (RegistryKey dcs = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("FXPAL").CreateSubKey("DisplayCast").CreateSubKey("Player")) {
         dcs.SetValue("Name", myName.Text);
         TXTrecords.Remove("name");
         TXTrecords.Add("name", myName.Text);
         if (nsPublisher != null)
         {
             nsPublisher.TXTRecordData = NetService.DataFromTXTRecordDictionary(TXTrecords);
         }
     }
 }
Exemplo n.º 10
0
        private NetService SetupMdnsService(string name, string serviceType, int port, Dictionary <string, string> txt)
        {
            var service = new NetService("local.", serviceType, name, port);

            service.TXTRecordData = NetService.DataFromTXTRecordDictionary(txt);

            service.AllowMultithreadedCallbacks = true;
            service.DidPublishService          += service_DidPublishService;
            service.DidNotPublishService       += service_DidNotPublishService;
            service.DidUpdateTXT += service_DidUpdateTXT;

            return(service);
        }
Exemplo n.º 11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Streamer_Closed(object sender, FormClosedEventArgs e)
        {
            if (publisherTXTrecords != null)
            {
                String sid = this.GetHashCode().ToString();

                publisherTXTrecords.Remove(sid);
                nsPublisher.TXTRecordData = NetService.DataFromTXTRecordDictionary(publisherTXTrecords);
            }

            clntStream.Close();
            Dispose();
        }
Exemplo n.º 12
0
        /// <summary>
        /// Starts publishing the airplay service over Bonjour so that iOS devices can find it.
        /// This only advertises the service, Bonjour doesn't deal with the connections themselves. The connections are dealt with in the Server class.
        /// </summary>
        private void DoPublish()
        {
            publishService = new NetService(domain, type, name, port);

            //add delegates for success/false
            publishService.DidPublishService    += publishService_DidPublishService;
            publishService.DidNotPublishService += publishService_DidNotPublishService;

            //add txtrecord, which gives details of the service. For now we'll just put the version number
            System.Collections.Hashtable dict = new System.Collections.Hashtable();
            dict.Add("txtvers", "1");
            publishService.TXTRecordData = NetService.DataFromTXTRecordDictionary(dict);

            publishService.Publish();
        }
Exemplo n.º 13
0
 private void updateTXTButton_Click(object sender, EventArgs e)
 {
     /* HARDCODE TXT RECORD */
     System.Collections.Hashtable dict = new System.Collections.Hashtable();
     dict.Add("txtvers", "2");
     dict.Add("CurrentTime", DateTime.Now.ToString());
     try
     {
         publishService.TXTRecordData = NetService.DataFromTXTRecordDictionary(dict);
         Debug.WriteLine("TXT Record updated");
     }
     catch (Exception)
     {
         Debug.WriteLine("ERROR UPDATING TXT RECORD!");
     }
 }
Exemplo n.º 14
0
        protected override NetService GetNetService()
        {
            Logger.Debug("AirplayEmitter: {0}, {1}, {2}", name, identifier, port);
            txtRecord = new Dictionary <string, object>();
            txtRecord.Add("txtvers", "1");
            txtRecord.Add("model", model);
            txtRecord.Add("deviceid", identifier);
            txtRecord.Add("srcvers", "130.14");
            txtRecord.Add("features", ios8Workaround ? "0x20F7" : features);
            if (pass)
            {
                txtRecord.Add("pw", "1");
            }

            NetService service = new NetService("", TYPE, name, port);

            service.TXTRecordData = NetService.DataFromTXTRecordDictionary(txtRecord);
            return(service);
        }
Exemplo n.º 15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="e"></param>
        private void locationChecked(object Sender, EventArgs e)
        {
            if (locationItem.Checked)
            {
                locationItem.Checked = false;

                prevLoc = null;
                TXTrecords.Remove("locationID");
                nsPublisher.TXTRecordData = NetService.DataFromTXTRecordDictionary(TXTrecords);
            }
            else
            {
                locationItem.Checked = true;
                discloseLocation     = true;
            }
            using (RegistryKey dcs = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("FXPAL").CreateSubKey("DisplayCast").CreateSubKey("Streamer")) {
                dcs.SetValue("discloseLocation", locationItem.Checked);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Publish a service.
        /// </summary>
        /// <param name="type">
        /// Type of the service to publish.
        /// <para>
        /// `type` must contain both the service type and transport layer information. To
        /// ensure that the mDNS responder searches for services, as opposed to hosts,
        /// prefix both the service name and transport layer name with an underscore
        /// character ("_"). For example, to publish an HTTP service on TCP, you would
        /// use the type string `@"_http._tcp."`. Note that the period character at the end
        /// of the string, which indicates that the domain name is an absolute name, is
        /// required. It will be automatically set if it does not exists.
        /// </para>
        /// </param>
        /// <param name="port">Port of the service to publish.</param>
        /// <param name="name">Name of the service to publish.</param>
        /// <param name="domain">Domain in which to publish the service.</param>
        /// <param name="TXTRecord">TXT record of the service to publish.</param>
        public bool PublishService(String type, ushort port, String name, String domain, Dictionary <String, String> TXTRecord)
        {
            if (!type.EndsWith("."))
            {
                type += ".";
            }

            String key = this.KeyForPublish(type, domain, port);

            if (this.IsPublishing)
            {
                if (netServices.ContainsKey(key))
                {
                    logger.TraceEvent(TraceEventType.Warning, 0, String.Format("Already publishing service of type {0} in domain {1} on port {2}", type, domain, port));
                    return(false);
                }
            }

            this.IsPublishing = true;

            NetService netService = new NetService(domain, type, name, port);

            netService.AllowApplicationForms       = false;
            netService.AllowMultithreadedCallbacks = true;

            netService.DidPublishService    += new NetService.ServicePublished(NetServiceDidPublish);
            netService.DidNotPublishService += new NetService.ServiceNotPublished(NetServiceDidNotPublish);

            /* HARDCODE TXT RECORD */
            System.Collections.Hashtable dict = new System.Collections.Hashtable();
            dict.Add("txtvers", "1");
            netService.TXTRecordData = NetService.DataFromTXTRecordDictionary(dict);

            netServices[key] = netService;

            netService.Publish();

            logger.TraceEvent(TraceEventType.Information, 0, String.Format("Published service of type {0} in domain {1} on port {2}", type, domain, port));

            return(true);
        }
Exemplo n.º 17
0
        public void PublishServices(List <Service> services)
        {
            if (!Configuration.Services.BonjourEnabled || !CheckBonjourInstallation())
            {
                return;
            }

            serviceName = GetServiceName();
            foreach (Service srv in services)
            {
                // We also send a list of usernames and password hashes, so that clients can detect if they match across MPExtended
                // installations.
                // Note: this is specifically introduced for aMPdroid. It will probably be changed to something more advanced in the
                // next release where we don't keep backwards-compatibility for this part. Please do not depend on the presence of
                // this property.
                HashAlgorithm hashAlg = MD5.Create();
                Dictionary <string, string> sendUsers = new Dictionary <string, string>();
                foreach (var user in Configuration.Services.Users)
                {
                    byte[] hash = hashAlg.ComputeHash(Encoding.UTF8.GetBytes(user.EncryptedPassword));
                    for (int i = 1; i < 1000; i++)
                    {
                        hash = hashAlg.ComputeHash(hash);
                    }
                    sendUsers.Add(user.Username, Convert.ToBase64String(hash, 0, 12));
                }

                // also publish IP address and username list
                Dictionary <string, string> additionalData = new Dictionary <string, string>();
                additionalData["hwAddr"] = GetHardwareAddresses();
                additionalData["users"]  = String.Join(";", sendUsers.Select(x => x.Key + ":" + x.Value));

                NetService net = new NetService(DOMAIN, srv.ZeroconfServiceType, serviceName, srv.Port);
                net.AllowMultithreadedCallbacks = true;
                net.TXTRecordData         = NetService.DataFromTXTRecordDictionary(additionalData);
                net.DidNotPublishService += new NetService.ServiceNotPublished(FailedToPublishService);
                net.DidPublishService    += new NetService.ServicePublished(PublishedService);
                net.Publish();
            }
            Log.Info("Published bonjour services");
        }
Exemplo n.º 18
0
        /// <summary>
        ///
        /// </summary>
        public static void monitorMyLocation()
        {
            /* TextBox locationString = (TextBox)o;
             * if (locationString.GetType() != typeof(TextBox)) {
             *   Trace.WriteLine("Hmmm, not the right type");
             *   return;
             * }
             */
            while (true)
            {
                using (RegistryKey dcs = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("FXPAL").CreateSubKey("DisplayCast").CreateSubKey("Player")) {
                    discloseLocation = Convert.ToBoolean(dcs.GetValue("discloseLocation", false));
                }

                if (discloseLocation)
                {
                    // Trace.WriteLine("DEBUG: Looking up location info..");
                    try {
                        MSE.login();
                        AesMobileStationLocation loc = MSE.queryMAC(myMac);
                        MSE.logout();

                        if (loc != null)
                        {
                            if ((prevLoc == null) || (prevLoc.x != loc.x) || (prevLoc.y != loc.y))
                            {
                                TXTrecords.Add("locationID", "NOTIMPL" /* loc.x + " x " + loc.y */);
                                nsPublisher.TXTRecordData = NetService.DataFromTXTRecordDictionary(TXTrecords);

                                Trace.WriteLine(" Mac: " + loc.macAddress + " Loc: " + loc.x + "x" + loc.y + " lastHeard " + loc.minLastHeardSecs + " conf " + loc.confidenceFactor);
                                prevLoc = loc;
                            }
                        }
                    } catch (Exception e) {
                        Trace.WriteLine("DEBUG: Disclose location: " + e.StackTrace);
                    }
                }

                Thread.Sleep(5000);
            }
        }
Exemplo n.º 19
0
        private void DoPublish()
        {
            try
            {
                Debug.WriteLine(String.Format("Bonjour Version: {0}", NetService.DaemonVersion));
            }
            catch (Exception ex)
            {
                String message = ex is DNSServiceException ? "Bonjour is not installed!" : ex.Message;
                MessageBox.Show(message, "Critical Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Exit();
            }

            String domain = "";
            String type   = serviceTypeTextBox.Text;
            String name   = serviceNameTextBox.Text;
            int    port   = Int32.Parse(portTextBox.Text);

            publishService = new NetService(domain, type, name, port);

            publishService.DidPublishService    += new NetService.ServicePublished(publishService_DidPublishService);
            publishService.DidNotPublishService += new NetService.ServiceNotPublished(publishService_DidNotPublishService);

            /* HARDCODE TXT RECORD */
            System.Collections.Hashtable dict = new System.Collections.Hashtable();
            dict.Add("txtvers", "1");
            publishService.TXTRecordData = NetService.DataFromTXTRecordDictionary(dict);

            publishService.Publish();

            serviceNameTextBox.Enabled = false;
            serviceTypeTextBox.Enabled = false;
            portTextBox.Enabled        = false;

            startStopButton.Enabled = false;
            startStopButton.Text    = "Publishing...";

            mPublishing = true;
        }
Exemplo n.º 20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void changeName(object sender, EventArgs e)
        {
            if (nsPublisher != null)
            {
                String defaultName;

                using (RegistryKey dcs = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("FXPAL").CreateSubKey("DisplayCast").CreateSubKey("Player")) {
                    defaultName = dcs.GetValue("Name", System.Environment.UserName).ToString();
                    String name = Interaction.InputBox("Enter our name. Remote streamers will use this name to project their screencast.", "FXPal DisplayCast Player", defaultName, 0, 0);

                    if (name.Length != 0)
                    {
                        dcs.SetValue("Name", name);
                        // Trace.WriteLine("DEBUG - name is " + name + " length is " + name.Length);

                        TXTrecords.Remove("name");
                        TXTrecords.Add("name", name);
                        nsPublisher.TXTRecordData = NetService.DataFromTXTRecordDictionary(TXTrecords);
                    }
                }
            }
        }
Exemplo n.º 21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Streamer_SizeLocationChanged(object sender, EventArgs e)
        {
            /* Control control = (Control)sender;
             * String val;
             *
             * if ((control.Location.X == -32000) && (control.Location.Y == -32000))
             *  val = "-x-";
             * else
             *  val = control.Location.X + "x" + control.Location.Y;
             * val = val + "x" + control.Size.Width + "x" + control.Size.Height;
             */
            String val = null;

            using (RegistryKey dcs = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("FXPAL").CreateSubKey("DisplayCast").CreateSubKey("Player")) {
                if (dcs.GetValue("uid") == null)
                {
                    dcs.SetValue("uid", System.Guid.NewGuid().ToString("D"));
                }
                val = this.id + " " + dcs.GetValue("uid").ToString();
            }

            Rectangle loc = DesktopBounds;

            val = val + " " + loc.X + " " + loc.Y + " " + loc.Width + " " + loc.Height;
            val = val + " " + ((this.WindowState == FormWindowState.Minimized) ? "1" : "0");
            val = val + " " + ((fs) ? "1" : "0");

            String sid = this.GetHashCode().ToString();

            Trace.WriteLine("Resized to " + val);

            if (publisherTXTrecords != null)
            {
                publisherTXTrecords.Remove(sid);
                publisherTXTrecords.Add(sid, val);

                nsPublisher.TXTRecordData = NetService.DataFromTXTRecordDictionary(publisherTXTrecords);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Publish the service via Bonjour protocol to the network
        /// </summary>
        private void PublishBonjourService()
        {
            if (servicePublishing)
            {
                WifiRemote.LogMessage("Already in the process of publishing the Bonjour service. Aborting publish ...", LogType.Debug);
                return;
            }

            // Test if Bonjour is installed
            try
            {
                //float bonjourVersion = NetService.GetVersion();
                Version bonjourVersion = NetService.DaemonVersion;
                LogMessage(String.Format("Bonjour version {0} found.", bonjourVersion.ToString()), LogType.Info);
            }
            catch
            {
                LogMessage("Bonjour enabled but not installed! Get it at http://support.apple.com/downloads/Bonjour_for_Windows", LogType.Error);
                LogMessage("Disabling Bonjour for this session.", LogType.Info);
                disableBonjour = true;
                return;
            }

            servicePublishing = true;

            publishService = new NetService(domain, serviceType, serviceName, port);

            // Get the MAC addresses and set it as bonjour txt record
            // Needed by the clients to implement wake on lan
            Hashtable dict = new Hashtable();

            dict.Add("hwAddr", GetHardwareAddresses());
            publishService.TXTRecordData         = NetService.DataFromTXTRecordDictionary(dict);
            publishService.DidPublishService    += new NetService.ServicePublished(publishService_DidPublishService);
            publishService.DidNotPublishService += new NetService.ServiceNotPublished(publishService_DidNotPublishService);

            publishService.Publish();
        }
Exemplo n.º 23
0
        static void Main()
        {
            // Catchall for all uncaught exceptions !!
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyDefaultHandler);

            // Catch hibernation event so that we can reload the driver
            SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(DesktopMirror.SystemEvents_PowerModeChanged);

            // Setting some garbage collector parameters
            GCSettings.LatencyMode = GCLatencyMode.LowLatency;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // First load the mirror driver
            try {
                _mirror.Load();
            } catch (System.Security.SecurityException se) {
                MessageBox.Show(se.Message + ". You need to run this program as an administrator",
                                "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                System.Environment.Exit(1);
            } catch (Exception ex) {
                MessageBox.Show("FATAL: Loading mirror driver failed. Check http://displaycast.fxpal.net/ for further instructions " + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // _mirror.Dispose();
                System.Environment.Exit(1);
            }

            // Nest, create a TCP port to listen for new Player connections
            TcpListener serverAddr = new TcpListener(new IPEndPoint(IPAddress.Any, 0));

            serverAddr.Start();

            // Now create a thread to process new client requests
            streamer = new streamThread(_mirror);
            serverThread nt = new serverThread(serverAddr, _mirror, streamer);

            Thread netThread = new Thread(new ThreadStart(nt.process));

            netThread.Name = "processNewClient";
            netThread.Start();

            // Create a thread to send data to the connected clients
            Thread strmThread = new Thread(new ThreadStart(streamer.process));

            strmThread.Name = "dataStreamer";
            // strmThread.Priority = ThreadPriority.Highest;
            strmThread.Start();

            // Now create a listener for snapshots - hardwired to port 9854
            try {
                HttpListener imageListener = new HttpListener();

                imageListener.Prefixes.Add("http://+:9854/");
                imageListener.Start();
                imageListener.BeginGetContext(_mirror.sendScreenShot, imageListener);

                if (imageListener.IsListening)
                {
                    TXTrecords.Add("imagePort", "9854");
                }
            } catch (Exception e) {
                MessageBox.Show("Oops " + e.Message);
            }

            maskX      = maskY = 0;
            maskWidth  = DesktopMirror._bitmapWidth;
            maskHeight = DesktopMirror._bitmapHeight;

            // Now listen for mask requests - perhaps I could've reused the imageport also
            TcpListener ctrlAddr = new TcpListener(IPAddress.Any, 0);   // Used for accepting MASK command

            ctrlAddr.Start();
            IPEndPoint sep = (IPEndPoint)ctrlAddr.LocalEndpoint;

            Debug.Assert(sep.Port != 0);
            TXTrecords.Add("maskPort", sep.Port.ToString());
            ctrlAddr.BeginAcceptTcpClient(ctrlBeginAcceptTcpClient, ctrlAddr);

            /* Fill TXT RECORD */
            TXTrecords.Add("screen", "0x0 " + DesktopMirror._bitmapWidth.ToString() + "x" + DesktopMirror._bitmapHeight.ToString());
            TXTrecords.Add("machineName", System.Environment.MachineName);
            TXTrecords.Add("osVersion", System.Environment.OSVersion.VersionString);
            TXTrecords.Add("version", Shared.DisplayCastGlobals.DISPLAYCAST_VERSION.ToString());
            TXTrecords.Add("userid", System.Environment.UserName);

#if USE_BLUETOOTH
            if (BluetoothRadio.IsSupported)
            {
                try {
                    TXTrecords.Add("bluetooth", BluetoothRadio.PrimaryRadio.LocalAddress.ToString("C").Replace(":", "-").ToLower());
                } catch {
                    TXTrecords.Add("bluetooth", "NotSupported");
                }
            }
            else
#endif
            TXTrecords.Add("bluetooth", "NotSupported");
            TXTrecords.Add("nearby", "UNKNOWN");

            String myName = null, id;
            using (RegistryKey dcs = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("FXPAL").CreateSubKey("DisplayCast").CreateSubKey("Streamer")) {
                if (dcs.GetValue("uid") == null)
                {
                    dcs.SetValue("uid", System.Guid.NewGuid().ToString("D"));
                }
                id = dcs.GetValue("uid").ToString();

                if (dcs.GetValue("Name") == null)
                {
                    dcs.SetValue("Name", System.Environment.UserName);
                }
                myName = dcs.GetValue("Name").ToString();
                TXTrecords.Add("name", myName);
            }

            try {
                // Now, publish my info via Bonjour
                IPEndPoint serv = (IPEndPoint)serverAddr.LocalEndpoint;

                publishService = new NetService(Shared.DisplayCastGlobals.BONJOURDOMAIN, Shared.DisplayCastGlobals.STREAMER, id, serv.Port);
                publishService.DidPublishService    += new NetService.ServicePublished(publishService_DidPublishService);
                publishService.DidNotPublishService += new NetService.ServiceNotPublished(publishService_DidNotPublishService);
                publishService.TXTRecordData         = NetService.DataFromTXTRecordDictionary(TXTrecords);
                publishService.Publish();
            } catch (Exception e) {
                Trace.WriteLine(e.StackTrace);
                MessageBox.Show("Apple Bonjour not installed. Pick up a local copy from http://displaycast.fxpal.net/",
                                "FATAL", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }

            _mirror.DesktopChange += _DesktopChange;
            try {
                Application.Run(new Console(publishService, TXTrecords, id));
            } catch (Exception e) {
                MessageBox.Show("FATAL: " + e.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ar"></param>
        public static void ctrlBeginAcceptTcpClient(IAsyncResult ar)
        {
            TcpListener   ctrlAddr = (TcpListener)ar.AsyncState;
            TcpClient     clnt     = ctrlAddr.EndAcceptTcpClient(ar);
            NetworkStream strm     = clnt.GetStream();

            char[] delimiters = { ' ', '\t', '\r', '\n' };
            byte[] bytes      = new byte[clnt.ReceiveBufferSize];

            ctrlAddr.BeginAcceptTcpClient(ctrlBeginAcceptTcpClient, ctrlAddr);
            // strm.BeginRead(bytes, 0, clnt.ReceiveBufferSize, ctrlCmdRead, state);

            strm.ReadTimeout = 30000;
            try {
                strm.Read(bytes, 0, clnt.ReceiveBufferSize);
            } catch (System.IO.IOException ioe) {
                Trace.WriteLine("FATAL: Timeout waiting for remote control: " + ioe.Message);
                strm.Close();
                return;
            }

            String cmdString = Encoding.UTF8.GetString(bytes);

            String[] words = cmdString.Split(delimiters);
            String   cmd   = words[0].ToUpper();

            switch (cmd)
            {
            case "MASK":
            case "CREATEREGION":
                maskX      = Convert.ToInt32(words[1]);
                maskY      = Convert.ToInt32(words[2]);
                maskWidth  = Convert.ToInt32(words[3]);
                maskHeight = Convert.ToInt32(words[4]);

                if ((maskX == 0) && (maskY == 0) && (maskWidth == DesktopMirror._bitmapWidth) && (maskHeight == DesktopMirror._bitmapHeight))
                {
                    bytes = Encoding.ASCII.GetBytes("Mask unset");
                    strm.Write(bytes, 0, bytes.Length);
                    strm.Close();

                    maskValid = false;
                }
                else
                {
                    bytes = Encoding.ASCII.GetBytes("Mask set to: " + maskX + "x" + maskY + " " + maskWidth + "x" + maskHeight);
                    strm.Write(bytes, 0, bytes.Length);
                    strm.Close();
                    maskValid = true;
                }

                if (publishService != null)
                {
                    if (TXTrecords.ContainsKey("maskScreen"))
                    {
                        TXTrecords.Remove("maskScreen");
                    }

                    if (maskValid)
                    {
                        TXTrecords.Add("maskScreen", maskX + "x" + maskY + " " + maskWidth + "x" + maskHeight);
                    }
                    publishService.TXTRecordData = NetService.DataFromTXTRecordDictionary(TXTrecords);
                    publishService.Publish();
                }
                return;

            default:
                bytes = Encoding.ASCII.GetBytes(DisplayCastGlobals.STREAMER_CMD_SYNTAX_ERROR);
                strm.Write(bytes, 0, bytes.Length);
                strm.Close();
                break;
            }
        }
Exemplo n.º 25
0
        static void Main()
        {
            // Catchall for all uncaught exceptions !!
            AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs args) {
                // Application.Restart();

                var exception = (Exception)args.ExceptionObject;
                MessageBox.Show("FATAL: Unhandled - " + exception.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            };

            try {
                TXTrecords.Add("machineName", System.Environment.MachineName);
                TXTrecords.Add("osVersion", System.Environment.OSVersion.VersionString);
                TXTrecords.Add("userid", System.Environment.UserName);
#if USE_BLUETOOTH
                if (BluetoothRadio.IsSupported)
                {
                    try {
                        TXTrecords.Add("bluetooth", BluetoothRadio.PrimaryRadio.LocalAddress.ToString("C").Replace(":", "-").ToLower());
                    } catch {
                        TXTrecords.Add("bluetooth", "NotSupported");
                    }
                }
                else
#endif
                TXTrecords.Add("bluetooth", "NotSupported");
                allScreen = Screen.AllScreens;
                for (int i = 0; i < allScreen.Length; i++)
                {
                    TXTrecords.Add("screen" + i, allScreen[i].Bounds.X + "x" + allScreen[i].Bounds.Y + "x" + allScreen[i].Bounds.Width + "x" + allScreen[i].Bounds.Height);
                }

                // TXTrecords.Add("screenWidth", System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width.ToString());
                // TXTrecords.Add("screenHeight", System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height.ToString());

                TcpListener ctrlAddr = new TcpListener(IPAddress.Any, 0);
                ctrlAddr.Start();

                IPEndPoint sep = (IPEndPoint)ctrlAddr.LocalEndpoint;
                Debug.Assert(sep.Port != 0);

                String id, nm;
                using (RegistryKey dcs = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("FXPAL").CreateSubKey("DisplayCast").CreateSubKey("Player")) {
                    if (dcs.GetValue("uid") == null)
                    {
                        dcs.SetValue("uid", System.Guid.NewGuid().ToString("D"));
                    }
                    id = dcs.GetValue("uid").ToString();

                    if (dcs.GetValue("name") == null)
                    {
                        dcs.SetValue("name", System.Environment.UserName);
                    }
                    nm = dcs.GetValue("Name").ToString();
                    TXTrecords.Remove("name");
                    TXTrecords.Add("name", nm);
                }

                try {
                    nsPublisher = new NetService(Shared.DisplayCastGlobals.BONJOURDOMAIN, Shared.DisplayCastGlobals.PLAYER, id, sep.Port);
                    nsPublisher.DidPublishService    += new NetService.ServicePublished(publishService_DidPublishService);
                    nsPublisher.DidNotPublishService += new NetService.ServiceNotPublished(publishService_DidNotPublishService);
                    nsPublisher.TXTRecordData         = NetService.DataFromTXTRecordDictionary(TXTrecords);
                    nsPublisher.AllowApplicationForms = true;
                    nsPublisher.Publish();
                } catch {
                    MessageBox.Show("Apple Bonjour not installed. Pick up a local copy from https://developer.apple.com/opensource/", "FATAL", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Environment.Exit(1);
                }

                // PlayerRemoteControl rc = new PlayerRemoteControl(ctrlAddr);
                // Thread ctrlThread = new Thread(new ThreadStart(rc.process));
                // ctrlThread.Name = "processNewControl";
                // ctrlThread.Start();

                ctrlAddr.BeginAcceptTcpClient(ctrlBeginAcceptTcpClient, ctrlAddr);

                MSE   = new QueryMSE();
                myMac = getWIFIMACAddress();
                // if (myMac == null)
                //    myMac = displaycast;

                if (myMac != null)
                {
                    using (RegistryKey dcs = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("FXPAL").CreateSubKey("DisplayCast").CreateSubKey("Player")) {
                        discloseLocation = Convert.ToBoolean(dcs.GetValue("discloseLocation", false));
                    }

                    locThread = new Thread(new ThreadStart(monitorMyLocation));
                    locThread.Start();
                }
            } catch (Exception e) {
                MessageBox.Show("FATAL: Unhandled - " + e.StackTrace,
                                "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }
            try {
                streamerList = new StreamerList();
                Application.Run(streamerList);
            } catch (Exception e) {
                MessageBox.Show("FATAL: Cannot start streamerList - " + e.StackTrace);
                Environment.Exit(1);
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Publishes the mDNS sevrice to pretend like we are a client device
        /// like an iPod Touch.  Service is "_touch-able._tcp" and DBId is
        /// the important value here. CtlN is the name that represents this
        /// server on the iPhone/Android device.
        /// </summary>
        private void PublishMdnsServices()
        {
            Console.WriteLine("Publishing mDNS Service...");
            try {
                Console.WriteLine("mDNS Version: {0}", NetService.DaemonVersion);
                string name = this.GetApplicationName() + " " + Environment.MachineName;
                string hash = name.GetHashCode().ToString("X");
                hash = hash + hash;
                if (hash.Length <= 16)
                {
                    this.ServiceName = hash;
                }
                else
                {
                    this.ServiceName = (hash + hash).Substring(0, 15);
                }

                String domain = "";
                touchAbleService = new NetService(domain, TOUCHSERVICE_TYPE, this.ServiceName, PORT);
                touchAbleService.AllowMultithreadedCallbacks = true;
                touchAbleService.DidPublishService          += new NetService.ServicePublished(publishService_DidPublishService);
                touchAbleService.DidNotPublishService       += new NetService.ServiceNotPublished(publishService_DidNotPublishService);

                webService = new NetService(domain, WEBSERVICE_TYPE, name, PORT);
                webService.AllowMultithreadedCallbacks = true;
                webService.DidPublishService          += new NetService.ServicePublished(publishService_DidPublishService);
                webService.DidNotPublishService       += new NetService.ServiceNotPublished(publishService_DidNotPublishService);

                dacpService = new NetService(domain, DACPSERVICE_TYPE, name, PORT);
                dacpService.AllowMultithreadedCallbacks = true;
                dacpService.DidPublishService          += new NetService.ServicePublished(publishService_DidPublishService);
                dacpService.DidNotPublishService       += new NetService.ServiceNotPublished(publishService_DidNotPublishService);

                daapService = new NetService(domain, DAAPSERVICE_TYPE, name, PORT);
                daapService.AllowMultithreadedCallbacks = true;
                daapService.DidPublishService          += new NetService.ServicePublished(publishService_DidPublishService);
                daapService.DidNotPublishService       += new NetService.ServiceNotPublished(publishService_DidNotPublishService);

                /* Touchable-Service RECORD */
                System.Collections.Hashtable dict = new System.Collections.Hashtable();
                dict.Add("CtlN", name);
                dict.Add("OSsi", "0x1F5");
                dict.Add("Ver", "131075");
                dict.Add("txtvers", "1");
                dict.Add("DvTy", this.GetApplicationName());
                dict.Add("DvSv", "2049");
                dict.Add("DbId", this.ServiceName);
                touchAbleService.TXTRecordData = NetService.DataFromTXTRecordDictionary(dict);
                touchAbleService.Publish();

                /* DACP-Service RECORD */
                System.Collections.Hashtable dictDacp = new System.Collections.Hashtable();
                dictDacp.Add("OSsi", "0x1F5");
                dictDacp.Add("Ver", "131075");
                dictDacp.Add("txtvers", "1");
                dictDacp.Add("DbId", this.ServiceName);
                dacpService.TXTRecordData = NetService.DataFromTXTRecordDictionary(dictDacp);
                dacpService.Publish();

                /* DAAP-Service RECORD */
                System.Collections.Hashtable dictDaap = new System.Collections.Hashtable();
                dictDaap.Add("Machine Name", name);
                dictDaap.Add("iTSh Version", "131073");
                dictDaap.Add("Version", "196615");
                dictDaap.Add("txtvers", "1");
                dictDaap.Add("Password", "false");
                dictDaap.Add("DvSv", "2049");
                dictDaap.Add("Database ID", this.ServiceName);
                dictDaap.Add("Machine ID", this.ServiceName);
                dictDaap.Add("DbId", this.ServiceName);
                daapService.TXTRecordData = NetService.DataFromTXTRecordDictionary(dictDaap);
                //daapService.Publish();

                /* HTTP-Service has no service record */
                webService.Publish();
            } catch (Exception ex) {
                Console.WriteLine("Error publishing mDNS Services", ex);
            }
        }