Example #1
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();
        }
Example #2
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"] = String.Join(";", NetworkInformation.GetMACAddresses());
                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");
        }
Example #3
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;
        }
Example #4
0
        public PlexServer(string ServerTestUrl)
        {
            Router router = new Router();
            router.AddController("library", new Library());
            router.AddController("resources", new Resources());
            router.AddController("manage", new Manage());
            listener = new WebServer(ServerTestUrl, router);
            listener.Start();

            String domain = "";
            String type = "_plexmediasvr._tcp";
            String name = "WinPlex Media Server";
            int port = 32400;

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

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

            publishService.Publish();
        }
        /// <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;
        }
        private void PublishZeroconf()
        {
            int port = 9909;
            int.TryParse(GetSettingValue("PORT"), out port);

            string domain = "";
            String type = "_lightswitch._tcp.";
            String name = "Lightswitch " + Environment.MachineName;
            netservice = new NetService(domain, type, name, port);
            netservice.AllowMultithreadedCallbacks = true;
            netservice.DidPublishService += new NetService.ServicePublished(publishService_DidPublishService);
            netservice.DidNotPublishService += new NetService.ServiceNotPublished(publishService_DidNotPublishService);

            /* HARDCODE TXT RECORD */
            System.Collections.Hashtable dict = new System.Collections.Hashtable();
            dict = new System.Collections.Hashtable();
            dict.Add("txtvers", "1");
            dict.Add("ServiceName", name);
            dict.Add("MachineName", Environment.MachineName);
            dict.Add("OS", Environment.OSVersion.ToString());
            dict.Add("IPAddress", "127.0.0.1");
            dict.Add("Version", zvsEntityControl.zvsNameAndVersion);
            netservice.TXTRecordData = NetService.DataFromTXTRecordDictionary(dict);
            netservice.Publish();
        }
Example #7
0
        /// <summary>
        /// Publish the service via Bonjour protocol to the network
        /// </summary>
        private void PublishBonjourService()
        {
            // 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;
            }

            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();
        }
Example #8
0
        public bool Publish()
        {
            // old style services
            foreach (var srv in Installation.GetInstalledServices())
            {
                if (srv.ToWebService() == null || !ZeroconfDiscoverer.serviceTypes.ContainsKey(srv.ToWebService()))
                    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()], 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"] = System.Environment.MachineName;
                additionalData["external-ip"] = ExternalAddress.GetAddress();
                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;
        }
Example #9
0
        /**
        *  FIXME
        */
        public void start()
        {
            if (Program.gui is ISynchronizeInvoke)
            {
                try
                {
                    publishService = new NetService("", "_crossfade._tcp", System.Environment.MachineName, 21000);
                    publishService.Publish();

                    nsBrowser.InvokeableObject = (ISynchronizeInvoke)Program.gui;
                    nsBrowser.DidFindService += new NetServiceBrowser.ServiceFound(Program.gui.p2p_DidFindService);
                    nsBrowser.DidRemoveService += new NetServiceBrowser.ServiceRemoved(Program.gui.p2p_DidRemoveService);
                    nsBrowser.SearchForService("_crossfade._tcp", "");
                }
                catch (DNSServiceException e)
                {
                    System.Diagnostics.Debug.Print(String.Format("A DNSServiceException occured: {0}", e.Message));
                    return;
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.Print(String.Format("An exception occured: {0}", e.Message));
                    return;
                }
            }
        }
Example #10
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);
            }
        }
        /// <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();
        }
Example #12
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);
            }
        }
 private static void RegisterBonjour()
 {
     try
     {
         m_mdnsService = new NetService(m_serviceDomain, m_serviceName, Environment.MachineName, m_port);
         m_mdnsService.Publish();
     }
     catch
     {
         //no nothing because bonjour is not installed
     }
 }