aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
blob: 04ddb4c4b1df805951d25fab1e3c165b2247929f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Logging;
using Mono.Nat;
using System;
using System.IO;
using System.Text;

namespace MediaBrowser.Server.Implementations.EntryPoints
{
    public class ExternalPortForwarding : IServerEntryPoint
    {
        private readonly IServerApplicationHost _appHost;
        private readonly ILogger _logger;
        private readonly IServerConfigurationManager _config;

        private bool _isStarted;

        public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config)
        {
            _logger = logmanager.GetLogger("PortMapper");
            _appHost = appHost;
            _config = config;

            _config.ConfigurationUpdated += _config_ConfigurationUpdated;
        }

        void _config_ConfigurationUpdated(object sender, EventArgs e)
        {
            var enable = _config.Configuration.EnableUPnP;

            if (enable && !_isStarted)
            {
                Reload();
            }
            else if (!enable && _isStarted)
            {
                DisposeNat();
            }
        }

        public void Run()
        {
            //NatUtility.Logger = new LogWriter(_logger);
            
            Reload();
        }

        private void Reload()
        {
            if (_config.Configuration.EnableUPnP)
            {
                _logger.Debug("Starting NAT discovery");
                
                NatUtility.DeviceFound += NatUtility_DeviceFound;
                NatUtility.DeviceLost += NatUtility_DeviceLost;
                NatUtility.UnhandledException += NatUtility_UnhandledException;
                NatUtility.StartDiscovery();

                _isStarted = true;
            }
        }

        void NatUtility_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //var ex = e.ExceptionObject as Exception;

            //if (ex == null)
            //{
            //    _logger.Error("Unidentified error reported by Mono.Nat");
            //}
            //else
            //{
            //    // Seeing some blank exceptions coming through here
            //    _logger.ErrorException("Error reported by Mono.Nat: ", ex);
            //}
        }

        void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
        {
            try
            {
                var device = e.Device;
                _logger.Debug("NAT device found: {0}", device.LocalAddress.ToString());

                CreateRules(device);
            }
            catch (Exception)
            {
                //_logger.ErrorException("Error creating port forwarding rules", ex);
            }
        }

        private void CreateRules(INatDevice device)
        {
            var info = _appHost.GetSystemInfo();

            CreatePortMap(device, info.HttpServerPortNumber);

            if (info.WebSocketPortNumber != info.HttpServerPortNumber)
            {
                CreatePortMap(device, info.WebSocketPortNumber);
            }
        }

        private void CreatePortMap(INatDevice device, int port)
        {
            _logger.Debug("Creating port map on port {0}", port);

            device.CreatePortMap(new Mapping(Protocol.Tcp, port, port)
            {
                Description = "Media Browser Server"
            });
        }

        void NatUtility_DeviceLost(object sender, DeviceEventArgs e)
        {
            var device = e.Device;
            _logger.Debug("NAT device lost: {0}", device.LocalAddress.ToString());
        }

        public void Dispose()
        {
            DisposeNat();
        }

        private void DisposeNat()
        {
            _logger.Debug("Stopping NAT discovery");

            try
            {
                NatUtility.DeviceFound -= NatUtility_DeviceFound;
                NatUtility.DeviceLost -= NatUtility_DeviceLost;
                NatUtility.UnhandledException -= NatUtility_UnhandledException;
                NatUtility.StopDiscovery();
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error stopping NAT Discovery", ex);
            }
            finally
            {
                _isStarted = false;
            }
        }

        private class LogWriter : TextWriter
        {
            private readonly ILogger _logger;

            public LogWriter(ILogger logger)
            {
                _logger = logger;
            }

            public override Encoding Encoding
            {
                get { return Encoding.UTF8; }
            }

            public override void WriteLine(string format, params object[] arg)
            {
                _logger.Debug(format, arg);
            }

            public override void WriteLine(string value)
            {
                _logger.Debug(value);
            }
        }
    }
}