diff --git a/.gitignore b/.gitignore
index b2a3a21..81c3d01 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,10 @@
-project.lock.json
-bin/
-obj/
-Migrations/
-*.db
+project.lock.json
+DNWS260.code-workspace
+Dockerfile
+bin/
+obj/
+out/
+Migrations/
+*.db
+client/node_modules/
+client/app/bower_components/
diff --git a/.vs/slnx.sqlite b/.vs/slnx.sqlite
new file mode 100644
index 0000000..f7c9c77
Binary files /dev/null and b/.vs/slnx.sqlite differ
diff --git a/.vs/slnx.sqlite-journal b/.vs/slnx.sqlite-journal
new file mode 100644
index 0000000..e52a304
Binary files /dev/null and b/.vs/slnx.sqlite-journal differ
diff --git a/ClientInfoPlugin.cs b/ClientInfoPlugin.cs
index 7a01615..d73d151 100644
--- a/ClientInfoPlugin.cs
+++ b/ClientInfoPlugin.cs
@@ -14,25 +14,25 @@ public HTTPResponse GetResponse(HTTPRequest request)
{
StringBuilder sb = new StringBuilder();
- string[] client_endpoint = request.getPropertyByKey("RemoteEndPoint").Split(':');
+ string[] client_endpoint = request.GetPropertyByKey("RemoteEndPoint").Split(':');
string val;
sb.Append("
");
sb.Append("Client Port: ").Append(client_endpoint[1]).Append("
\n");
- if ((val = request.getPropertyByKey("user-agent")) != null)
+ if ((val = request.GetPropertyByKey("user-agent")) != null)
{
sb.Append("Browser Information: ").Append(val).Append("
\n");
}
- if ((val = request.getPropertyByKey("accept-language")) != null)
+ if ((val = request.GetPropertyByKey("accept-language")) != null)
{
sb.Append("Accept Language: ").Append(val).Append("
\n");
}
- if ((val = request.getPropertyByKey("accept-encoding")) != null)
+ if ((val = request.GetPropertyByKey("accept-encoding")) != null)
{
sb.Append("Accept Encoding: ").Append(val).Append("
\n");
}
sb.Append("");
HTTPResponse response = new HTTPResponse(200);
- response.body = Encoding.UTF8.GetBytes(sb.ToString());
+ response.Body = Encoding.UTF8.GetBytes(sb.ToString());
return response;
}
diff --git a/DNWS.csproj b/DNWS.csproj
index 26242d2..aa65af3 100644
--- a/DNWS.csproj
+++ b/DNWS.csproj
@@ -6,11 +6,14 @@
-
-
+
+
+
+
+
-
+
-
\ No newline at end of file
+
diff --git a/DNWS260.code-workspace b/DNWS260.code-workspace
new file mode 100644
index 0000000..876a149
--- /dev/null
+++ b/DNWS260.code-workspace
@@ -0,0 +1,8 @@
+{
+ "folders": [
+ {
+ "path": "."
+ }
+ ],
+ "settings": {}
+}
\ No newline at end of file
diff --git a/DelayPlugin.cs b/DelayPlugin.cs
index 006ab1e..08a8fff 100644
--- a/DelayPlugin.cs
+++ b/DelayPlugin.cs
@@ -26,7 +26,7 @@ public HTTPResponse GetResponse(HTTPRequest request)
delay = Convert.ToInt32(parts[1]);
} catch (Exception ex) {
response = new HTTPResponse(400);
- response.body = Encoding.UTF8.GetBytes(ex.ToString());
+ response.Body = Encoding.UTF8.GetBytes(ex.ToString());
return response;
}
@@ -38,7 +38,7 @@ public HTTPResponse GetResponse(HTTPRequest request)
sb.Append("");
sb.Append("Sleep for " + delay + " millisecond.
");
sb.Append("");
- response.body = Encoding.UTF8.GetBytes(sb.ToString());
+ response.Body = Encoding.UTF8.GetBytes(sb.ToString());
return response;
}
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..8008971
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,16 @@
+FROM microsoft/dotnet:2.0-sdk AS build-env
+WORKDIR /app
+
+COPY *.csproj ./
+RUN dotnet restore
+COPY . ./
+RUN dotnet publish -c Release -r linux-x64 -o out
+#RUN dotnet publish -c Release -o out
+
+FROM microsoft/dotnet:2.0-runtime-deps
+WORKDIR /app
+COPY --from=build-env /app/out ./
+#COPY /app/out ./
+COPY ./config.json /app/out
+COPY ./index.html /app/out
+ENTRYPOINT [ "/app/DNWS" ]
\ No newline at end of file
diff --git a/GPUPlugin.cs b/GPUPlugin.cs
new file mode 100644
index 0000000..222eae4
--- /dev/null
+++ b/GPUPlugin.cs
@@ -0,0 +1,200 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading;
+
+using OpenCL.Net.Extensions;
+using OpenCL.Net;
+using System.Linq;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
+namespace DNWS
+{
+ class GPUPlugin : IPluginWithParameters
+ {
+ private Context _context;
+ private Device _device;
+ private Dictionary _parameters;
+ private bool _isInit = false;
+
+ public GPUPlugin()
+ {
+ }
+
+ private void init()
+ {
+ ErrorCode error;
+
+ // Get platform info
+ Platform[] platforms = Cl.GetPlatformIDs(out error);
+ List devicesList = new List();
+
+ LogError (error, "Cl.GetPlaformIDs");
+
+ DeviceType deviceType = DeviceType.Default;
+ switch(_parameters["DeviceType"]) {
+ case "Gpu":
+ deviceType = DeviceType.Gpu;
+ break;
+ case "Cpu":
+ deviceType = DeviceType.Cpu;
+ break;
+ case "All":
+ deviceType = DeviceType.All;
+ break;
+ case "Accelerator":
+ deviceType = DeviceType.Accelerator;
+ break;
+ }
+
+ // Get available devices
+ foreach (Platform platform in platforms) {
+ string platformName = Cl.GetPlatformInfo(platform, PlatformInfo.Name, out error).ToString();
+ Console.WriteLine("Platform: " + platformName);
+ LogError (error, "Cl.GetPlatformInfo");
+ foreach (Device device in Cl.GetDeviceIDs(platform, deviceType, out error)) {
+ LogError(error, "Cl.GetDeviceIDs");
+ Console.WriteLine("Device:" + device.ToString() );
+ devicesList.Add(device);
+ }
+ }
+
+ if(devicesList.Count <= 0) {
+ Console.WriteLine("No devices found.");
+ return;
+ }
+
+ _device = devicesList[0];
+ if(Cl.GetDeviceInfo(_device, DeviceInfo.ImageSupport, out error).CastTo() == OpenCL.Net.Bool.False)
+ {
+ Console.WriteLine("No image support.");
+ return;
+ }
+ _context = Cl.CreateContext(null, 1, new[] {_device}, ContextNotify, IntPtr.Zero, out error);
+ LogError(error, "Cl.CreateContext");
+
+
+ }
+
+ private void ContextNotify(string errInfo, byte[] data, IntPtr cb, IntPtr userData) {
+ Console.WriteLine("OpenCL Notification: " + errInfo);
+ }
+
+ public void PreProcessing(HTTPRequest request)
+ {
+ throw new NotImplementedException();
+ }
+
+ private void LogError(ErrorCode err, string name)
+ {
+ if (err != ErrorCode.Success) {
+ Console.WriteLine("ERROR: " + name + " (" + err.ToString() + ")");
+ }
+ }
+
+ private StringBuilder GenUploadForm()
+ {
+ StringBuilder sb = new StringBuilder();
+ sb.Append("");
+ return sb;
+ }
+
+ public HTTPResponse GetResponse(HTTPRequest request)
+ {
+ HTTPResponse response = new HTTPResponse(200);
+ StringBuilder sb = new StringBuilder();
+ ErrorCode error;
+
+ if(!_isInit) {
+ init();
+ _isInit = true;
+ }
+
+ if (request.Method == HTTPRequest.METHOD_GET) {
+ sb.Append("");
+ sb.Append(GenUploadForm());
+ sb.Append("");
+ response.Body = Encoding.UTF8.GetBytes(sb.ToString());
+ return response;
+ } else if (request.Method == HTTPRequest.METHOD_POST) {
+ sb.Append(request.Body);
+ response.Body = Encoding.UTF8.GetBytes(sb.ToString());
+ string programPath = System.Environment.CurrentDirectory + "/Kernel.cl";
+ if(!System.IO.File.Exists(programPath)) {
+ Console.WriteLine("Program doesn't exist at path " + programPath);
+ return new HTTPResponse(404);
+ }
+
+ sb.Append("");
+ string programSource = System.IO.File.ReadAllText(programPath);
+ using (OpenCL.Net.Program program = Cl.CreateProgramWithSource(_context, 1, new[] {programSource}, null, out error)) {
+ LogError(error, "Cl.CreateProgramWithSource");
+ error = Cl.BuildProgram(program, 1, new[] {_device}, string.Empty, null, IntPtr.Zero);
+ LogError(error, "Cl.BuildProgram");
+ if (Cl.GetProgramBuildInfo (program, _device, ProgramBuildInfo.Status, out error).CastTo()
+ != BuildStatus.Success) {
+ LogError(error, "Cl.GetProgramBuildInfo");
+ Console.WriteLine("Cl.GetProgramBuildInfo != Success");
+ Console.WriteLine(Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Log, out error));
+ return new HTTPResponse(404);
+ }
+ Kernel kernel = Cl.CreateKernel(program, "answer", out error);
+ LogError(error, "Cl.CreateKernel");
+
+ Random rand = new Random();
+ int[] input = (from i in Enumerable.Range(0, 100) select (int)rand.Next()).ToArray();
+ int[] output = new int[100];
+
+ var buffIn = _context.CreateBuffer(input, MemFlags.ReadOnly);
+ var buffOut = _context.CreateBuffer(output, MemFlags.WriteOnly);
+ int IntPtrSize = Marshal.SizeOf(typeof(IntPtr));
+ error = Cl.SetKernelArg(kernel, 0, (IntPtr)IntPtrSize, buffIn);
+ error |= Cl.SetKernelArg(kernel, 1, (IntPtr)IntPtrSize, buffOut);
+ LogError(error, "Cl.SetKernelArg");
+ CommandQueue cmdQueue = Cl.CreateCommandQueue(_context, _device, (CommandQueueProperties)0, out error);
+ LogError(error, "Cl.CreateCommandQueue");
+ Event clevent;
+ error = Cl.EnqueueNDRangeKernel(cmdQueue, kernel, 2, null, new[]{(IntPtr)100,(IntPtr)1}, null, 0, null, out clevent);
+ LogError(error, "Cl.EnqueueNDRangeKernel");
+ error = Cl.Finish(cmdQueue);
+ LogError(error, "Cl.Finih");
+ error = Cl.EnqueueReadBuffer(cmdQueue, buffOut, OpenCL.Net.Bool.True, 0, 100, output, 0, null, out clevent);
+ LogError(error, "Cl.EnqueueReadBuffer");
+ error = Cl.Finish(cmdQueue);
+ LogError(error, "Cl.Finih");
+
+
+ Cl.ReleaseKernel(kernel);
+ Cl.ReleaseCommandQueue(cmdQueue);
+ Cl.ReleaseMemObject(buffIn);
+ Cl.ReleaseMemObject(buffOut);
+ sb.Append("");
+ for(int i = 0; i != 100; i++) {
+ sb.Append(input[i] + " % 42 = " + output[i] + "
");
+ }
+ sb.Append("");
+ }
+ sb.Append("");
+ response.Body = Encoding.UTF8.GetBytes(sb.ToString());
+ return response;
+ }
+ return new HTTPResponse(501);
+ }
+
+ public HTTPResponse PostProcessing(HTTPResponse response)
+ {
+ throw new NotImplementedException();
+ }
+
+ public void SetParameters(Dictionary parameters)
+ {
+ _parameters = parameters;
+ }
+ }
+}
\ No newline at end of file
diff --git a/HTTPRequest.cs b/HTTPRequest.cs
index 232dee7..37c01e4 100644
--- a/HTTPRequest.cs
+++ b/HTTPRequest.cs
@@ -7,10 +7,14 @@ namespace DNWS
{
public class HTTPRequest
{
+ public const string METHOD_POST = "POST";
+ public const string METHOD_GET = "GET";
+ public const string METHOD_DELETE = "DELETE";
+ public const string METHOD_OPTIONS = "OPTIONS";
protected String _url;
protected String _filename;
- protected static Dictionary _propertyListDictionary = null;
- protected static Dictionary _requestListDictionary = null;
+ protected Dictionary _propertyListDictionary = null;
+ protected Dictionary _requestListDictionary = null;
protected String _body;
@@ -57,11 +61,15 @@ public HTTPRequest(String request)
_status = 401;
return;
}
- if (!statusLine[0].ToLower().Equals("get"))
+ if (statusLine[0].ToLower().Equals("get"))
{
- _method = "GET";
- } else if(!statusLine[0].ToLower().Equals("post")) {
- _method = "POST";
+ _method = METHOD_GET;
+ } else if(statusLine[0].ToLower().Equals("post")) {
+ _method = METHOD_POST;
+ } else if(statusLine[0].ToLower().Equals("delete")) {
+ _method = METHOD_DELETE;
+ } else if(statusLine[0].ToLower().Equals("options")) {
+ _method = METHOD_OPTIONS;
} else {
_status = 501;
return;
@@ -81,7 +89,7 @@ public HTTPRequest(String request)
if (parts.Length > 1) {
String[] requestParts = Regex.Split(parts[1], "[=]");
if(requestParts.Length > 1) {
- _requestListDictionary.Add(requestParts[0], requestParts[1]);
+ AddRequest(requestParts[0], requestParts[1]);
}
}
}
@@ -94,14 +102,18 @@ public HTTPRequest(String request)
if(pair.Length == 1) { // handle post body
if(pair[0].Length > 1) { //FIXME, this is a quick hack
Dictionary _bodys = pair[0].Split('&').Select(x => x.Split('=')).ToDictionary(x => x[0].ToLower(), x => x[1]);
- _requestListDictionary = _requestListDictionary.Concat(_bodys).ToDictionary(x=>x.Key, x=>x.Value);
+ foreach(KeyValuePair entry in _bodys) {
+ if(!_requestListDictionary.ContainsKey(entry.Key)) {
+ AddRequest(entry.Key, entry.Value);
+ }
+ }
}
} else { // Length == 2, GET url request
- addProperty(pair[0], pair[1]);
+ AddProperty(pair[0], pair[1]);
}
}
}
- public String getPropertyByKey(String key)
+ public String GetPropertyByKey(String key)
{
if(_propertyListDictionary.ContainsKey(key.ToLower())) {
return _propertyListDictionary[key.ToLower()];
@@ -109,7 +121,7 @@ public String getPropertyByKey(String key)
return null;
}
}
- public String getRequestByKey(String key)
+ public String GetRequestByKey(String key)
{
if(_requestListDictionary.ContainsKey(key.ToLower())) {
return _requestListDictionary[key.ToLower()];
@@ -118,13 +130,13 @@ public String getRequestByKey(String key)
}
}
- public void addProperty(String key, String value)
+ public void AddProperty(String key, String value)
{
- _propertyListDictionary[key.ToLower()] = value;
+ _propertyListDictionary.Add(key.ToLower(), value.TrimEnd('\r', '\n'));
}
- public void addRequest(String key, String value)
+ public void AddRequest(String key, String value)
{
- _requestListDictionary[key.ToLower()] = value;
+ _requestListDictionary.Add(key.ToLower(), value.TrimEnd('\r', '\n'));
}
}
}
\ No newline at end of file
diff --git a/HTTPResponse.cs b/HTTPResponse.cs
index 6f744d4..ecd91c1 100644
--- a/HTTPResponse.cs
+++ b/HTTPResponse.cs
@@ -10,14 +10,14 @@ namespace DNWS
public class HTTPResponse
{
protected int _status = 404;
- public int status
+ public int Status
{
get { return _status; }
set { _status = value; }
}
protected byte[] _body;
- public byte[] body
+ public byte[] Body
{
get { return _body; }
set { _body = value; }
@@ -25,13 +25,40 @@ public byte[] body
protected string _type = "text/html";
- public string type
+ public string Type
{
get { return _type; }
set { _type = value; }
}
- public String header
+ Dictionary _customHeader = new Dictionary();
+
+ public Dictionary CustomHeader
+ {
+ get
+ {
+ return _customHeader;
+ }
+ set
+ {
+ _customHeader = value;
+ }
+ }
+
+ public bool AddCustomHeader(string key, string value)
+ {
+ if(_customHeader.ContainsKey(key)) {
+ return false;
+ }
+ _customHeader.Add(key, value);
+ return true;
+ }
+ public void SetBody(string msg)
+ {
+ Body = Encoding.UTF8.GetBytes(msg);
+ }
+
+ public String Header
{
get
{
@@ -41,6 +68,12 @@ public String header
case 200:
headerResponse.Append("200 OK");
break;
+ case 201:
+ headerResponse.Append("201 Created");
+ break;
+ case 301:
+ headerResponse.Append("301 Moved Permanently");
+ break;
case 400:
headerResponse.Append("400 Bad Request");
break;
@@ -59,9 +92,15 @@ public String header
}
headerResponse.Append("\r\n");
- headerResponse.Append("Content-Type: ").Append(type).Append("\r\n");
+ headerResponse.Append("Content-Type: ").Append(Type).Append("\r\n");
headerResponse.Append("Connection: close\r\n");
headerResponse.Append("Server: DNWS 1.0\r\n");
+ headerResponse.Append("Access-Control-Allow-Origin: *\r\n");
+ headerResponse.Append("Access-Control-Allow-Headers: Content-Type, X-session \r\n");
+ headerResponse.Append("Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE\r\n");
+ foreach(KeyValuePair entry in _customHeader) {
+ headerResponse.Append(entry.Key).Append(": ").Append(entry.Value).Append("\r\n");
+ }
headerResponse.Append("\r\n");
return headerResponse.ToString();
}
diff --git a/IPlugin.cs b/IPlugin.cs
index cf7606b..25eadea 100644
--- a/IPlugin.cs
+++ b/IPlugin.cs
@@ -1,3 +1,4 @@
+using System.Collections.Generic;
namespace DNWS
{
@@ -8,4 +9,9 @@ public interface IPlugin
HTTPResponse GetResponse(HTTPRequest request);
}
+ public interface IPluginWithParameters : IPlugin
+ {
+ void SetParameters(Dictionary parameters);
+ }
+
}
\ No newline at end of file
diff --git a/Kernel.cl b/Kernel.cl
new file mode 100644
index 0000000..eea8abc
--- /dev/null
+++ b/Kernel.cl
@@ -0,0 +1,5 @@
+__kernel void answer(__global int* a, __global int* b)
+{
+ int id = get_global_id(0);
+ b[id] = a[id] % 42;
+}
\ No newline at end of file
diff --git a/OXPlugin.cs b/OXPlugin.cs
index 63754de..5aaf7ec 100644
--- a/OXPlugin.cs
+++ b/OXPlugin.cs
@@ -589,7 +589,7 @@ public HTTPResponse GetResponse(HTTPRequest request)
}
}
}
- response.body = Encoding.UTF8.GetBytes(sb.ToString());
+ response.Body = Encoding.UTF8.GetBytes(sb.ToString());
return response;
}
diff --git a/Program.cs b/Program.cs
index 3fad0a2..76ca2d1 100644
--- a/Program.cs
+++ b/Program.cs
@@ -38,51 +38,130 @@ static void Main(string[] args)
}
}
- ///
- /// HTTP processor will process each http request
- ///
+ public class PluginInfo
+ {
+ protected string _path;
+ protected string _type;
+ protected bool _preprocessing;
+ protected bool _postprocessing;
+ protected IPlugin _reference;
+ protected Dictionary _parameters;
- public class HTTPProcessor
+ public string path
+ {
+ get { return _path;}
+ set {_path = value;}
+ }
+ public string type
+ {
+ get { return _type;}
+ set {_type = value;}
+ }
+ public bool preprocessing
+ {
+ get { return _preprocessing;}
+ set {_preprocessing = value;}
+ }
+ public bool postprocessing
+ {
+ get { return _postprocessing;}
+ set {_postprocessing = value;}
+ }
+ public IPlugin reference
+ {
+ get { return _reference;}
+ set {_reference = value;}
+ }
+
+ public Dictionary parameters
+ {
+ get {return _parameters;}
+ set {_parameters = value;}
+ }
+
+ }
+
+ public class PluginManager
{
- protected class PluginInfo
+ private static PluginManager _instance = null;
+ private Dictionary plugins = null;
+ private Program _parent;
+
+ private PluginManager()
{
- protected string _path;
- protected string _type;
- protected bool _preprocessing;
- protected bool _postprocessing;
- protected IPlugin _reference;
- public string path
- {
- get { return _path;}
- set {_path = value;}
- }
- public string type
- {
- get { return _type;}
- set {_type = value;}
- }
- public bool preprocessing
- {
- get { return _preprocessing;}
- set {_preprocessing = value;}
+ }
+
+ private void SetParent(Program parent)
+ {
+ _parent = parent;
+ }
+
+ /* Singletron
+ */
+ public static PluginManager GetInstance(Program parent)
+ {
+ if (_instance == null) {
+ _instance = new PluginManager();
}
- public bool postprocessing
+ _instance.SetParent(parent);
+ return _instance;
+ }
+
+ public Dictionary Plugins
+ {
+ get
{
- get { return _postprocessing;}
- set {_postprocessing = value;}
+ return plugins;
}
- public IPlugin reference
+ }
+
+ public void LoadConfiguration(IEnumerable sections)
+ {
+ if (plugins == null)
{
- get { return _reference;}
- set {_reference = value;}
+ plugins = new Dictionary();
+ foreach (ConfigurationSection section in sections)
+ {
+ PluginInfo pi = new PluginInfo();
+ Dictionary parameters = null;
+ pi.path = section["Path"];
+ pi.type = section["Class"];
+ pi.preprocessing = section["Preprocessing"].ToLower().Equals("true");
+ pi.postprocessing = section["Postprocessing"].ToLower().Equals("true");
+ foreach(ConfigurationSection parameter in section.GetSection("Parameters").GetChildren()) {
+ if (parameters == null) parameters = new Dictionary();
+ parameters[parameter.Key] = parameter.Value;
+ }
+ try {
+ if(parameters != null) {
+ IPluginWithParameters ip = (IPluginWithParameters)Activator.CreateInstance(Type.GetType(pi.type));
+ ip.SetParameters(parameters);
+ pi.reference = (IPlugin) ip;
+ } else {
+ pi.reference = (IPlugin)Activator.CreateInstance(Type.GetType(pi.type));
+ }
+ } catch (Exception ex) {
+ _parent.Log("Error loading plugin " + pi.path + " with error " + ex);
+ continue;
+ }
+ plugins[section["Path"]] = pi;
+ _parent.Log("Plugin " + pi.path + " loaded.");
+ }
}
}
+ }
+ ///
+ /// HTTP processor will process each http request
+ ///
+
+ public class HTTPProcessor
+ {
// Get config from config manager, e.g., document root and port
protected string ROOT = Program.Configuration["DocumentRoot"];
protected Socket _client;
protected Program _parent;
- protected Dictionary plugins;
+ protected PluginManager PM;
///
/// Constructor, set the client socket and parent ref, also init stat hash
@@ -93,18 +172,9 @@ public HTTPProcessor(Socket client, Program parent)
{
_client = client;
_parent = parent;
- plugins = new Dictionary();
// load plugins
- var sections = Program.Configuration.GetSection("Plugins").GetChildren();
- foreach(ConfigurationSection section in sections) {
- PluginInfo pi = new PluginInfo();
- pi.path = section["Path"];
- pi.type = section["Class"];
- pi.preprocessing = section["Preprocessing"].ToLower().Equals("true");
- pi.postprocessing = section["Postprocessing"].ToLower().Equals("true");
- pi.reference = (IPlugin) Activator.CreateInstance(Type.GetType(pi.type));
- plugins[section["Path"]] = pi;
- }
+ PM = PluginManager.GetInstance(_parent);
+ PM.LoadConfiguration(Program.Configuration.GetSection("Plugins").GetChildren());
}
///
@@ -118,31 +188,39 @@ protected HTTPResponse getFile(String path)
// Guess the content type from file extension
string fileType = "text/html";
- if (path.ToLower().EndsWith("jpg") || path.ToLower().EndsWith("jpeg"))
+ if (path.ToLower().EndsWith(".jpg") || path.ToLower().EndsWith(".jpeg"))
{
fileType = "image/jpeg";
}
- if (path.ToLower().EndsWith("png"))
+ else if (path.ToLower().EndsWith(".png"))
{
fileType = "image/png";
}
+ else if (path.ToLower().EndsWith(".js"))
+ {
+ fileType = "application/javascript";
+ }
+ else if (path.ToLower().EndsWith(".css"))
+ {
+ fileType = "text/css";
+ }
// Try to read the file, if not found then 404, otherwise, 500.
try
{
response = new HTTPResponse(200);
- response.type = fileType;
- response.body = System.IO.File.ReadAllBytes(path);
+ response.Type = fileType;
+ response.Body = System.IO.File.ReadAllBytes(path);
}
catch (FileNotFoundException ex)
{
response = new HTTPResponse(404);
- response.body = Encoding.UTF8.GetBytes("404 Not found
" + ex.Message);
+ response.Body = Encoding.UTF8.GetBytes("404 Not found
" + ex.Message);
}
catch (Exception ex)
{
response = new HTTPResponse(500);
- response.body = Encoding.UTF8.GetBytes("500 Internal Server Error
" + ex.Message);
+ response.Body = Encoding.UTF8.GetBytes("500 Internal Server Error
" + ex.Message);
}
return response;
@@ -154,21 +232,22 @@ protected HTTPResponse getFile(String path)
public void Process()
{
NetworkStream ns = new NetworkStream(_client);
- string requestStr = "";
+ StringBuilder requestStr = new StringBuilder();
HTTPRequest request = null;
HTTPResponse response = null;
byte[] bytes = new byte[1024];
int bytesRead;
+
// Read all request
do
{
bytesRead = ns.Read(bytes, 0, bytes.Length);
- requestStr += Encoding.UTF8.GetString(bytes, 0, bytesRead);
+ requestStr.Append(Encoding.UTF8.GetString(bytes, 0, bytesRead));
} while (ns.DataAvailable);
- request = new HTTPRequest(requestStr);
- request.addProperty("RemoteEndPoint", _client.RemoteEndPoint.ToString());
+ request = new HTTPRequest(requestStr.ToString());
+ request.AddProperty("RemoteEndPoint", _client.RemoteEndPoint.ToString());
// We can handle only GET now
if(request.Status != 200) {
@@ -177,15 +256,19 @@ public void Process()
else
{
bool processed = false;
+ //FIXME, this seem duplicate with HTTPRequest
+ string[] requestUrls = request.Url.Split("/");
+ string[] paths = requestUrls[1].Split("?");
// pre processing
- foreach(KeyValuePair plugininfo in plugins) {
+ foreach(KeyValuePair plugininfo in PM.Plugins) {
if(plugininfo.Value.preprocessing) {
plugininfo.Value.reference.PreProcessing(request);
}
}
// plugins
- foreach(KeyValuePair plugininfo in plugins) {
- if(request.Filename.StartsWith(plugininfo.Key)) {
+ foreach(KeyValuePair plugininfo in PM.Plugins) {
+ if(paths[0].Equals(plugininfo.Key, StringComparison.InvariantCultureIgnoreCase)) {
+ //if(request.Url.StartsWith("/" + plugininfo.Key)) {
response = plugininfo.Value.reference.GetResponse(request);
processed = true;
}
@@ -194,24 +277,24 @@ public void Process()
if(!processed) {
if (request.Filename.Equals(""))
{
- response = getFile(ROOT + "/index.html");
+ response = getFile(ROOT + "/" + request.Url + "/index.html");
}
else
{
- response = getFile(ROOT + "/" + request.Filename);
+ response = getFile(ROOT + "/" + request.Url);
}
}
// post processing pipe
- foreach(KeyValuePair plugininfo in plugins) {
+ foreach(KeyValuePair plugininfo in PM.Plugins) {
if(plugininfo.Value.postprocessing) {
response = plugininfo.Value.reference.PostProcessing(response);
}
}
}
// Generate response
- ns.Write(Encoding.UTF8.GetBytes(response.header), 0, response.header.Length);
- if(response.body != null) {
- ns.Write(response.body, 0, response.body.Length);
+ ns.Write(Encoding.UTF8.GetBytes(response.Header), 0, response.Header.Length);
+ if(response.Body != null) {
+ ns.Write(response.Body, 0, response.Body.Length);
}
// Shuting down
diff --git a/StatPlugin.cs b/StatPlugin.cs
index aec7606..160264d 100644
--- a/StatPlugin.cs
+++ b/StatPlugin.cs
@@ -27,7 +27,7 @@ public void PreProcessing(HTTPRequest request)
statDictionary[request.Url] = 1;
}
}
- public HTTPResponse GetResponse(HTTPRequest request)
+ public virtual HTTPResponse GetResponse(HTTPRequest request)
{
HTTPResponse response = null;
StringBuilder sb = new StringBuilder();
@@ -38,7 +38,7 @@ public HTTPResponse GetResponse(HTTPRequest request)
}
sb.Append("