Skip to content

Commit

Permalink
Fix some code analysis stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
nmaier committed Apr 3, 2014
1 parent fb70b9f commit 1300d50
Show file tree
Hide file tree
Showing 26 changed files with 147 additions and 137 deletions.
2 changes: 1 addition & 1 deletion SimpleDLNA/ServerListViewItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ where d.Exists
fileServer.Load();
var authorizer = new HttpAuthorizer();
if (Description.Ips.Length != 0) {
authorizer.AddMethod(new IpAuthorizer(Description.Ips));
authorizer.AddMethod(new IPAddressAuthorizer(Description.Ips));
}
if (Description.Macs.Length != 0) {
authorizer.AddMethod(new MacAuthorizer(Description.Macs));
Expand Down
2 changes: 1 addition & 1 deletion sdlna/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ private static void Main(string[] args)
try {
using (var authorizer = new HttpAuthorizer(server)) {
if (options.Ips.Length != 0) {
authorizer.AddMethod(new IpAuthorizer(options.Ips));
authorizer.AddMethod(new IPAddressAuthorizer(options.Ips));
}
if (options.Macs.Length != 0) {
authorizer.AddMethod(new MacAuthorizer(options.Macs));
Expand Down
3 changes: 3 additions & 0 deletions server/GlobalSuppressions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,6 @@
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "NMaier.SimpleDlna.Server.Views.LargeView")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "NMaier.SimpleDlna.Server.Views.NewView")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "NMaier.SimpleDlna.Server.Views.FilterView")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ip", Scope = "type", Target = "NMaier.SimpleDlna.Server.IpAuthorizer")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Satisfiable", Scope = "member", Target = "NMaier.SimpleDlna.Server.HttpCode.#RangeNotSatisfiable")]
2 changes: 1 addition & 1 deletion server/Handlers/IconHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public IResponse HandleRequest(IRequest req)
{
var resource = req.Path.Substring(Prefix.Length);
var isPng = resource.EndsWith(".png");
return new ResourceResponse(HttpCodes.OK, isPng ? "image/png" : "image/jpeg", resource);
return new ResourceResponse(HttpCode.Ok, isPng ? "image/png" : "image/jpeg", resource);
}
}
}
2 changes: 1 addition & 1 deletion server/Handlers/IndexHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public IResponse HandleRequest(IRequest req)

article.AppendChild(list);

return new StringResponse(HttpCodes.OK, document.OuterXml);
return new StringResponse(HttpCode.Ok, document.OuterXml);
}
}
}
8 changes: 4 additions & 4 deletions server/Handlers/MediaMount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,16 +104,16 @@ public IMediaItem GetItem(string id)
public IResponse HandleRequest(IRequest request)
{
if (Authorizer != null && !IPAddress.IsLoopback(request.RemoteEndpoint.Address) && !Authorizer.Authorize(request.Headers, request.RemoteEndpoint, IP.GetMAC(request.RemoteEndpoint.Address))) {
throw new HttpStatusException(HttpCodes.DENIED);
throw new HttpStatusException(HttpCode.Denied);
}

var path = request.Path.Substring(prefix.Length);
Debug(path);
if (path == "description.xml") {
return new StringResponse(HttpCodes.OK, "text/xml", GenerateDescriptor(request.LocalEndPoint.Address));
return new StringResponse(HttpCode.Ok, "text/xml", GenerateDescriptor(request.LocalEndPoint.Address));
}
if (path == "contentDirectory.xml") {
return new ResourceResponse(HttpCodes.OK, "text/xml", "contentdirectory");
return new ResourceResponse(HttpCode.Ok, "text/xml", "contentdirectory");
}
if (path == "control") {
return ProcessSoapRequest(request);
Expand All @@ -137,7 +137,7 @@ public IResponse HandleRequest(IRequest request)
return ProcessHtmlRequest(item);
}
WarnFormat("Did not understand {0} {1}", request.Method, path);
throw new HttpStatusException(HttpCodes.NOT_FOUND);
throw new HttpStatusException(HttpCode.NotFound);
}
}
}
4 changes: 2 additions & 2 deletions server/Handlers/MediaMount_HTML.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ private IResponse ProcessHtmlRequest(IMediaItem aItem)
{
var item = aItem as IMediaFolder;
if (item == null) {
throw new HttpStatusException(HttpCodes.NOT_FOUND);
throw new HttpStatusException(HttpCode.NotFound);
}

var article = HtmlTools.CreateHtmlArticle(string.Format("Folder: {0}", item.Title));
Expand Down Expand Up @@ -91,7 +91,7 @@ private IResponse ProcessHtmlRequest(IMediaItem aItem)
}
}

return new StringResponse(HttpCodes.OK, document.OuterXml);
return new StringResponse(HttpCode.Ok, document.OuterXml);
}
}
}
6 changes: 3 additions & 3 deletions server/Handlers/MediaMount_SOAP.cs
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ private IResponse ProcessSoapRequest(IRequest request)
var rbody = env.CreateElement("SOAP-ENV:Body", NS_SOAPENV);
env.DocumentElement.AppendChild(rbody);

var code = HttpCodes.OK;
var code = HttpCode.Ok;
try {
IEnumerable<KeyValuePair<string, string>> result;
switch (method.LocalName) {
Expand All @@ -431,7 +431,7 @@ private IResponse ProcessSoapRequest(IRequest request)
result = HandleXSetBookmark(sparams);
break;
default:
throw new HttpStatusException(HttpCodes.NOT_FOUND);
throw new HttpStatusException(HttpCode.NotFound);
}
var response = env.CreateElement(String.Format("u:{0}Response", method.LocalName), method.NamespaceURI);
rbody.AppendChild(response);
Expand All @@ -443,7 +443,7 @@ private IResponse ProcessSoapRequest(IRequest request)
}
}
catch (Exception ex) {
code = HttpCodes.INTERNAL_ERROR;
code = HttpCode.InternalError;
var fault = env.CreateElement("SOAP-ENV", "Fault", NS_SOAPENV);
var faultCode = env.CreateElement("faultcode");
faultCode.InnerText = "500";
Expand Down
4 changes: 2 additions & 2 deletions server/Http/HTTPServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ public HttpServer()
}
public HttpServer(int port)
{
prefixes.TryAdd("/favicon.ico", new StaticHandler(new ResourceResponse(HttpCodes.OK, "image/icon", "favicon")));
prefixes.TryAdd("/static/browse.css", new StaticHandler(new ResourceResponse(HttpCodes.OK, "text/css", "browse_css")));
prefixes.TryAdd("/favicon.ico", new StaticHandler(new ResourceResponse(HttpCode.Ok, "image/icon", "favicon")));
prefixes.TryAdd("/static/browse.css", new StaticHandler(new ResourceResponse(HttpCode.Ok, "text/css", "browse_css")));
RegisterHandler(new IconHandler());

listener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
Expand Down
11 changes: 4 additions & 7 deletions server/Http/HttpAuthorizer.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
using NMaier.SimpleDlna.Utilities;
using System;
using System.Collections.Generic;
using System.Net;
using NMaier.SimpleDlna.Utilities;

namespace NMaier.SimpleDlna.Server
{
public class HttpAuthorizer : Logging, IHttpAuthorizationMethod, IDisposable
public sealed class HttpAuthorizer : Logging, IHttpAuthorizationMethod, IDisposable
{
private readonly List<IHttpAuthorizationMethod> methods = new List<IHttpAuthorizationMethod>();


protected readonly HttpServer server = null;
private readonly HttpServer server = null;


public HttpAuthorizer()
{
}


public HttpAuthorizer(HttpServer server)
{
if (server == null) {
Expand All @@ -42,7 +39,7 @@ public void AddMethod(IHttpAuthorizationMethod method)
methods.Add(method);
}

public virtual bool Authorize(IHeaders headers, IPEndPoint ep, string mac)
public bool Authorize(IHeaders headers, IPEndPoint ep, string mac)
{
if (methods.Count == 0) {
return true;
Expand Down
36 changes: 18 additions & 18 deletions server/Http/HttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ internal sealed class HttpClient : Logging, IRequest, IDisposable

private static readonly Regex bytes = new Regex(@"^bytes=(\d+)(?:-(\d+)?)?$", RegexOptions.Compiled);

private readonly static IHandler Error403 = new StaticHandler(new StringResponse(HttpCodes.DENIED, "<!doctype html><title>Access denied!</title><h1>Access denied!</h1><p>You're not allowed to access the requested resource.</p>"));
private readonly static IHandler Error403 = new StaticHandler(new StringResponse(HttpCode.Denied, "<!doctype html><title>Access denied!</title><h1>Access denied!</h1><p>You're not allowed to access the requested resource.</p>"));

private readonly static IHandler Error404 = new StaticHandler(new StringResponse(HttpCodes.NOT_FOUND, "<!doctype html><title>Not found!</title><h1>Not found!</h1><p>The requested resource was not found!</p>"));
private readonly static IHandler Error404 = new StaticHandler(new StringResponse(HttpCode.NotFound, "<!doctype html><title>Not found!</title><h1>Not found!</h1><p>The requested resource was not found!</p>"));

private readonly static IHandler Error416 = new StaticHandler(new StringResponse(HttpCodes.RANGE_NOT_SATISFIABLE, "<!doctype html><title>Requested Range not satisfiable!</title><h1>Requested Range not satisfiable!</h1><p>Nice try, but do not try again :p</p>"));
private readonly static IHandler Error416 = new StaticHandler(new StringResponse(HttpCode.RangeNotSatisfiable, "<!doctype html><title>Requested Range not satisfiable!</title><h1>Requested Range not satisfiable!</h1><p>Nice try, but do not try again :p</p>"));

private readonly static IHandler Error500 = new StaticHandler(new StringResponse(HttpCodes.INTERNAL_ERROR, "<!doctype html><title>Internal Server Error</title><h1>Internal Server Error</h1><p>Something is very rotten in the State of Denmark!</p>"));
private readonly static IHandler Error500 = new StaticHandler(new StringResponse(HttpCode.InternalError, "<!doctype html><title>Internal Server Error</title><h1>Internal Server Error</h1><p>Something is very rotten in the State of Denmark!</p>"));

private readonly IHeaders headers = new Headers();

Expand Down Expand Up @@ -177,12 +177,12 @@ private long GetContentLengthFromStream(Stream responseBody)
return contentLength;
}

private Stream ProcessRanges(IResponse response, ref HttpCodes status)
private Stream ProcessRanges(IResponse rangedResponse, ref HttpCode status)
{
var responseBody = response.Body;
var responseBody = rangedResponse.Body;
var contentLength = GetContentLengthFromStream(responseBody);
string ar;
if (status != HttpCodes.OK && contentLength > 0 || !headers.TryGetValue("Range", out ar)) {
if (status != HttpCode.Ok && contentLength > 0 || !headers.TryGetValue("Range", out ar)) {
return responseBody;
}
try {
Expand All @@ -201,17 +201,17 @@ private Stream ProcessRanges(IResponse response, ref HttpCodes status)
}
if (start >= end) {
responseBody.Close();
response = Error416.HandleRequest(this);
return response.Body;
rangedResponse = Error416.HandleRequest(this);
return rangedResponse.Body;
}

if (start > 0) {
responseBody.Seek(start, SeekOrigin.Current);
}
contentLength = end - start + 1;
response.Headers["Content-Length"] = contentLength.ToString();
response.Headers.Add("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, totalLength));
status = HttpCodes.PARTIAL;
rangedResponse.Headers["Content-Length"] = contentLength.ToString();
rangedResponse.Headers.Add("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, totalLength));
status = HttpCode.Partial;
}
catch (Exception ex) {
Warn(String.Format("{0} - Failed to process range request!", this), ex);
Expand Down Expand Up @@ -375,14 +375,14 @@ private void SetupResponse()
State = HttpStates.WRITEBEGIN;
try {
if (!owner.AuthorizeClient(this)) {
throw new HttpStatusException(HttpCodes.DENIED);
throw new HttpStatusException(HttpCode.Denied);
}
if (string.IsNullOrEmpty(path)) {
throw new HttpStatusException(HttpCodes.NOT_FOUND);
throw new HttpStatusException(HttpCode.NotFound);
}
var handler = owner.FindHandler(path);
if (handler == null) {
throw new HttpStatusException(HttpCodes.NOT_FOUND);
throw new HttpStatusException(HttpCode.NotFound);
}
response = handler.HandleRequest(this);
if (response == null) {
Expand All @@ -396,13 +396,13 @@ private void SetupResponse()
InfoFormat("{0} - Got a {2}: {1}", this, path, ex.Code);
#endif
switch (ex.Code) {
case HttpCodes.NOT_FOUND:
case HttpCode.NotFound:
response = Error404.HandleRequest(this);
break;
case HttpCodes.DENIED:
case HttpCode.Denied:
response = Error403.HandleRequest(this);
break;
case HttpCodes.INTERNAL_ERROR:
case HttpCode.InternalError:
response = Error500.HandleRequest(this);
break;
default:
Expand Down
16 changes: 16 additions & 0 deletions server/Http/HttpCode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace NMaier.SimpleDlna.Server
{
public enum HttpCode : int
{
None = 0,
Denied = 403,
InternalError = 500,
MovedPermanently = 301,
NotFound = 404,
NotModified = 304,
Ok = 200,
Partial = 206,
RangeNotSatisfiable = 416,
TemporaryRedirect = 307
}
}
15 changes: 0 additions & 15 deletions server/Http/HttpCodes.cs

This file was deleted.

20 changes: 10 additions & 10 deletions server/Http/HttpPhrases.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ namespace NMaier.SimpleDlna.Server
{
internal static class HttpPhrases
{
public static readonly IDictionary<HttpCodes, string> Phrases = new Dictionary<HttpCodes, string>() {
{ HttpCodes.OK, "OK" },
{ HttpCodes.PARTIAL, "Partial Content" },
{ HttpCodes.MOVED_PERMANENTLY, "Moved Permanently" },
{ HttpCodes.NOT_MODIFIED, "Not Modified" },
{ HttpCodes.TEMPORARY_REDIRECT, "Temprary Redirect" },
{ HttpCodes.DENIED, "Forbidden" },
{ HttpCodes.NOT_FOUND, "Not Found" },
{ HttpCodes.RANGE_NOT_SATISFIABLE, "Requested Range not satisfiable" },
{ HttpCodes.INTERNAL_ERROR, "Internal Server Error" } };
public static readonly IDictionary<HttpCode, string> Phrases = new Dictionary<HttpCode, string>() {
{ HttpCode.Ok, "OK" },
{ HttpCode.Partial, "Partial Content" },
{ HttpCode.MovedPermanently, "Moved Permanently" },
{ HttpCode.NotModified, "Not Modified" },
{ HttpCode.TemporaryRedirect, "Temprary Redirect" },
{ HttpCode.Denied, "Forbidden" },
{ HttpCode.NotFound, "Not Found" },
{ HttpCode.RangeNotSatisfiable, "Requested Range not satisfiable" },
{ HttpCode.InternalError, "Internal Server Error" } };
}
}
Original file line number Diff line number Diff line change
@@ -1,27 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using NMaier.SimpleDlna.Utilities;

namespace NMaier.SimpleDlna.Server
{
public sealed class IpAuthorizer : Logging, IHttpAuthorizationMethod
public sealed class IPAddressAuthorizer : Logging, IHttpAuthorizationMethod
{
private readonly Dictionary<IPAddress, object> ips = new Dictionary<IPAddress, object>();


private IpAuthorizer()
private IPAddressAuthorizer()
{
}


public IpAuthorizer(IEnumerable<IPAddress> addresses)
public IPAddressAuthorizer(IEnumerable<IPAddress> addresses)
{
if (addresses == null) {
throw new ArgumentNullException("addresses");
}
foreach (var ip in addresses) {
ips.Add(ip, null);
}
}
public IpAuthorizer(IEnumerable<string> addresses)
public IPAddressAuthorizer(IEnumerable<string> addresses)
: this((from a in addresses
select IPAddress.Parse(a)))
{
Expand Down
3 changes: 3 additions & 0 deletions server/Http/MacAuthorizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ private MacAuthorizer()

public MacAuthorizer(IEnumerable<string> macs)
{
if (macs == null) {
throw new ArgumentNullException("macs");
}
foreach (var m in macs) {
var mac = m.ToUpperInvariant().Trim();
if (!IP.IsAcceptedMAC(mac)) {
Expand Down
Loading

0 comments on commit 1300d50

Please sign in to comment.