-regex, buggy
[oweals/gnunet.git] / src / gns / gnunet-gns-proxy.c
index dd75c2efaa8250073989978b20b39cb2b942037a..2b561d811ab855df0c5e8f23e7f37ab43a80950f 100644 (file)
@@ -20,6 +20,9 @@
 
 #include "platform.h"
 #include <gnunet_util_lib.h>
+#include <microhttpd.h>
+#include <curl/curl.h>
+#include <regex.h>
 #include "gns_proxy_proto.h"
 #include "gns.h"
 
@@ -56,9 +59,6 @@ is_tld(const char* name, const char* tld)
 
 struct Socks5Request
 {
-  struct Socks5Request *prev;
-  struct Socks5Request *next;
-
   struct GNUNET_NETWORK_Handle *sock;
   struct GNUNET_NETWORK_Handle *remote_sock;
 
@@ -75,17 +75,807 @@ struct Socks5Request
   unsigned int wbuf_len;
 };
 
-struct Socks5Connections
+
+#define BUF_WAIT_FOR_CURL 0
+#define BUF_WAIT_FOR_MHD 1
+#define HTML_HDR_CONTENT "Content-Type: text/html\r\n"
+#define RE_DOTPLUS "<a href=\"http://(([A-Za-z]+[.])+)([+])"
+#define RE_N_MATCHES 4
+
+#define HTTP_PORT 80
+#define HTTPS_PORT 443
+
+struct ProxyCurlTask
 {
-  struct Socks5Request *head;
-  struct Socks5Request *tail;
+  //DLL
+  struct ProxyCurlTask *prev;
+  struct ProxyCurlTask *next;
+
+  CURL *curl;
+  char url[2048];
+  char buffer[CURL_MAX_WRITE_SIZE];
+  char *buffer_ptr;
+  int buf_status;
+  unsigned int bytes_downloaded;
+  unsigned int bytes_in_buffer;
+  int download_in_progress;
+  int download_successful;
+  int download_error;
+  struct MHD_Connection *connection;
+  int parse_content;
+  int is_postprocessing;
+
+  GNUNET_SCHEDULER_TaskIdentifier pp_task;
+
+  char pp_buf[256];
+  
 };
 
-
 unsigned long port = GNUNET_GNS_PROXY_PORT;
 static struct GNUNET_NETWORK_Handle *lsock;
 GNUNET_SCHEDULER_TaskIdentifier ltask;
-static struct Socks5Connections s5conns;
+GNUNET_SCHEDULER_TaskIdentifier curl_download_task;
+static struct MHD_Daemon *httpd;
+static GNUNET_SCHEDULER_TaskIdentifier httpd_task;
+CURLM *curl_multi;
+
+struct ProxyCurlTask *ctasks_head;
+struct ProxyCurlTask *ctasks_tail;
+
+static regex_t re_dotplus;
+
+/**
+ * Read HTTP request header field 'Host'
+ *
+ * @param cls buffer to write to
+ * @param kind value kind
+ * @param key field key
+ * @param value field value
+ * @return MHD_NO when Host found
+ */
+static int
+con_val_iter (void *cls,
+              enum MHD_ValueKind kind,
+              const char *key,
+              const char *value)
+{
+  char* buf = (char*)cls;
+
+  if (0 == strcmp ("Host", key))
+  {
+    strcpy (buf, value);
+    return MHD_NO;
+  }
+  return MHD_YES;
+}
+
+
+/**
+ * Check HTTP response header for mime
+ *
+ * @param buffer curl buffer
+ * @param size curl blocksize
+ * @param nmemb curl blocknumber
+ * @param cls handle
+ * @return size of read bytes
+ */
+static size_t
+curl_check_hdr (void *buffer, size_t size, size_t nmemb, void *cls)
+{
+  size_t bytes = size * nmemb;
+  struct ProxyCurlTask *ctask = cls;
+  char hdr[bytes+1];
+
+  memcpy (hdr, buffer, bytes);
+  hdr[bytes] = '\0';
+
+  if (0 == strcmp (hdr, HTML_HDR_CONTENT))
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                "Got HTML HTTP response header\n");
+    ctask->parse_content = GNUNET_YES;
+  }
+
+  return bytes;
+}
+
+/**
+ * schedule mhd
+ */
+static void
+run_httpd (void);
+
+
+/**
+ * Process cURL download bits
+ *
+ * @param ptr buffer with data
+ * @param size size of a record
+ * @param nmemb number of records downloaded
+ * @param ctx context
+ * @return number of processed bytes
+ */
+static size_t
+callback_download (void *ptr, size_t size, size_t nmemb, void *ctx)
+{
+  const char *cbuf = ptr;
+  size_t total;
+  struct ProxyCurlTask *ctask = ctx;
+
+  MHD_run (httpd);
+
+  total = size*nmemb;
+  ctask->bytes_downloaded += total;
+
+  if (total == 0)
+  {
+    return total;
+  }
+
+  if (total > sizeof (ctask->buffer))
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+                "CURL gave us too much data to handle (%d)!\n",
+                total);
+    return 0;
+  }
+  
+  if (ctask->buf_status == BUF_WAIT_FOR_MHD)
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                "CURL: Waiting for MHD (%s)\n", ctask->url);
+    return CURL_WRITEFUNC_PAUSE;
+  }
+
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "CURL: Copying to MHD (%s, %d)\n", ctask->url, total);
+  memcpy (ctask->buffer, cbuf, total);
+  ctask->bytes_in_buffer = total;
+  ctask->buffer_ptr = ctask->buffer;
+
+  ctask->buf_status = BUF_WAIT_FOR_MHD;
+
+  //GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+  //            "cURL chunk:\n%s\n", (char*)ctask->buffer);
+  MHD_run (httpd);
+  return total;
+}
+
+
+
+/**
+ * Callback to free content
+ *
+ * @param cls content to free
+ */
+static void
+mhd_content_free (void *cls)
+{
+  struct ProxyCurlTask *ctask = cls;
+
+  if (ctask->curl != NULL)
+    curl_easy_cleanup (ctask->curl);
+
+  GNUNET_free (ctask);
+
+}
+
+static void
+postprocess_name (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  struct ProxyCurlTask *ctask = cls;
+  char tmp[strlen(ctask->pp_buf)];
+
+  sprintf ( tmp, "<a href=http://%sxxx.gnunet", ctask->pp_buf);
+
+  strcpy (ctask->pp_buf, tmp);
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "Created %s\n", tmp);
+
+  run_httpd();
+  //MHD_run (httpd);
+}
+
+/**
+ * Callback for MHD response
+ *
+ * @param cls closure
+ * @param pos in buffer
+ * @param buf buffer
+ * @param max space in buffer
+ */
+static ssize_t
+mhd_content_cb (void *cls,
+                uint64_t pos,
+                char* buf,
+                size_t max)
+{
+  struct ProxyCurlTask *ctask = cls;
+  ssize_t copied = 0;
+  size_t bytes_to_copy;
+  int nomatch;
+  char *hostptr;
+  regmatch_t m[RE_N_MATCHES];
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "MHD: content cb\n");
+
+  if (ctask->download_successful &&
+      (ctask->buf_status == BUF_WAIT_FOR_CURL))
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                "MHD: sending response for %s\n", ctask->url);
+    ctask->download_in_progress = GNUNET_NO;
+    curl_multi_remove_handle (curl_multi, ctask->curl);
+    curl_easy_cleanup (ctask->curl);
+    return MHD_CONTENT_READER_END_OF_STREAM;
+  }
+  
+  if (ctask->download_error &&
+      (ctask->buf_status == BUF_WAIT_FOR_CURL))
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                "MHD: sending error response\n");
+    ctask->download_in_progress = GNUNET_NO;
+    curl_multi_remove_handle (curl_multi, ctask->curl);
+    curl_easy_cleanup (ctask->curl);
+    return MHD_CONTENT_READER_END_WITH_ERROR;
+  }
+
+  if ( ctask->buf_status == BUF_WAIT_FOR_CURL )
+    return 0;
+
+  bytes_to_copy = ctask->bytes_in_buffer;
+  
+  if (ctask->parse_content == GNUNET_YES)
+  {
+
+    GNUNET_log ( GNUNET_ERROR_TYPE_DEBUG,
+                 "MHD: We need to parse the HTML %s\n", ctask->buffer_ptr);
+
+    nomatch = regexec ( &re_dotplus, ctask->buffer_ptr, RE_N_MATCHES, m, 0);
+
+    if (!nomatch)
+    {
+      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                  "MHD RE: Match\n");
+
+      GNUNET_assert (m[1].rm_so != -1);
+
+      hostptr = ctask->buffer_ptr+m[1].rm_so;
+
+      if (m[0].rm_so > 0)
+      {
+        bytes_to_copy = m[0].rm_so;
+        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                    "Copying %d bytes.\n", m[0].rm_so);
+
+
+      }
+      else
+      {
+        if (ctask->is_postprocessing == GNUNET_YES)
+        {
+          
+          /*Done?*/
+          if ( 0 == strcmp (ctask->pp_buf, "") )
+            return 0;
+          
+          ctask->is_postprocessing = GNUNET_NO;
+
+          ctask->bytes_in_buffer -= m[0].rm_eo;//(m[1].rm_eo-m[1].rm_so);
+          ctask->buffer_ptr += m[0].rm_eo;//(m[1].rm_eo-m[1].rm_so);
+          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                      "Skipping next %d bytes in buffer\n", m[0].rm_eo);
+
+          if ( strlen (ctask->pp_buf) <= max )
+          {
+            GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                        "Copying postprocessed %s.\n", ctask->pp_buf);
+            memcpy ( buf, ctask->pp_buf, strlen (ctask->pp_buf) );
+            GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                        "Done %s.\n", buf);
+            ctask->is_postprocessing = GNUNET_NO;
+            return strlen (ctask->pp_buf);
+          }
+          
+          return 0;
+        }
+
+        memset (ctask->pp_buf, 0, sizeof(ctask->pp_buf));
+        memcpy (ctask->pp_buf, hostptr, (m[1].rm_eo-m[1].rm_so));
+
+        ctask->is_postprocessing = GNUNET_YES;
+
+        postprocess_name(ctask, NULL);
+        //ctask->pp_task = GNUNET_SCHEDULER_add_now (&postprocess_name, ctask);
+
+        return 0;
+      }
+    }
+  }
+
+  if ( bytes_to_copy > max )
+  {
+    GNUNET_log ( GNUNET_ERROR_TYPE_DEBUG,
+                 "MHD: buffer in response too small! (%s)\n",
+                 ctask->url);
+    memcpy ( buf, ctask->buffer_ptr, max);
+    ctask->bytes_in_buffer -= max;
+    ctask->buffer_ptr += max;
+    copied = max;
+  }
+  else
+  {
+    GNUNET_log ( GNUNET_ERROR_TYPE_DEBUG,
+                 "MHD: copying %d bytes to mhd response at offset %d\n",
+                 bytes_to_copy, pos);
+
+    memcpy ( buf, ctask->buffer_ptr, bytes_to_copy );
+    copied = bytes_to_copy;
+    if (bytes_to_copy < ctask->bytes_in_buffer)
+    {
+      ctask->bytes_in_buffer -= bytes_to_copy;
+      ctask->buffer_ptr += bytes_to_copy;
+    }
+    else
+    {
+      ctask->bytes_in_buffer = 0;
+      ctask->buf_status = BUF_WAIT_FOR_CURL;
+      ctask->buffer_ptr = ctask->buffer;
+      curl_easy_pause (ctask->curl, CURLPAUSE_CONT);
+    }
+  }
+
+  return copied;
+}
+
+
+
+/**
+ * Task that is run when we are ready to receive more data
+ * from curl
+ *
+ * @param cls closure
+ * @param tc task context
+ */
+static void
+curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
+
+/**
+ * Ask cURL for the select sets and schedule download
+ */
+static void
+curl_download_prepare ()
+{
+  CURLMcode mret;
+  fd_set rs;
+  fd_set ws;
+  fd_set es;
+  int max;
+  struct GNUNET_NETWORK_FDSet *grs;
+  struct GNUNET_NETWORK_FDSet *gws;
+  long to;
+  struct GNUNET_TIME_Relative rtime;
+
+  max = -1;
+  FD_ZERO (&rs);
+  FD_ZERO (&ws);
+  FD_ZERO (&es);
+  mret = curl_multi_fdset (curl_multi, &rs, &ws, &es, &max);
+
+  if (mret != CURLM_OK)
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+                "%s failed at %s:%d: `%s'\n",
+                "curl_multi_fdset", __FILE__, __LINE__,
+                curl_multi_strerror (mret));
+    //TODO cleanup here?
+    return;
+  }
+
+  mret = curl_multi_timeout (curl_multi, &to);
+  rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, to);
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "cURL multi fds: max=%d timeout=%llu\n", max, to);
+
+  grs = GNUNET_NETWORK_fdset_create ();
+  gws = GNUNET_NETWORK_fdset_create ();
+  GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
+  GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "Scheduling task cURL\n");
+
+  if (curl_download_task != GNUNET_SCHEDULER_NO_TASK)
+    GNUNET_SCHEDULER_cancel (curl_download_task);
+  
+  curl_download_task =
+    GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
+                                 rtime,
+                                 grs, gws,
+                                 &curl_task_download, curl_multi);
+  GNUNET_NETWORK_fdset_destroy (gws);
+  GNUNET_NETWORK_fdset_destroy (grs);
+
+}
+
+
+/**
+ * Task that is run when we are ready to receive more data
+ * from curl
+ *
+ * @param cls closure
+ * @param tc task context
+ */
+static void
+curl_task_download (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  int running;
+  int msgnum;
+  struct CURLMsg *msg;
+  CURLMcode mret;
+  struct ProxyCurlTask *ctask;
+  int num_ctasks;
+
+  curl_download_task = GNUNET_SCHEDULER_NO_TASK;
+
+  if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                "Shutdown requested while trying to download\n");
+    //TODO cleanup
+    return;
+  }
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "Ready to dl\n");
+
+  do
+  {
+    running = 0;
+    num_ctasks = 0;
+    
+    mret = curl_multi_perform (curl_multi, &running);
+
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                "Running curl tasks: %d\n", running);
+
+    ctask = ctasks_head;
+    for (; ctask != NULL; ctask = ctask->next)
+    {
+      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                  "CTask: %s\n", ctask->url);
+      num_ctasks++;
+    }
+
+    if (num_ctasks != running)
+    {
+      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                  "%d ctasks, %d curl running\n", num_ctasks, running);
+    }
+    
+    do
+    {
+      ctask = ctasks_head;
+      msg = curl_multi_info_read (curl_multi, &msgnum);
+      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                  "Messages left: %d\n", msgnum);
+      
+      if (msg == NULL)
+        break;
+      switch (msg->msg)
+      {
+       case CURLMSG_DONE:
+         if ((msg->data.result != CURLE_OK) &&
+             (msg->data.result != CURLE_GOT_NOTHING))
+         {
+           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+                       "Download curl failed");
+            
+           for (; ctask != NULL; ctask = ctask->next)
+           {
+             if (memcmp (msg->easy_handle, ctask->curl, sizeof (CURL)) != 0)
+               continue;
+             
+             GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+                         "Download curl failed for task %s: %s.\n",
+                         ctask->url,
+                         curl_easy_strerror (msg->data.result));
+             ctask->download_successful = GNUNET_NO;
+             ctask->download_error = GNUNET_YES;
+             //curl_multi_remove_handle (curl_multi, ctask->curl);
+             //curl_easy_cleanup (ctask->curl);
+             GNUNET_CONTAINER_DLL_remove (ctasks_head, ctasks_tail,
+                                          ctask);
+             break;
+           }
+           GNUNET_assert (ctask != NULL);
+         }
+         else
+         {
+           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                       "cURL download completed.\n");
+
+           for (; ctask != NULL; ctask = ctask->next)
+           {
+             if (memcmp (msg->easy_handle, ctask->curl, sizeof (CURL)) != 0)
+               continue;
+             
+             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                         "cURL task %s found.\n", ctask->url);
+             ctask->download_successful = GNUNET_YES;
+             //curl_multi_remove_handle (curl_multi, ctask->curl);
+             //curl_easy_cleanup (ctask->curl);
+             GNUNET_CONTAINER_DLL_remove (ctasks_head, ctasks_tail,
+                                          ctask);
+             break;
+           }
+           GNUNET_assert (ctask != NULL);
+         }
+         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                     "curl end %s\n", curl_easy_strerror(msg->data.result));
+         break;
+       default:
+         GNUNET_assert (0);
+         break;
+      }
+    } while (msgnum > 0);
+    
+    num_ctasks=0;
+    for (ctask=ctasks_head; ctask != NULL; ctask = ctask->next)
+    {
+      num_ctasks++;
+    }
+    
+    if (num_ctasks != running)
+    {
+      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                  "%d ctasks, %d curl running\n", num_ctasks, running);
+    }
+
+    GNUNET_assert ( num_ctasks == running );
+
+    run_httpd ();
+
+  } while (mret == CURLM_CALL_MULTI_PERFORM);
+  
+  
+  if (mret != CURLM_OK)
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s failed at %s:%d: `%s'\n",
+                "curl_multi_perform", __FILE__, __LINE__,
+                curl_multi_strerror (mret));
+  }
+  curl_download_prepare();
+}
+
+
+/**
+ * Main MHD callback for handling requests.
+ *
+ * @param cls unused
+ * @param con MHD connection handle
+ * @param meth the HTTP method used ("GET", "PUT", etc.)
+ * @param ver the HTTP version string (i.e. "HTTP/1.1")
+ * @param upload_data the data being uploaded (excluding HEADERS,
+ *        for a POST that fits into memory and that is encoded
+ *        with a supported encoding, the POST data will NOT be
+ *        given in upload_data and is instead available as
+ *        part of MHD_get_connection_values; very large POST
+ *        data *will* be made available incrementally in
+ *        upload_data)
+ * @param upload_data_size set initially to the size of the
+ *        upload_data provided; the method must update this
+ *        value to the number of bytes NOT processed;
+ * @param con_cls pointer to location where we store the 'struct Request'
+ * @return MHD_YES if the connection was handled successfully,
+ *         MHD_NO if the socket must be closed due to a serious
+ *         error while handling the request
+ */
+static int
+create_response (void *cls,
+                 struct MHD_Connection *con,
+                 const char *url,
+                 const char *meth,
+                 const char *ver,
+                 const char *upload_data,
+                 size_t *upload_data_size,
+                 void **con_cls)
+{
+  static int dummy;
+  const char* page = "<html><head><title>gnoxy</title>"\
+                      "</head><body>cURL fail</body></html>";
+  struct MHD_Response *response;
+  char host[265];
+  char curlurl[512];
+  int ret = MHD_YES;
+
+  CURLMcode mret;
+  struct ProxyCurlTask *ctask;
+  
+  if (0 != strcmp (meth, "GET"))
+    return MHD_NO;
+  if (&dummy != *con_cls)
+  {
+    *con_cls = &dummy;
+    return MHD_YES;
+  }
+
+  if (0 != *upload_data_size)
+    return MHD_NO;
+
+  *con_cls = NULL;
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "url %s\n", url);
+
+  MHD_get_connection_values (con,
+                             MHD_HEADER_KIND,
+                             &con_val_iter, host);
+
+  
+  /* Do cURL */
+  ctask = GNUNET_malloc (sizeof (struct ProxyCurlTask));
+  ctask->curl = curl_easy_init();
+
+  if (curl_multi == NULL)
+    curl_multi = curl_multi_init ();
+  
+  if ((ctask->curl == NULL) || (curl_multi == NULL))
+  {
+    response = MHD_create_response_from_buffer (strlen (page),
+                                              (void*)page,
+                                              MHD_RESPMEM_PERSISTENT);
+    ret = MHD_queue_response (con,
+                              MHD_HTTP_OK,
+                              response);
+    MHD_destroy_response (response);
+    GNUNET_free (ctask);
+    return ret;
+  }
+
+  ctask->download_in_progress = GNUNET_YES;
+  ctask->download_successful = GNUNET_NO;
+  ctask->bytes_downloaded = 0;
+  ctask->connection = con;
+  ctask->buf_status = BUF_WAIT_FOR_CURL;
+  ctask->bytes_in_buffer = 0;
+  ctask->parse_content = GNUNET_NO;
+
+  curl_easy_setopt (ctask->curl, CURLOPT_HEADERFUNCTION, &curl_check_hdr);
+  curl_easy_setopt (ctask->curl, CURLOPT_HEADERDATA, ctask);
+  curl_easy_setopt (ctask->curl, CURLOPT_WRITEFUNCTION, &callback_download);
+  curl_easy_setopt (ctask->curl, CURLOPT_WRITEDATA, ctask);
+  curl_easy_setopt (ctask->curl, CURLOPT_FOLLOWLOCATION, 1);
+  curl_easy_setopt (ctask->curl, CURLOPT_MAXREDIRS, 4);
+  /* no need to abort if the above failed */
+  sprintf (curlurl, "http://%s%s", host, url);
+  strcpy (ctask->url, curlurl);
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "Adding new curl task for %s\n", curlurl);
+  
+  curl_easy_setopt (ctask->curl, CURLOPT_URL, curlurl);
+  curl_easy_setopt (ctask->curl, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (ctask->curl, CURLOPT_CONNECTTIMEOUT, 600L);
+  curl_easy_setopt (ctask->curl, CURLOPT_TIMEOUT, 600L);
+
+  mret = curl_multi_add_handle (curl_multi, ctask->curl);
+
+  if (mret != CURLM_OK)
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+                "%s failed at %s:%d: `%s'\n",
+                "curl_multi_add_handle", __FILE__, __LINE__,
+                curl_multi_strerror (mret));
+    response = MHD_create_response_from_buffer (strlen (page),
+                                                (void*)page,
+                                                MHD_RESPMEM_PERSISTENT);
+    ret = MHD_queue_response (con,
+                              MHD_HTTP_OK,
+                              response);
+    MHD_destroy_response (response);
+
+    curl_easy_cleanup (ctask->curl);
+    GNUNET_free (ctask);
+    return ret;
+  }
+  
+  GNUNET_CONTAINER_DLL_insert (ctasks_head, ctasks_tail, ctask);
+
+  curl_download_prepare ();
+
+  response = MHD_create_response_from_callback (-1, -1,
+                                                &mhd_content_cb,
+                                                ctask,
+                                                &mhd_content_free);
+  
+  ret = MHD_queue_response (con, MHD_HTTP_OK, response);
+  
+  //MHD_destroy_response (response);
+
+  return ret;
+}
+
+/**
+ * Task run whenever HTTP server operations are pending.
+ *
+ * @param cls unused
+ * @param tc sched context
+ */
+static void
+do_httpd (void *cls,
+          const struct GNUNET_SCHEDULER_TaskContext *tc);
+
+
+/**
+ * schedule mhd
+ */
+static void
+run_httpd ()
+{
+  fd_set rs;
+  fd_set ws;
+  fd_set es;
+  struct GNUNET_NETWORK_FDSet *wrs;
+  struct GNUNET_NETWORK_FDSet *wws;
+  struct GNUNET_NETWORK_FDSet *wes;
+  int max;
+  int haveto;
+  unsigned MHD_LONG_LONG timeout;
+  struct GNUNET_TIME_Relative tv;
+
+  FD_ZERO (&rs);
+  FD_ZERO (&ws);
+  FD_ZERO (&es);
+  wrs = GNUNET_NETWORK_fdset_create ();
+  wes = GNUNET_NETWORK_fdset_create ();
+  wws = GNUNET_NETWORK_fdset_create ();
+  max = -1;
+  GNUNET_assert (MHD_YES == MHD_get_fdset (httpd, &rs, &ws, &es, &max));
+  
+  
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "MHD fds: max=%d\n", max);
+  
+  haveto = MHD_get_timeout (httpd, &timeout);
+
+  if (haveto == MHD_YES)
+    tv.rel_value = (uint64_t) timeout;
+  else
+    tv = GNUNET_TIME_UNIT_FOREVER_REL;
+  GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
+  GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
+  GNUNET_NETWORK_fdset_copy_native (wes, &es, max + 1);
+  
+  if (httpd_task != GNUNET_SCHEDULER_NO_TASK)
+    GNUNET_SCHEDULER_cancel (httpd_task);
+  httpd_task =
+    GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
+                                 tv, wrs, wws,
+                                 &do_httpd, NULL);
+  GNUNET_NETWORK_fdset_destroy (wrs);
+  GNUNET_NETWORK_fdset_destroy (wws);
+  GNUNET_NETWORK_fdset_destroy (wes);
+}
+
+/**
+ * Task run whenever HTTP server operations are pending.
+ *
+ * @param cls unused
+ * @param tc sched context
+ */
+static void
+do_httpd (void *cls,
+          const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  httpd_task = GNUNET_SCHEDULER_NO_TASK;
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "MHD run \n");
+  MHD_run (httpd);
+  run_httpd ();
+}
 
 /**
  * Read data from socket
@@ -121,8 +911,8 @@ do_write_remote (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
 
   if ((NULL != tc->read_ready) &&
       (GNUNET_NETWORK_fdset_isset (tc->write_ready, s5r->remote_sock)) &&
-      (len = GNUNET_NETWORK_socket_send (s5r->remote_sock, s5r->rbuf,
-                                         s5r->rbuf_len)))
+      ((len = GNUNET_NETWORK_socket_send (s5r->remote_sock, s5r->rbuf,
+                                         s5r->rbuf_len)>0)))
   {
     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                 "Successfully sent %d bytes to remote socket\n",
@@ -167,8 +957,8 @@ do_write (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
 
   if ((NULL != tc->read_ready) &&
       (GNUNET_NETWORK_fdset_isset (tc->write_ready, s5r->sock)) &&
-      (len = GNUNET_NETWORK_socket_send (s5r->sock, s5r->wbuf,
-                                         s5r->wbuf_len)))
+      ((len = GNUNET_NETWORK_socket_send (s5r->sock, s5r->wbuf,
+                                         s5r->wbuf_len)>0)))
   {
     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                 "Successfully sent %d bytes to socket\n",
@@ -247,6 +1037,19 @@ do_read_remote (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
 }
 
 
+static int
+add_handle_to_mhd (struct GNUNET_NETWORK_Handle *h)
+{
+  int fd;
+  struct sockaddr *addr;
+  socklen_t len;
+
+  fd = GNUNET_NETWORK_get_fd (h);
+  addr = GNUNET_NETWORK_get_addr (h);
+  len = GNUNET_NETWORK_get_addrlen (h);
+
+  return MHD_add_connection (httpd, fd, addr, len);
+}
 
 /**
  * Read data from incoming connection
@@ -355,6 +1158,40 @@ do_read (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                   "Requested connection is gnunet tld\n",
                   domain);
+
+      if (NULL == httpd)
+      {
+        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+                    _("Failed to start HTTP server\n"));
+        s_resp->version = 0x05;
+        s_resp->reply = 0x01;
+        s5r->wtask = 
+          GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
+                                        s5r->sock,
+                                        &do_write, s5r);
+        //ERROR!
+        //TODO! close socket after the write! schedule task
+        //GNUNET_NETWORK_socket_close (s5r->sock);
+        //GNUNET_free(s5r);
+        return;
+      }
+
+      if (MHD_YES == add_handle_to_mhd ( s5r->sock ))
+        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                    "Sucessfully added client to MHD!\n");
+      s_resp->version = 0x05;
+      s_resp->reply = 0x00;
+      s_resp->reserved = 0x00;
+      s_resp->addr_type = 0x01;
+
+      s5r->wtask =
+        GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
+                                        s5r->sock,
+                                        &do_write, s5r);
+      run_httpd ();
+      //GNUNET_free ( s5r );
+      //FIXME complete socks resp!
+      return;
     }
     else
     {
@@ -523,6 +1360,59 @@ do_accept (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
   //GNUNET_CONTAINER_DLL_insert (s5conns.head, s5conns.tail, s5r);
 }
 
+/**
+ * Task run on shutdown
+ *
+ * @param cls closure
+ * @param tc task context
+ */
+static void
+do_shutdown (void *cls,
+             const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  if (GNUNET_SCHEDULER_NO_TASK != httpd_task)
+  {
+    GNUNET_SCHEDULER_cancel (httpd_task);
+    httpd_task = GNUNET_SCHEDULER_NO_TASK;
+  }
+  
+  if (GNUNET_SCHEDULER_NO_TASK != curl_download_task)
+  {
+    GNUNET_SCHEDULER_cancel (curl_download_task);
+    curl_download_task = GNUNET_SCHEDULER_NO_TASK;
+  }
+
+  if (NULL != httpd)
+  {
+    MHD_stop_daemon (httpd);
+    httpd = NULL;
+  }
+}
+
+/**
+ * Compiles a regex for us
+ *
+ * @param re ptr to re struct
+ * @param rt the expression to compile
+ * @return 0 on success
+ */
+static int
+compile_regex (regex_t *re, const char* rt)
+{
+  int status;
+  char err[1024];
+
+  status = regcomp (re, rt, REG_EXTENDED|REG_NEWLINE);
+  if (status)
+  {
+    regerror (status, re, err, 1024);
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+                "Regex error compiling '%s': %s\n", rt, err);
+    return 1;
+  }
+  return 0;
+}
+
 /**
  * Main function that will be run
  *
@@ -537,6 +1427,8 @@ run (void *cls, char *const *args, const char *cfgfile,
 {
   struct sockaddr_in sa;
 
+  compile_regex (&re_dotplus, (char*) RE_DOTPLUS);
+
   memset (&sa, 0, sizeof (sa));
   sa.sin_family = AF_INET;
   sa.sin_port = htons (port);
@@ -572,9 +1464,32 @@ run (void *cls, char *const *args, const char *cfgfile,
   ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                          lsock, &do_accept, NULL);
 
+  ctasks_head = NULL;
+  ctasks_tail = NULL;
+
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+                "cURL global init failed!\n");
+    return;
+  }
+
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
               "Proxy listens on port %u\n",
               port);
+  
+  httpd = MHD_start_daemon (MHD_USE_DEBUG, 4444,
+                               NULL, NULL,
+                               &create_response, NULL,
+                               MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 128,
+                               MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
+                               MHD_OPTION_NOTIFY_COMPLETED,
+                               NULL, NULL,
+                               MHD_OPTION_END);
+  run_httpd ();
+
+  GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
+                                &do_shutdown, NULL);
 
 }