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

Files support for POST requests #107

Open
wants to merge 1 commit 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ obj
*.suo
*.user
_ReSharper.*
*.ReSharper
*.DS_Store
*.userprefs
*.pidb
Expand Down
4 changes: 2 additions & 2 deletions src/Main/Gate.Middleware/ShowExceptions.View.cs
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ unknown location
");

var form = request.ReadForm();
if (form.Any())
if (form.Fields.Any())
{
write(@"
<table class=""req"">
Expand All @@ -365,7 +365,7 @@ unknown location
</thead>
<tbody>
");
foreach (var kv in form.OrderBy(kv => kv.Key))
foreach (var kv in form.Fields.OrderBy(kv => kv.Key))
{
write(@"
<tr>
Expand Down
127 changes: 127 additions & 0 deletions src/Main/Gate/Form/Form.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Gate.Utils;

namespace Gate.Form
{
internal class Form : IForm
{
readonly Encoding _encoding = new ASCIIEncoding();

public Form()
{
Fields = ParamDictionary.Parse("");
Files = new Dictionary<string, IFormFile>();
}

public Form(string text)
{
Fields = ParamDictionary.Parse(text);
Files = new Dictionary<string, IFormFile>();
}

public Form(string boundary, Stream stream)
{
Fields = new Dictionary<string, string>();
Files = new Dictionary<string, IFormFile>();
if (stream == null)
return;
if (stream.CanSeek)
stream.Seek(0, SeekOrigin.Begin);
ReadData(boundary, stream);
}

private static int IndexOf(byte[] searchIn, byte[] searchBytes, int start = 0)
{
var found = -1;
if (searchIn.Length > 0 && searchBytes.Length > 0 && start <= (searchIn.Length - searchBytes.Length) && searchIn.Length >= searchBytes.Length)
{
for (var i = start; i <= searchIn.Length - searchBytes.Length; i++)
{
if (searchIn[i] != searchBytes[0]) continue;
if (searchIn.Length > 1)
{
var matched = true;
for (var y = 1; y <= searchBytes.Length - 1; y++)
{
if (searchIn[i + y] == searchBytes[y]) continue;
matched = false;
break;
}
if (matched)
{
found = i;
break;
}
}
else
{
found = i;
break;
}
}
}
return found;
}

private static byte[] ReadFully(Stream input)
{
var buffer = new byte[16 * 1024];
using (var ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}

private static byte[] SubArray(byte[] data, int index, int length)
{
var result = new byte[length];
Array.Copy(data, index, result, 0, length);
return result;
}

private void ReadData(string boundary, Stream input)
{
var data = ReadFully(input);

var b = _encoding.GetBytes(boundary);
var ret1 = _encoding.GetBytes("\r\n--"+boundary);
var ret2 = _encoding.GetBytes("\r\n\r\n");

var offset = 0;
int pos;
while ((pos = IndexOf(data, b, offset)) != -1)
{
// pos - boundary starting point
if (pos + b.Length + 2 - data.Length > -5)
return;
// pos2 - boundary header endpoint/boundary body start point
var pos2 = IndexOf(data, ret2, pos + 1);
if (pos2 == -1)
return;
pos2 += ret2.Length;
// pos3 - boundary endpoint
var pos3 = IndexOf(data, ret1, pos2);
if (pos3 == -1)
return;
var file = new FormFile(SubArray(data, pos, pos2 - pos), SubArray(data, pos2, pos3 - pos2), _encoding);
if (file.IsFile)
Files[file.Name] = file;
else
Fields[file.Name] = file.FileName;
offset = pos3;
}
}

public IDictionary<string, string> Fields { get; private set; }

public IDictionary<string, IFormFile> Files { get; private set; }
}
}
60 changes: 60 additions & 0 deletions src/Main/Gate/Form/FormFile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System;
using System.IO;
using System.Linq;
using System.Text;

namespace Gate.Form
{
internal class FormFile : IFormFile
{
readonly Stream _stream;

public FormFile(byte[] infob, byte[] content, Encoding encoding)
{
var info = encoding.GetString(infob);
ContentType = null;
Size = -1;
var parts = info.Split(new[] {";", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
foreach (var part in parts.Select(x => x.Trim()))
{
if (part.StartsWith("name=", StringComparison.OrdinalIgnoreCase))
{
Name = UnEscape(part.Substring(5));
}
else if (part.StartsWith("filename=", StringComparison.OrdinalIgnoreCase))
{
FileName = UnEscape(part.Substring(9));
Size = content.Length;
}
else if (part.StartsWith("Content-Type: ", StringComparison.OrdinalIgnoreCase))
{
ContentType = UnEscape(part.Substring(14));
}
}

_stream = ContentType != null ? new MemoryStream(content) : null;
if (ContentType == null)
FileName = encoding.GetString(content);
}

private static string UnEscape(string v)
{
return v.Trim(' ', '"');
}

public bool IsFile { get { return Stream != null; } }

public string Name { get; private set; }

public string FileName { get; private set; }

public string ContentType { get; private set; }

public long Size { get; private set; }

public Stream Stream
{
get { return _stream; }
}
}
}
4 changes: 4 additions & 0 deletions src/Main/Gate/Gate.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@
<Compile Include="App_Packages\TaskHelpers.Sources.0.1\TaskHelpers.cs" />
<Compile Include="App_Packages\TaskHelpers.Sources.0.1\TaskHelpersExtensions.cs" />
<Compile Include="DictionaryExtensions.cs" />
<Compile Include="Form\FormFile.cs" />
<Compile Include="Form\Form.cs" />
<Compile Include="Headers.cs" />
<Compile Include="IForm.cs" />
<Compile Include="IFormFile.cs" />
<Compile Include="Mapping\MapBuilder.cs" />
<Compile Include="Mapping\UrlMapper.cs" />
<Compile Include="AppBuilderMapExtensions.cs" />
Expand Down
10 changes: 10 additions & 0 deletions src/Main/Gate/IForm.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System.Collections.Generic;

namespace Gate
{
public interface IForm
{
IDictionary<string, string> Fields { get; }
IDictionary<string, IFormFile> Files { get; }
}
}
13 changes: 13 additions & 0 deletions src/Main/Gate/IFormFile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.IO;

namespace Gate
{
public interface IFormFile
{
string Name { get; }
string FileName { get; }
string ContentType { get; }
long Size { get; }
Stream Stream { get; }
}
}
70 changes: 54 additions & 16 deletions src/Main/Gate/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Gate.Utils;
using Owin;

namespace Gate
{
Expand Down Expand Up @@ -189,6 +187,14 @@ public bool HasParseableData
}
}

public bool HasBoundary
{
get
{
var ct = ContentType;
return ct != null && ContentType.IndexOf("boundary=", System.StringComparison.Ordinal) != -1;
}
}

public string ContentType
{
Expand All @@ -210,6 +216,22 @@ public string MediaType
}
}

public string Boundary
{
get
{
var contentType = ContentType;
if (contentType == null)
return null;
var idx = contentType.IndexOf("boundary=", System.StringComparison.Ordinal);
if (idx == -1)
return null;
var boundary = contentType.Substring(idx + "boundary=".Length);
var delimiterPos = boundary.IndexOfAny(CommaSemicolon);
return delimiterPos < 0 ? boundary : boundary.Substring(0, delimiterPos);
}
}

public Task CopyToStreamAsync(Stream stream)
{
if (Body == null)
Expand Down Expand Up @@ -291,14 +313,14 @@ public string ReadText()
return text;
}

public Task<IDictionary<string, string>> ReadFormAsync()
public Task<IForm> ReadFormAsync()
{
if (!HasFormData && !HasParseableData)
if (!HasFormData && !HasParseableData && !HasBoundary)
{
return TaskHelpers.FromResult(ParamDictionary.Parse(""));
return TaskHelpers.FromResult((IForm) new Form.Form());
}

var form = Environment.Get<IDictionary<string, string>>("Gate.Request.Form");
var form = Environment.Get<IForm>("Gate.Request.Form");
var thisInput = Body;
var lastInput = Environment.Get<object>("Gate.Request.Form#input");
if (form != null && ReferenceEquals(thisInput, lastInput))
Expand All @@ -308,32 +330,48 @@ public string ReadText()

Request thisRequest = this;

return ReadTextAsync().Then(text =>
var boundary = Boundary;
if (boundary == null)
return ReadTextAsync().Then(text =>
{
form = new Form.Form(text);
thisRequest.Environment.Set("Gate.Request.Form#input", thisInput);
thisRequest.Environment.Set("Gate.Request.Form", form);
return form;
});
return TaskHelpers.FromResult(form = new Form.Form(boundary, thisInput)).Then(x =>
{
form = ParamDictionary.Parse(text);
thisRequest.Environment.Set("Gate.Request.Form#input", thisInput);
thisRequest.Environment.Set("Gate.Request.Form", form);
return form;
thisRequest.Environment.Set("Gate.Request.Form", x);
return x;
});
}

public IDictionary<string, string> ReadForm()
public IForm ReadForm()
{
if (!HasFormData && !HasParseableData)
if (!HasFormData && !HasParseableData && !HasBoundary)
{
return ParamDictionary.Parse("");
return new Form.Form();
}

var form = Environment.Get<IDictionary<string, string>>("Gate.Request.Form");
var form = Environment.Get<IForm>("Gate.Request.Form");
var thisInput = Body;
var lastInput = Environment.Get<object>("Gate.Request.Form#input");
if (form != null && ReferenceEquals(thisInput, lastInput))
{
return form;
}

var text = ReadText();
form = ParamDictionary.Parse(text);
var boundary = Boundary;
if (boundary == null)
{
var text = ReadText();
form = new Form.Form(text);
}
else
{
form = new Form.Form(boundary, thisInput);
}
Environment.Set("Gate.Request.Form#input", thisInput);
Environment.Set("Gate.Request.Form", form);
return form;
Expand Down