jellyfin-server/Mono.Nat/Pmp/PmpNatDevice.cs

217 lines
8.3 KiB
C#
Raw Normal View History

2016-09-11 07:33:53 +00:00
//
// Authors:
// Ben Motmans <ben.motmans@gmail.com>
//
// Copyright (C) 2007 Ben Motmans
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;
2016-10-28 01:07:40 +00:00
using System.Threading.Tasks;
using MediaBrowser.Model.Extensions;
2018-09-12 17:26:21 +00:00
using MediaBrowser.Model.Logging;
2016-09-11 07:33:53 +00:00
namespace Mono.Nat.Pmp
{
2016-10-28 03:11:21 +00:00
internal sealed class PmpNatDevice : AbstractNatDevice, IEquatable<PmpNatDevice>
{
private IPAddress localAddress;
private IPAddress publicAddress;
2018-09-12 17:26:21 +00:00
private ILogger _logger;
2016-09-11 07:33:53 +00:00
2018-09-12 17:26:21 +00:00
internal PmpNatDevice(IPAddress localAddress, IPAddress publicAddress, ILogger logger)
2016-09-11 07:33:53 +00:00
{
2018-09-12 17:26:21 +00:00
if (localAddress == null)
{
throw new ArgumentNullException("localAddress");
}
2016-10-28 03:11:21 +00:00
this.localAddress = localAddress;
this.publicAddress = publicAddress;
2018-09-12 17:26:21 +00:00
_logger = logger;
2016-09-11 07:33:53 +00:00
}
2016-10-28 03:11:21 +00:00
public override IPAddress LocalAddress
2016-09-11 07:33:53 +00:00
{
2016-10-28 03:11:21 +00:00
get { return localAddress; }
}
2016-09-11 07:33:53 +00:00
2016-10-28 03:11:21 +00:00
public override Task CreatePortMap(Mapping mapping)
{
return InternalCreatePortMapAsync(mapping, true);
}
2016-09-11 07:33:53 +00:00
2016-10-28 03:11:21 +00:00
public override bool Equals(object obj)
{
PmpNatDevice device = obj as PmpNatDevice;
return (device == null) ? false : this.Equals(device);
}
2016-09-11 07:33:53 +00:00
2016-10-28 03:11:21 +00:00
public override int GetHashCode()
{
return this.publicAddress.GetHashCode();
}
2016-09-11 07:33:53 +00:00
2016-10-28 03:11:21 +00:00
public bool Equals(PmpNatDevice other)
{
return (other == null) ? false : this.publicAddress.Equals(other.publicAddress);
2016-09-11 07:33:53 +00:00
}
2016-10-28 03:11:21 +00:00
private async Task<Mapping> InternalCreatePortMapAsync(Mapping mapping, bool create)
{
var package = new List<byte>();
package.Add(PmpConstants.Version);
package.Add(mapping.Protocol == Protocol.Tcp ? PmpConstants.OperationCodeTcp : PmpConstants.OperationCodeUdp);
package.Add(0); //reserved
package.Add(0); //reserved
package.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)mapping.PrivatePort)));
package.AddRange(
BitConverter.GetBytes(create ? IPAddress.HostToNetworkOrder((short)mapping.PublicPort) : (short)0));
package.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(mapping.Lifetime)));
try
{
byte[] buffer = package.ToArray(package.Count);
2016-10-28 03:11:21 +00:00
int attempt = 0;
int delay = PmpConstants.RetryDelay;
2016-09-11 07:33:53 +00:00
2016-10-28 03:11:21 +00:00
using (var udpClient = new UdpClient())
{
var cancellationTokenSource = new CancellationTokenSource();
2016-09-11 07:33:53 +00:00
2016-10-28 03:11:21 +00:00
while (attempt < PmpConstants.RetryAttempts)
{
2018-09-12 17:26:21 +00:00
await udpClient.SendAsync(buffer, buffer.Length, new IPEndPoint(LocalAddress, PmpConstants.ServerPort));
2016-09-11 07:33:53 +00:00
2016-10-28 03:11:21 +00:00
if (attempt == 0)
{
Task.Run(() => CreatePortMapListen(udpClient, mapping, cancellationTokenSource.Token));
}
2016-09-11 07:33:53 +00:00
2016-10-28 03:11:21 +00:00
attempt++;
delay *= 2;
await Task.Delay(delay).ConfigureAwait(false);
}
2016-09-11 07:33:53 +00:00
2016-10-28 03:11:21 +00:00
cancellationTokenSource.Cancel();
}
}
catch (OperationCanceledException)
{
2016-09-11 07:33:53 +00:00
2016-10-28 03:11:21 +00:00
}
catch (Exception e)
{
string type = create ? "create" : "delete";
string message = String.Format("Failed to {0} portmap (protocol={1}, private port={2}) {3}",
type,
mapping.Protocol,
mapping.PrivatePort,
e.Message);
2018-09-12 17:26:21 +00:00
_logger.Debug(message);
throw e;
2016-10-28 03:11:21 +00:00
}
return mapping;
}
2016-09-11 07:33:53 +00:00
2016-10-28 03:11:21 +00:00
private async void CreatePortMapListen(UdpClient udpClient, Mapping mapping, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
2016-09-11 07:33:53 +00:00
{
2017-01-15 21:29:00 +00:00
try
{
var result = await udpClient.ReceiveAsync().ConfigureAwait(false);
var endPoint = result.RemoteEndPoint;
byte[] data = data = result.Buffer;
2016-09-11 07:33:53 +00:00
2017-01-15 21:29:00 +00:00
if (data.Length < 16)
continue;
2016-09-11 07:33:53 +00:00
2017-01-15 21:29:00 +00:00
if (data[0] != PmpConstants.Version)
continue;
2016-09-11 07:33:53 +00:00
2017-01-15 21:29:00 +00:00
var opCode = (byte)(data[1] & 127);
2016-09-11 07:33:53 +00:00
2017-01-15 21:29:00 +00:00
var protocol = Protocol.Tcp;
if (opCode == PmpConstants.OperationCodeUdp)
protocol = Protocol.Udp;
2016-09-11 07:33:53 +00:00
2017-01-15 21:29:00 +00:00
short resultCode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 2));
int epoch = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 4));
2016-09-11 07:33:53 +00:00
2017-01-15 21:29:00 +00:00
short privatePort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 8));
short publicPort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 10));
2016-10-28 03:11:21 +00:00
2017-01-15 21:29:00 +00:00
var lifetime = (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 12));
2016-10-28 03:11:21 +00:00
2017-01-15 21:29:00 +00:00
if (privatePort < 0 || publicPort < 0 || resultCode != PmpConstants.ResultCodeSuccess)
{
var errors = new[]
{
2016-10-28 03:11:21 +00:00
"Success",
"Unsupported Version",
"Not Authorized/Refused (e.g. box supports mapping, but user has turned feature off)"
,
"Network Failure (e.g. NAT box itself has not obtained a DHCP lease)",
"Out of resources (NAT box cannot create any more mappings at this time)",
"Unsupported opcode"
};
2016-10-29 18:59:36 +00:00
2017-01-15 21:29:00 +00:00
var errorMsg = errors[resultCode];
2018-09-12 17:26:21 +00:00
_logger.Debug("Error in CreatePortMapListen: " + errorMsg);
2017-01-15 21:29:00 +00:00
return;
}
2016-09-11 07:33:53 +00:00
2017-01-15 21:29:00 +00:00
if (lifetime == 0) return; //mapping was deleted
2016-09-11 07:33:53 +00:00
2017-01-15 21:29:00 +00:00
//mapping was created
//TODO: verify that the private port+protocol are a match
mapping.PublicPort = publicPort;
mapping.Protocol = protocol;
mapping.Expiration = DateTime.Now.AddSeconds(lifetime);
return;
}
catch (Exception ex)
{
2018-09-12 17:26:21 +00:00
_logger.ErrorException("Error in CreatePortMapListen", ex);
2017-01-15 21:29:00 +00:00
return;
}
2016-10-28 03:11:21 +00:00
}
}
2016-09-11 07:33:53 +00:00
/// <summary>
/// Overridden.
/// </summary>
/// <returns></returns>
2016-10-28 03:11:21 +00:00
public override string ToString()
2016-09-11 07:33:53 +00:00
{
2016-10-28 03:11:21 +00:00
return String.Format("PmpNatDevice - Local Address: {0}, Public IP: {1}, Last Seen: {2}",
this.localAddress, this.publicAddress, this.LastSeen);
2016-09-11 07:33:53 +00:00
}
2016-10-28 03:11:21 +00:00
}
2016-09-11 07:33:53 +00:00
}