Example #1
0
 public virtual bool Process(HttpServer server, HttpRequest request, HttpResponse response)
 {
     string fn = server.GetFilename(request);
     if(!File.Exists(fn)){
         response.ReturnCode = 404;
         response.Content = "File not found.";
         return true;
     }
     string ext = Path.GetExtension(fn);
     string mime = (string)MimeTypes[ext];
     if(mime == null) mime = "application/octet-stream";
     response.ContentType =  mime;
     try {
         if(mime.Substring(0, 5) == "text/") {
             // Mime type 'text' is substituted
             StreamReader sr = new StreamReader(fn);
             response.Content = sr.ReadToEnd();
             sr.Close();
             if(substitute){
                 // Do substitutions
                 Regex regex = new Regex(@"\<\%(?<tag>[^>]+)\>");
                 lock(this){
                     req = request;
                     response.Content = regex.Replace(response.Content, new MatchEvaluator(RegexMatch));
                 }
             }
         } else {
             FileStream fs = File.Open(fn, FileMode.Open);
             byte[] buf = new byte[fs.Length];
             fs.Read(buf, 0, buf.Length);
             fs.Close();
             response.RawContent = buf;
         }
     } catch(Exception e) {
         response.ReturnCode = 500;
         response.Content = "Error reading file: "+e;
         return true;
     }
     return true;
 }
Example #2
0
 void SendResponse(ClientInfo ci, HttpRequest req, HttpResponse resp, bool close)
 {
     #if DEBUG
     Console.WriteLine("Response: "+resp.ReturnCode + Responses[resp.ReturnCode]);
     #endif
     ByteBuilder bb = new ByteBuilder();
     bb.Add(Encoding.UTF8.GetBytes("HTTP/1.1 " + resp.ReturnCode + " " + Responses[resp.ReturnCode] +
             "\r\nDate: "+DateTime.Now.ToString("R")+
             "\r\nServer: RedCoronaEmbedded/1.0"+
             "\r\nConnection: "+(close ? "close" : "Keep-Alive")));
     bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Encoding: " + (resp.Encoding == null ? "utf-8" : resp.Encoding)));
     if (resp.RawContent == null)
         bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Length: " + resp.Content.Length));
     else
         bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Length: " + resp.RawContent.Length));
     if(resp.ContentType != null)
         bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Type: "+resp.ContentType));
     if(req.Session != null) bb.Add(Encoding.UTF8.GetBytes("\r\nSet-Cookie: _sessid="+req.Session.ID+"; path=/"));
     foreach(KeyValuePair<string, string> de in resp.Header) bb.Add(Encoding.UTF8.GetBytes("\r\n" + de.Key + ": " + de.Value));
     bb.Add(Encoding.UTF8.GetBytes("\r\n\r\n")); // End of header
     if(resp.RawContent != null) bb.Add(resp.RawContent);
     else bb.Add(Encoding.UTF8.GetBytes(resp.Content));
     ci.Send(bb.Read(0, bb.Length));
     #if DEBUG
     Console.WriteLine("** SENDING\n"+resp.Content);
     #endif
     if(close) ci.Close();
 }
Example #3
0
 public bool Process(HttpServer server, HttpRequest req, HttpResponse resp)
 {
     #if DEBUG
     Console.WriteLine("Processing "+req);
     #endif
     server.RequestSession(req);
     StringBuilder sb = new StringBuilder();
     sb.Append("<h3>Session</h3>");
     sb.Append("<p>ID: "+req.Session.ID+"<br>User: "+req.Session.User);
     sb.Append("<h3>Header</h3>");
     sb.Append("Method: "+req.Method+"; URL: '"+req.Url+"'; HTTP version "+req.HttpVersion+"<p>");
     foreach(KeyValuePair<string, string> ide in req.Header) sb.Append(" "+ide.Key +": "+ide.Value+"<br>");
     sb.Append("<h3>Cookies</h3>");
     foreach(KeyValuePair<string, string> ide in req.Cookies) sb.Append(" "+ide.Key +": "+ide.Value+"<br>");
     sb.Append("<h3>Query</h3>");
     foreach(KeyValuePair<string, string> ide in req.Query) sb.Append(" "+ide.Key +": "+ide.Value+"<br>");
     sb.Append("<h3>Content</h3>");
     sb.Append(req.Content);
     resp.Content = sb.ToString();
     return true;
 }
Example #4
0
 protected virtual bool Process(ClientInfo ci, HttpRequest req)
 {
     HttpResponse resp = new HttpResponse();
     resp.Url = req.Url;
     for(int i = handlers.Count - 1; i >= 0; i--){
         IHttpHandler handler = (IHttpHandler)handlers[i];
         if(handler.Process(this, req, resp)){
             SendResponse(ci, req, resp, resp.ReturnCode != 200);
             return resp.ReturnCode != 200;
         }
     }
     return true;
 }
Example #5
0
            public override bool Process(HttpServer server, HttpRequest request, HttpResponse response)
            {
                if (request.Page.StartsWith("/status"))
                {
                    response.ContentType = (string)SubstitutingFileReader.MimeTypes[".html"];
                    response.ReturnCode = 200;
                    StringBuilder sb = new StringBuilder();
                    StringWriter sw = new StringWriter(sb);

                    using (JsonWriter jsonWriter = new JsonTextWriter(sw))
                    {
                        jsonWriter.Formatting = Formatting.Indented;
                        jsonWriter.WriteStartObject();
                        jsonWriter.WritePropertyName("twain_source");
                        jsonWriter.WriteValue(Properties.Settings.Default.twain_source);
                        jsonWriter.WriteComment("ID of selected TWAIN source");

                        jsonWriter.WritePropertyName("x");
                        jsonWriter.WriteValue(Properties.Settings.Default.x);
                        jsonWriter.WriteComment("The x-coordinate of the upper-left corner of the crop rectangle");

                        jsonWriter.WritePropertyName("y");
                        jsonWriter.WriteValue(Properties.Settings.Default.y);
                        jsonWriter.WriteComment("The y-coordinate of the upper-left corner of the crop rectangle");

                        jsonWriter.WritePropertyName("w");
                        jsonWriter.WriteValue(Properties.Settings.Default.w);
                        jsonWriter.WriteComment("The width of the crop rectangle");

                        jsonWriter.WritePropertyName("h");
                        jsonWriter.WriteValue(Properties.Settings.Default.h);
                        jsonWriter.WriteComment("The height of the crop rectangle");

                        jsonWriter.WritePropertyName("encode");
                        jsonWriter.WriteValue(Properties.Settings.Default.encode);
                        jsonWriter.WriteComment("Encoding setup");

                        jsonWriter.WritePropertyName("server_autostart");
                        jsonWriter.WriteValue(Properties.Settings.Default.server_autostart);
                        jsonWriter.WriteComment("Shall web server be started automatically");

                        jsonWriter.WritePropertyName("start_minimized");
                        jsonWriter.WriteValue(Properties.Settings.Default.start_minimized);
                        jsonWriter.WriteComment("Shall application start minimized");

                        jsonWriter.WritePropertyName("port");
                        jsonWriter.WriteValue(Properties.Settings.Default.port);
                        jsonWriter.WriteComment("Web server listening port");

                        jsonWriter.WritePropertyName("dpi");
                        jsonWriter.WriteValue(Properties.Settings.Default.dpi);
                        jsonWriter.WriteComment("DPI");

                        jsonWriter.WritePropertyName("colour");
                        jsonWriter.WriteValue(Properties.Settings.Default.colour == ColourSetting.Colour ? "full" : Properties.Settings.Default.colour == ColourSetting.GreyScale ? "greyscale" : "blackandwhite");
                        jsonWriter.WriteComment("Colouring setup");

                        jsonWriter.WritePropertyName("adf");
                        jsonWriter.WriteValue(Properties.Settings.Default.useADF);
                        jsonWriter.WriteComment("Shall ADF be used?");
                        jsonWriter.WriteEndObject();
                    }

                    response.Content = sb.ToString();
                    return true;
                }
                return false;
            }
Example #6
0
            public override bool Process(HttpServer server, HttpRequest request, HttpResponse response)
            {
                if (request.Page.StartsWith("/sources"))
                {
                    response.ContentType = (string)SubstitutingFileReader.MimeTypes[".html"];
                    response.ReturnCode = 200;
                    StringBuilder sb = new StringBuilder();
                    StringWriter sw = new StringWriter(sb);

                    using (JsonWriter jsonWriter = new JsonTextWriter(sw))
                    {
                        jsonWriter.Formatting = Formatting.Indented;
                        jsonWriter.WriteStartObject();
                        foreach (string name in this.mainForm.twain.SourceNames)
                        {
                            jsonWriter.WritePropertyName(name);
                            jsonWriter.WriteValue(System.Web.HttpUtility.UrlEncode(name));
                        }
                        jsonWriter.WriteEndObject();
                    }

                    response.Content = sb.ToString();
                    return true;
                }
                return false;
            }
Example #7
0
            public override bool Process(HttpServer server, HttpRequest request, HttpResponse response)
            {
                if (request.Page.StartsWith("/scan"))
                {
                    string source = Properties.Settings.Default.twain_source;
                    int x = Properties.Settings.Default.x;
                    int y = Properties.Settings.Default.y;
                    int w = Properties.Settings.Default.w;
                    int h = Properties.Settings.Default.h;
                    string encode = Properties.Settings.Default.encode;
                    int dpi = Properties.Settings.Default.dpi;
                    bool adf = Properties.Settings.Default.useADF;
                    bool pdf = Properties.Settings.Default.pdf;
                    ColourSetting colour = Properties.Settings.Default.colour;

                    try
                    {
                        if (request.Query.ContainsKey("source"))
                        {
                            source = System.Web.HttpUtility.UrlDecode(request.Query["source"]);
                            if (!this.mainForm.twain.SourceNames.Contains(source))
                            {
                                throw new Exception("Unknown source: " + source);
                            }
                        }

                        if (request.Query.ContainsKey("encode"))
                        {
                            encode = request.Query["encode"];
                            if (!"base64".Equals(encode) && !"".Equals(encode))
                                throw new Exception("Unknown encoding: " + encode);
                        }

                        x = ScanHandler.getNumber(request, x, "x");
                        y = ScanHandler.getNumber(request, y, "y");
                        w = ScanHandler.getNumber(request, w, "w");
                        h = ScanHandler.getNumber(request, h, "h");

                        dpi = ScanHandler.getNumber(request, dpi, "dpi");
                        if (!this.mainForm.dpiComboBox.Items.Contains("" + dpi))
                            throw new Exception("Unsupported DPI value: " + dpi);

                        adf = request.Query.ContainsKey("adf") ? "1".Equals(request.Query["adf"]) : adf;
                        pdf = request.Query.ContainsKey("pdf") ? "1".Equals(request.Query["pdf"]) : adf;

                        if (request.Query.ContainsKey("colour"))
                        {
                            string col = request.Query["colour"];
                            if ("full".Equals(col)) colour = ColourSetting.Colour;
                            else if ("greyscale".Equals(col)) colour = ColourSetting.GreyScale;
                            else if ("blackandwhite".Equals(col)) colour = ColourSetting.BlackAndWhite;
                            else throw new Exception("Unknown colour settings: " + col);
                        }
                    }
                    catch (Exception e)
                    {
                        response.ReturnCode = 500;
                        response.Content = "Invalid URL arguments: " + e.Message;
                        return true;
                    }

                    bool testing = request.Query.ContainsKey("test") && "1".Equals(request.Query["test"]);

                    if ("".Equals(source) && !testing)
                    {
                        request.Host = ".";
                        request.Page = "/noscanner.html";
                        response.ReturnCode = 500;
                        return base.Process(server, request, response);
                    }

                    if (this.mainForm.scanSemaphore.WaitOne(0))
                    {
                        this.mainForm.scanData.Clear();
                        this.mainForm.dataReady = false;

                        if (testing)
                        {
                            try
                            {
                                this.mainForm.scanData.Add(new Bitmap("./TestImage.png"));
                            }
                            catch (Exception)
                            {
                                // left blank intentionally
                            }
                            this.mainForm.dataReady = true;
                            this.mainForm.scanSemaphore.Release();
                        }
                        else
                        {
                            this.mainForm.scanTarget = ScanTarget.WEB;
                            this.mainForm.Invoke(new ScanDelegate(Scan), new object[] { source, dpi, colour, adf });

                            DateTime startTime = DateTime.Now;
                            TimeSpan elapsed;
                            do
                            {
                                Thread.Sleep(100);
                                elapsed = DateTime.Now.Subtract(startTime);
                            } while (!this.mainForm.dataReady && elapsed.TotalMinutes < 5);
                        }

                        if (this.mainForm.dataReady && this.mainForm.scanData.Count > 0)
                        {
                            response.ReturnCode = 200;
                            using (MemoryStream ms = new MemoryStream())
                            {
                                if (!adf)
                                {
                                    ScanHandler.SaveImage(x, y, w, h, ms, this.mainForm.scanData.First(), pdf);
                                }
                                else
                                {
                                    ScanHandler.SaveImage(x, y, w, h, ms, this.mainForm.scanData, pdf);
                                }

                                if ("base64".Equals(encode))
                                {
                                    response.ContentType = "text/plain";
                                    response.Encoding = "base64";
                                    response.Content = Convert.ToBase64String(ms.ToArray());
                                }
                                else
                                {
                                    response.ContentType = (adf || pdf) ? "application/octet-stream" : (string)SubstitutingFileReader.MimeTypes[".png"];
                                    response.Encoding = null;
                                    response.RawContent = ms.ToArray();
                                }
                            }
                        }
                        else
                        {
                            request.Host = ".";
                            request.Page = "/failed.html";
                            response.ReturnCode = 500;
                            return base.Process(server, request, response);
                        }
                    }
                    else
                    {
                        request.Host = ".";
                        request.Page = "/blocked.html";
                        response.ReturnCode = 500;
                        return base.Process(server, request, response);
                    }
                    return true;
                }
                return false;
            }
Example #8
0
 public override bool Process(HttpServer server, HttpRequest request, HttpResponse response)
 {
     request.Host = ".";
     request.Page = "/home.html";
     return base.Process(server, request, response);
 }