Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactorings #59

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 59 additions & 38 deletions src/HyperFastCgi/AppHosts/AspNet/AspNetNativeWebRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,20 @@ static AspNetNativeWebRequest ()
private int input_data_offset;

public int PortNumber {
get {
if (port < 0)
//FIXME: tryparse
port = int.Parse (GetParameter (
"SERVER_PORT"));
get
{
if (port < 0)
{
if (!int.TryParse(GetParameter("SERVER_PORT"), out port)) {
Logger.Write(LogLevel.Error, "fastcgi_param 'SERVER_PORT' not set! Setting to default value '80'! "
+ "Please add 'fastcgi_param SERVER_PORT $server_port;' to your webserver config!");
port = 80;
}

return port;
}
}

return port;
}
}

public string Path {
Expand Down Expand Up @@ -143,7 +149,7 @@ public AspNetNativeWebRequest (ulong requestId, int requestNumber, IApplicationH

public void AddHeader (string header, string value)
{
if (!String.IsNullOrEmpty (header)) {
if (!string.IsNullOrEmpty (header)) {
int idx = HttpWorkerRequest.GetKnownRequestHeaderIndex (header);

if (idx != -1) {
Expand All @@ -154,34 +160,48 @@ public void AddHeader (string header, string value)
}
}

/// <summary>
/// TODO errors can happen here, changing return value to bool and then evaluating the return value outside could help
/// </summary>
/// <param name="data"></param>
public void AddBodyPart (byte[] data)
{
if (input_data == null) {
int len = 0;
int len;
string slen = GetParameter ("CONTENT_LENGTH");

if (slen == null) {
//TODO: error, throw an exception
//Instead of throwing an Exception, write to error log and return
Logger.Write(LogLevel.Error, "fastcgi_param 'CONTENT_LENGTH' not set! "
+ "Please add 'fastcgi_param SERVER_PORT $server_port;' to your webserver config!");

return;
}

if (!int.TryParse (slen, NumberStyles.None, CultureInfo.InvariantCulture, out len)) {
//TODO: error, throw an exception
Logger.Write(LogLevel.Error, "Invalid CONTENT_LENGTH: {0}", slen);

return;
}

input_data = new byte[len];
}

if (input_data_offset + data.Length > input_data.Length) {
//TODO: throw an exception
//Instead of throwing an Exception, write to error log and return
Logger.Write(LogLevel.Error, "Buffer too small: input_data (size {0}) but should be at least {1}", input_data.Length, (input_data_offset + data.Length));

return;
}

Buffer.BlockCopy (data, 0, input_data, input_data_offset, data.Length);
Buffer.BlockCopy (data, 0, input_data, input_data_offset, data.Length);
input_data_offset += data.Length;
}

public string GetParameter (string parameter)
{
if (parameter_table != null && parameter_table.ContainsKey (parameter))
return (string)parameter_table [parameter];
return parameter_table [parameter];

return null;
}
Expand Down Expand Up @@ -268,8 +288,7 @@ public override void SendResponseFromMemory (byte[] data, int length)

public override void SendStatus (int statusCode, string statusDescription)
{
AppendHeaderLine ("Status: {0} {1}",
statusCode, statusDescription);
AppendHeaderLine ("Status: {0} {1}", statusCode, statusDescription);
}

public override void SendUnknownResponseHeader (string name, string value)
Expand All @@ -294,7 +313,7 @@ public override bool IsEntireEntityBodyIsPreloaded ()

public override string GetPathInfo ()
{
return GetParameter ("PATH_INFO") ?? String.Empty;
return GetParameter ("PATH_INFO") ?? string.Empty;
}

public override string GetRawUrl ()
Expand All @@ -310,7 +329,7 @@ public override string GetRawUrl ()

StringBuilder b = new StringBuilder (GetUriPath ());
string query = GetQueryString ();
if (query != null && query.Length > 0) {
if (!string.IsNullOrEmpty(query)) {
b.Append ('?');
b.Append (query);
}
Expand All @@ -337,17 +356,17 @@ public override string GetHttpVersion ()
public override string GetLocalAddress ()
{
string address = GetParameter ("SERVER_ADDR");
if (address != null && address.Length > 0)
if (!string.IsNullOrEmpty(address))
return address;

address = AddressFromHostName (
GetParameter ("HTTP_HOST"));
if (address != null && address.Length > 0)
if (!string.IsNullOrEmpty(address))
return address;

address = AddressFromHostName (
GetParameter ("SERVER_NAME"));
if (address != null && address.Length > 0)
if (!string.IsNullOrEmpty(address))
return address;

return base.GetLocalAddress ();
Expand Down Expand Up @@ -378,7 +397,7 @@ public override byte [] GetQueryStringRawBytes ()
public override string GetRemoteAddress ()
{
string addr = GetParameter ("REMOTE_ADDR");
return addr != null && addr.Length > 0 ?
return !string.IsNullOrEmpty(addr) ?
addr : base.GetRemoteAddress ();
}

Expand All @@ -399,7 +418,7 @@ public override string GetRemoteName ()
public override int GetRemotePort ()
{
string port = GetParameter ("REMOTE_PORT");
if (port == null || port.Length == 0)
if (string.IsNullOrEmpty(port))
return base.GetRemotePort ();

try {
Expand All @@ -413,10 +432,10 @@ public override string GetServerVariable (string name)
{
string value = GetParameter (name);

if (value == null)
if (value == null && name != null)
value = Environment.GetEnvironmentVariable (name);

return value != null ? value : base.GetServerVariable (name);
return value ?? base.GetServerVariable (name);
}

public override string GetUriPath ()
Expand Down Expand Up @@ -553,7 +572,7 @@ private static string AddressFromHostName (string host)
if (host == null || host.Length > 126)
return null;

System.Net.IPAddress[] addresses = null;
IPAddress[] addresses = null;
try {
addresses = Dns.GetHostAddresses (host);
} catch (System.Net.Sockets.SocketException) {
Expand All @@ -570,7 +589,7 @@ private static string AddressFromHostName (string host)

private static string HostNameFromString (string host)
{
if (host == null || host.Length == 0)
if (string.IsNullOrEmpty(host))
return null;

int colon_index = host.IndexOf (':');
Expand All @@ -592,15 +611,17 @@ private static void SetDefaultIndexFiles (string list)
List<string> files = new List<string> ();

string [] fs = list.Split (',');
foreach (string f in fs) {
string trimmed = f.Trim ();
if (trimmed == "")
continue;
for (int index = 0; index < fs.Length; index++)
{
string f = fs[index];
string trimmed = f.Trim();
if (trimmed == "")
continue;

files.Add (trimmed);
}
files.Add(trimmed);
}

indexFiles = files.ToArray ();
indexFiles = files.ToArray ();
}

#endregion
Expand All @@ -613,16 +634,16 @@ public void Process (IWebResponse response)
#endregion

#region IWebResponse implementation
public void Send (int status, string description, IDictionary<string, string> headers)
public void Send (int status, string description, IDictionary<string, string> sendHeaders)
{
SendStatus (status, description);
foreach (KeyValuePair<string, string> pair in headers) {
foreach (KeyValuePair<string, string> pair in sendHeaders) {
SendUnknownResponseHeader (pair.Key, pair.Value);
}
}
public void Send (int status, string description, IDictionary<string, string> headers, byte[] response)
public void Send (int status, string description, IDictionary<string, string> sendHeaders, byte[] response)
{
Send (status, description, headers);
Send (status, description, sendHeaders);
SendResponseFromMemory (response, response.Length);
}
public void Send (byte[] response)
Expand Down
48 changes: 23 additions & 25 deletions src/HyperFastCgi/AppHosts/AspNet/MonoWorkerRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ static MonoWorkerRequest ()
}

public MonoWorkerRequest (HyperFastCgi.Interfaces.IApplicationHost appHost)
: base (String.Empty, String.Empty, null)
: base (string.Empty, string.Empty, null)
{
if (appHost == null)
throw new ArgumentNullException ("appHost");
Expand Down Expand Up @@ -256,12 +256,11 @@ public override string MapPath (string path)
if (eventResult != null)
return eventResult;

string hostVPath = HostVPath;
string currentHostVPath = HostVPath;
int hostVPathLen = HostVPath.Length;
int pathLen = path != null ? path.Length : 0;
bool inThisApp;

inThisApp = path.StartsWith (hostVPath, StringComparison.Ordinal);
bool inThisApp = path.StartsWith (currentHostVPath, StringComparison.Ordinal);

if (pathLen == 0 || (inThisApp && (pathLen == hostVPathLen || (pathLen == hostVPathLen + 1 && path [pathLen - 1] == '/')))) {
if (needToReplacePathSeparator)
Expand Down Expand Up @@ -314,36 +313,35 @@ public void ProcessRequest ()
error = ex.GetHtmlErrorMessage ();
} catch (Exception ex) {
inUnhandledException = true;
HttpException hex = new HttpException (400, "Bad request", ex);
if (hex != null) // just a precaution
error = hex.GetHtmlErrorMessage ();
else
error = String.Format (defaultExceptionHtml, ex.Message);
error = new HttpException(400, "Bad request", ex).GetHtmlErrorMessage();
}

if (!inUnhandledException)
return;

if (error.Length == 0)
error = String.Format (defaultExceptionHtml, "Unknown error");
if (error != null && error.Length == 0)
error = string.Format (defaultExceptionHtml, "Unknown error");

try {
SendStatus (400, "Bad request");
SendUnknownResponseHeader ("Connection", "close");
SendUnknownResponseHeader ("Date", DateTime.Now.ToUniversalTime ().ToString ("r"));

Encoding enc = Encoding.UTF8;
if (enc == null)
enc = Encoding.ASCII;

byte[] bytes = enc.GetBytes (error);
SendUnknownResponseHeader("Content-Type", "text/html; charset=" + enc.WebName);

if (error != null)
{
byte[] bytes = enc.GetBytes(error);
SendUnknownResponseHeader("Content-Length", bytes.Length.ToString());
SendResponseFromMemory(bytes, bytes.Length);
}

FlushResponse (true);

SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
SendUnknownResponseHeader ("Content-Length", bytes.Length.ToString ());
SendResponseFromMemory (bytes, bytes.Length);
FlushResponse (true);
} catch (Exception ex) { // should "never" happen
throw ex;
throw; // rethrow
}
}

Expand Down Expand Up @@ -380,39 +378,39 @@ public override void SendKnownResponseHeader (int index, string value)
public override string GetServerVariable (string name)
{
if (server_variables == null)
return String.Empty;
return string.Empty;

if (IsSecure ()) {
X509Certificate client = ClientCertificate;
switch (name) {
case "CERT_COOKIE":
if (cert_cookie == null) {
if (client == null)
cert_cookie = String.Empty;
cert_cookie = string.Empty;
else
cert_cookie = client.GetCertHashString ();
}
return cert_cookie;
case "CERT_ISSUER":
if (cert_issuer == null) {
if (client == null)
cert_issuer = String.Empty;
cert_issuer = string.Empty;
else
cert_issuer = client.Issuer;
}
return cert_issuer;
case "CERT_SERIALNUMBER":
if (cert_serial == null) {
if (client == null)
cert_serial = String.Empty;
cert_serial = string.Empty;
else
cert_serial = client.GetSerialNumberString ();
}
return cert_serial;
case "CERT_SUBJECT":
if (cert_subject == null) {
if (client == null)
cert_subject = String.Empty;
cert_subject = string.Empty;
else
cert_subject = client.Subject;
}
Expand All @@ -421,7 +419,7 @@ public override string GetServerVariable (string name)
}

string s = server_variables [name];
return (s == null) ? String.Empty : s;
return s ?? string.Empty;
}

public void AddServerVariable (string name, string value)
Expand Down
8 changes: 4 additions & 4 deletions src/HyperFastCgi/AppHosts/Raw/BaseRawRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,16 +114,16 @@ public IDictionary<string, string> ServerVariables {

#region IWebResponse implementation

public void Send (int status, string description, IDictionary<string, string> headers)
public void Send (int status, string description, IDictionary<string, string> sendHeaders)
{
Status = status;
StatusDescription = description;
responseHeaders = (Dictionary<string,string>)headers;
responseHeaders = (Dictionary<string,string>)sendHeaders;
}

public void Send (int status, string description, IDictionary<string, string> headers, byte[] response)
public void Send (int status, string description, IDictionary<string, string> sendHeaders, byte[] response)
{
Send (status, description, headers);
Send (status, description, sendHeaders);
Send (response);
}

Expand Down
Loading