private HttpResponse processResponse(HttpResponse response)
 {
     foreach (KeyValuePair<String, String> kvp in response.cookies)
     {
         if (cookies.ContainsKey(kvp.Key))
             cookies.Remove(kvp.Key);
         cookies.Add(kvp.Key, kvp.Value);
     }
     return response;
 }
 public bool continueDownload(Stream output, HttpResponse response, Action<int> setup, Action<int> step, Action whenfinished)
 {
     bool tmp = continueDownload(output, response, setup, step);
     whenfinished();
     return tmp;
 }
        public bool continueDownload(Stream output, HttpResponse response, Action<int> setup, Action<int> step)
        {
            if ((int)response.Status < 300)
            {
                try
                {
                    if (!response.headers.ContainsKey("content-length"))
                    {
                        throw new ConnectionException("Content Length needed");
                    }
                    int contentLen = Convert.ToInt32(response.headers["content-length"]);
                    int filepartlen = response.MessageRAW.Length - response.HeadLength;
                    int restLen = contentLen - filepartlen;

                    setup(contentLen);

                    output.Write(response.MessageRAW, response.HeadLength, filepartlen);
                    step(filepartlen);

                    byte[] rest = new byte[DL_CACHE_SIZE]; // 1mb of buffer space
                    int read = 0;
                    while (1 < restLen)
                    {
                        read = stream.Read(rest, 0, rest.Length);
                        output.Write(rest, 0, read);
                        restLen -= read;
                        step(read);
                        output.Flush();
                    }
                }
                catch (FormatException)
                {
                    return false;
                }
                catch (IOException)
                {
                    return false;
                }
                return true;
            }
            else
            {
                throw new ConnectionException("Download failed.");
            }
        }
        public HttpResponse awaitMessage()
        {
            byte[] buffer = new byte[BUFFER_SIZE];
            string message = "";

            HttpResponse response = null;

            bool Cont = true;
            bool ResponseReceived = false;//flag for init
            string tmp = "";
            do
            {
                buffer = new byte[BUFFER_SIZE];
                if ((buffer = this.takeByte(buffer)) == null)
                {
                    Cont = false;
                }
                else
                {
                    message += Encoding.UTF8.GetString(buffer);
                }

                if (!ResponseReceived)
                {
                    var request_line = message.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                    if (HttpResponse.validateResponse(request_line))
                    {
                        response = new HttpResponse(request_line);
                        response.clearMessageBytes();
                        ResponseReceived = true;
                        response.MessageRAW = Encoding.UTF8.GetBytes(message);
                    }
                    else
                    {
                        // wtf is this.. should at least be a header?!
                        tmp += message;
                        continue;
                        //ResponseReceived = false;
                    }
                }
                else
                {
                    // response created. headers should be done.
                    response.MessageRAW = buffer;
                    response.Body = message.Substring(response.HeadLength);
                }
                // Checking for termination - chunked encoding and content-length aware
                if (response.headers.ContainsKey("transfer-encoding") && response.headers["transfer-encoding"].Equals("chunked"))
                {
                    if (message.Contains(CHUNKED_TERMINATOR))
                    {
                        message = message.Remove(message.IndexOf(CHUNKED_TERMINATOR));
                        Cont = false;
                    }
                    ResponseReceived = true;
                }
                else
                {
                    //ResponseReceived = response.Status != 0;
                    if (ResponseReceived)
                    {
                        // The server may not be done spitting info at us
                        // checking content length
                        if (response.headers.ContainsKey("content-length"))
                        {
                            Cont = true; // must set based off content-length
                            int contentLen = Convert.ToInt32(response.headers["content-length"]);
                            if (response.MessageRAW.Length >= contentLen + response.HeadLength)
                            {
                                Cont = false;
                            }
                            else
                            {
                                buffer = new byte[BUFFER_SIZE]; // Careful of them overflowz
                                Cont = true;
                                //if ((buffer = this.takeByte(buffer)) == null)
                                //{
                                //    Cont = false;
                                //}
                                //else
                                //{
                                //    ResponseReceived = true;
                                //    message = Encoding.UTF8.GetString(buffer).Trim();
                                //    response.MessageRAW = buffer;
                                //    response.Body += message;
                                //    if (response.MessageRAW.Length >= contentLen + response.HeadLength)
                                //    {
                                //        Cont = false;
                                //    }
                                //}
                            }
                        }
                        else
                        {
                            if (BUFFER_SIZE == buffer.Length)
                            {
                                // in case terminator perfetly aligns at end
                                if (!message.EndsWith(Environment.NewLine))
                                {
                                    // if buffer full to brim and has EOL
                                    Cont = false;
                                }
                            }
                            else
                            {
                                // if no content-length and buffer not filled
                                Cont = false;
                            }
                        }
                    }
                }
            } while (Cont);

            if (response == null)
            {
                return null;
            }
            // may want to check if return code is > 200 for clearing referer
            return processResponse(response);
        }
        /// <summary>
        /// This method checks that the request path exists in the PAGE_ROOT directory.
        /// Then the content-type is parsed from the request.
        /// An HttpRequest is generated and sent, followed by the file specified.
        /// Call this method conditionally from any subclass unless there are no conditions as to what clients are permitted to GET.
        /// </summary>
        /// <param name="request"></param>
        protected virtual bool processGet(HttpRequest request)
        {
            String relativePath = request.Path;
            if (relativePath.IndexOf('/') == 0)
            {
                relativePath = relativePath.Substring(1);
            }
            HttpResponse response;

            //Keep in mind that File.OpenRead defaultly uses FileShare.Read
            #region "File Checks and Response Generation"
            if (File.Exists(PAGE_ROOT + relativePath))
            {
                String Content = request.requestMetaInfo("Accept");
                response = new HttpResponse(HttpResponse.ConnectionStatus.OK, "keep-alive", PAGE_ROOT + relativePath);
                response.addHeader("Content-Type", request.getGuessFileType());
            }
            else
            {
                if (request.Path.Equals("/"))
                {
                    response = new HttpResponse(HttpResponse.ConnectionStatus.OK, "keep-alive", PAGE_ROOT + @"\" + onInit(request));
                    response.addHeader("Content-Type", "text/html");
                }
                else
                {
                    on404(request);
                    return false;
                }
            }
            #endregion

            using (FileStream s = File.OpenRead(response.FilePath))
            {
                response.addHeader("Content-Length", s.Length.ToString());
                try
                {
                    SocketWriteLine(response.ToString());
                    s.CopyTo(stream);
                }
                catch (SocketException)
                {
                    return false;
                }
                catch (IOException)
                {
                    return false;
                }
            }
            //}
            //catch (IOException e)
            //{
            //    Debug.WriteLine("send failure:  " + request.path);
            //}

            stream.Flush();
            return true;
        }
        protected void writeStream(Stream s, HttpResponse response)
        {
            try
            {
                response.addHeader("Content-Length", s.Length.ToString());
                SocketWriteLine(response.ToString());
                s.CopyTo(stream);
            }
            catch (IOException) { }
            s.Close();

            stream.Flush();
        }
        protected void writeHtmlStream(Stream s, HttpResponse response)
        {
            String html;
            try
            {
                byte[] codedHtml = new byte[s.Length];
                s.Read(codedHtml, 0, (int)s.Length);
                html = Encoding.UTF8.GetString(codedHtml);
                foreach (KeyValuePair<string, string> kp in pageMutations)
                {
                    html = html.Replace(kp.Key, kp.Value);
                }
                response.addHeader("Content-Length", html.Length.ToString());
                SocketWriteLine(response.ToString());
                SocketWriteText(html);
            }
            catch (IOException) { }
            s.Close();

            stream.Flush();
        }
 public void processResponse(HttpResponse r)
 {
     foreach (KeyValuePair<string, string> kvp in r.cookies)
     {
         if (cookies.ContainsKey(kvp.Key))
         {
             cookies.Remove(kvp.Key);
         }
         cookies.Add(kvp.Key, kvp.Value);
     }
 }