2a4f92141c3dfb7a67224762355dd94c8e4bc2f4
[oweals/gnunet.git] / src / transport / plugin_transport_http.c
1 /*
2      This file is part of GNUnet
3      (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file transport/plugin_transport_http.c
23  * @brief http transport service plugin
24  * @author Matthias Wachs
25  */
26
27 #include "platform.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_connection_lib.h"
31 #include "gnunet_service_lib.h"
32 #include "gnunet_statistics_service.h"
33 #include "gnunet_transport_service.h"
34 #include "gnunet_resolver_service.h"
35 #include "gnunet_server_lib.h"
36 #include "gnunet_container_lib.h"
37 #include "plugin_transport.h"
38 #include "gnunet_os_lib.h"
39 #include "microhttpd.h"
40 #include <curl/curl.h>
41
42
43 #define DEBUG_CURL GNUNET_NO
44 #define DEBUG_HTTP GNUNET_NO
45
46 #define INBOUND GNUNET_NO
47 #define OUTBOUND GNUNET_YES
48
49 /**
50  * Text of the response sent back after the last bytes of a PUT
51  * request have been received (just to formally obey the HTTP
52  * protocol).
53  */
54 #define HTTP_PUT_RESPONSE "Thank you!"
55
56 /**
57  * After how long do we expire an address that we
58  * learned from another peer if it is not reconfirmed
59  * by anyone?
60  */
61 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
62
63 /**
64  * Page returned if request invalid
65  */
66 #define HTTP_ERROR_RESPONSE "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\"><HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>Not Found</H1>The requested URL was not found on this server.<P><HR><ADDRESS></ADDRESS></BODY></HTML>"
67
68 /**
69  * Timeout for a http connect
70  */
71 #define HTTP_CONNECT_TIMEOUT 30
72
73 /**
74  * Network format for IPv4 addresses.
75  */
76 struct IPv4HttpAddress
77 {
78   /**
79    * IPv4 address, in network byte order.
80    */
81   uint32_t ipv4_addr GNUNET_PACKED;
82
83   /**
84    * Port number, in network byte order.
85    */
86   uint16_t u_port GNUNET_PACKED;
87
88 };
89
90
91 /**
92  * Network format for IPv6 addresses.
93  */
94 struct IPv6HttpAddress
95 {
96   /**
97    * IPv6 address.
98    */
99   struct in6_addr ipv6_addr GNUNET_PACKED;
100
101   /**
102    * Port number, in network byte order.
103    */
104   uint16_t u6_port GNUNET_PACKED;
105
106 };
107
108
109 /**
110  *  Message to send using http
111  */
112 struct HTTP_Message
113 {
114   /**
115    * next pointer for double linked list
116    */
117   struct HTTP_Message * next;
118
119   /**
120    * previous pointer for double linked list
121    */
122   struct HTTP_Message * prev;
123
124   /**
125    * buffer containing data to send
126    */
127   char *buf;
128
129   /**
130    * amount of data already sent
131    */
132   size_t pos;
133
134   /**
135    * buffer length
136    */
137   size_t size;
138
139   /**
140    * Continuation function to call once the transmission buffer
141    * has again space available.  NULL if there is no
142    * continuation to call.
143    */
144   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
145
146   /**
147    * Closure for transmit_cont.
148    */
149   void *transmit_cont_cls;
150 };
151
152
153 struct HTTP_PeerContext
154 {
155   struct GNUNET_PeerIdentity identity;
156
157   /**
158    * Pointer to the global plugin struct.
159    */
160   struct Plugin *plugin;
161
162   struct Session * head;
163   struct Session * tail;
164 };
165
166
167 struct Session
168 {
169   /**
170    * API requirement.
171    */
172   struct SessionHeader header;
173
174   /**
175    * next session in linked list
176    */
177   struct Session * next;
178
179   /**
180    * previous session in linked list
181    */
182   struct Session * prev;
183
184   /**
185    * address of this session
186    */
187   void * addr;
188
189   /**
190    * address length
191    */
192   size_t addrlen;
193
194   /**
195    * target url
196    */
197   char * url;
198
199   /**
200    * Message queue for outbound messages
201    * head of queue
202    */
203   struct HTTP_Message * pending_msgs_head;
204
205   /**
206    * Message queue for outbound messages
207    * tail of queue
208    */
209   struct HTTP_Message * pending_msgs_tail;
210
211   /**
212    * partner peer this connection belongs to
213    */
214   struct HTTP_PeerContext * peercontext;
215
216   /**
217    * message stream tokenizer for incoming data
218    */
219   struct GNUNET_SERVER_MessageStreamTokenizer *msgtok;
220
221   /**
222    * session direction
223    * outbound: OUTBOUND (GNUNET_YES)
224    * inbound : INBOUND (GNUNET_NO)
225    */
226   unsigned int direction;
227
228   /**
229    * is session connected to send data?
230    */
231   unsigned int send_connected;
232
233   /**
234    * is send connection active?
235    */
236   unsigned int send_active;
237
238   /**
239    * is session connected to receive data?
240    */
241   unsigned int recv_connected;
242
243   /**
244    * is receive connection active?
245    */
246   unsigned int recv_active;
247
248   /**
249    * entity managing sending data
250    * outbound session: pointer to curl easy handle
251    */
252   void * send_endpoint;
253
254   /**
255    * entity managing recieving data
256    * outbound session: pointer to curl easy handle
257    */
258   void * recv_endpoint;
259 };
260
261 /**
262  * Encapsulation of all of the state of the plugin.
263  */
264 struct Plugin
265 {
266   /**
267    * Our environment.
268    */
269   struct GNUNET_TRANSPORT_PluginEnvironment *env;
270
271   unsigned int port_inbound;
272
273   struct GNUNET_CONTAINER_MultiHashMap *peers;
274
275   /**
276    * Daemon for listening for new IPv4 connections.
277    */
278   struct MHD_Daemon *http_server_daemon_v4;
279
280   /**
281    * Daemon for listening for new IPv6connections.
282    */
283   struct MHD_Daemon *http_server_daemon_v6;
284
285   /**
286    * Our primary task for http daemon handling IPv4 connections
287    */
288   GNUNET_SCHEDULER_TaskIdentifier http_server_task_v4;
289
290   /**
291    * Our primary task for http daemon handling IPv6 connections
292    */
293   GNUNET_SCHEDULER_TaskIdentifier http_server_task_v6;
294
295   /**
296    * The task sending data
297    */
298   GNUNET_SCHEDULER_TaskIdentifier http_server_task_send;
299
300   /**
301    * cURL Multihandle
302    */
303   CURLM * multi_handle;
304
305   /**
306    * Our ASCII encoded, hashed peer identity
307    * This string is used to distinguish between connections and is added to the urls
308    */
309   struct GNUNET_CRYPTO_HashAsciiEncoded my_ascii_hash_ident;
310 };
311
312
313 /**
314  * Function called for a quick conversion of the binary address to
315  * a numeric address.  Note that the caller must not free the
316  * address and that the next call to this function is allowed
317  * to override the address again.
318  *
319  * @param cls closure
320  * @param addr binary address
321  * @param addrlen length of the address
322  * @return string representing the same address
323  */
324 static const char*
325 http_plugin_address_to_string (void *cls,
326                                    const void *addr,
327                                    size_t addrlen);
328
329 static char * create_url(void * cls, const void * addr, size_t addrlen)
330 {
331   struct Plugin *plugin = cls;
332   char *url = NULL;
333
334   GNUNET_assert ((addr!=NULL) && (addrlen != 0));
335   GNUNET_asprintf(&url,
336                   "http://%s/%s",
337                   http_plugin_address_to_string(NULL, addr, addrlen),
338                   (char *) (&plugin->my_ascii_hash_ident));
339
340   return url;
341 }
342
343 /**
344  * Removes a message from the linked list of messages
345  * @param con connection to remove message from
346  * @param msg message to remove
347  * @return GNUNET_SYSERR if msg not found, GNUNET_OK on success
348  */
349
350 static int remove_http_message(struct Session * ps, struct HTTP_Message * msg)
351 {
352   GNUNET_CONTAINER_DLL_remove(ps->pending_msgs_head,ps->pending_msgs_tail,msg);
353   GNUNET_free(msg);
354   return GNUNET_OK;
355 }
356
357 static struct Session * get_Session (void * cls, struct HTTP_PeerContext *pc, const void * addr, size_t addr_len)
358 {
359   struct Session * cc = pc->head;
360   struct Session * con = NULL;
361   unsigned int count = 0;
362
363   GNUNET_assert((addr_len == sizeof (struct IPv4HttpAddress)) || (addr_len == sizeof (struct IPv6HttpAddress)));
364   while (cc!=NULL)
365   {
366     if (addr_len == cc->addrlen)
367     {
368       if (0 == memcmp(cc->addr, addr, addr_len))
369       {
370         con = cc;
371         break;
372       }
373     }
374     count++;
375     cc=cc->next;
376   }
377   return con;
378 }
379
380
381 /**
382  * Callback called by MHD when a connection is terminated
383  */
384 static void requestCompletedCallback (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
385 {
386   struct Session * ps = *httpSessionCache;
387   if (ps == NULL)
388     return;
389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection from peer `%s' was terminated\n",GNUNET_i2s(&ps->peercontext->identity));
390   /* session set to inactive */
391   //ps-> = GNUNET_NO;
392   //con->is_bad_request = GNUNET_NO;
393 }
394
395 static void mhd_write_mst_cb (void *cls,
396                               void *client,
397                               const struct GNUNET_MessageHeader *message)
398 {
399
400   struct Session *ps  = cls;
401   struct HTTP_PeerContext *pc = ps->peercontext;
402   GNUNET_assert(ps != NULL);
403   GNUNET_assert(pc != NULL);
404
405   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
406               "Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
407               ntohs(message->type),
408               ntohs(message->size),
409               GNUNET_i2s(&(ps->peercontext)->identity),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
410
411   pc->plugin->env->receive (ps->peercontext->plugin->env->cls,
412                             &pc->identity,
413                             message, 1, ps,
414                             ps->addr,
415                             ps->addrlen);
416 }
417
418 static void curl_write_mst_cb  (void *cls,
419                                 void *client,
420                                 const struct GNUNET_MessageHeader *message)
421 {
422   struct Session *ps  = cls;
423   struct HTTP_PeerContext *pc = ps->peercontext;
424   GNUNET_assert(ps != NULL);
425   GNUNET_assert(pc != NULL);
426
427   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
428               "Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
429               ntohs(message->type),
430               ntohs(message->size),
431               GNUNET_i2s(&(pc->identity)),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
432
433   pc->plugin->env->receive (pc->plugin->env->cls,
434                             &pc->identity,
435                             message, 1, ps,
436                             ps->addr,
437                             ps->addrlen);
438 }
439
440
441 /**
442  * Check if ip is allowed to connect.
443  */
444 static int
445 acceptPolicyCallback (void *cls,
446                       const struct sockaddr *addr, socklen_t addr_len)
447 {
448 #if 0
449   struct Plugin *plugin = cls;
450 #endif
451   /* Every connection is accepted, nothing more to do here */
452   return MHD_YES;
453 }
454
455 int server_read_callback (void *cls, uint64_t pos, char *buf, int max)
456 {
457   int bytes_read = 0;
458
459   struct Session * ps = cls;
460   struct HTTP_PeerContext * pc;
461   struct HTTP_Message * msg;
462   int res;res=5;
463
464   GNUNET_assert (ps!=NULL);
465   pc = ps->peercontext;
466   msg = ps->pending_msgs_tail;
467
468   if (msg!=NULL)
469   {
470     if ((msg->size-msg->pos) <= max)
471       {
472         memcpy(buf,&msg->buf[pos],(msg->size-msg->pos));
473         pos+=(msg->size-msg->pos);
474       }
475       else
476       {
477         memcpy(buf,&msg->buf[pos],max);
478         pos+=max;
479       }
480
481       if (msg->pos==msg->size)
482       {
483         if (NULL!=msg->transmit_cont)
484           msg->transmit_cont (msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
485         res = remove_http_message(ps,msg);
486       }
487   }
488   return bytes_read;
489 }
490
491 /**
492  * Process GET or PUT request received via MHD.  For
493  * GET, queue response that will send back our pending
494  * messages.  For PUT, process incoming data and send
495  * to GNUnet core.  In either case, check if a session
496  * already exists and create a new one if not.
497  */
498 static int
499 accessHandlerCallback (void *cls,
500                        struct MHD_Connection *mhd_connection,
501                        const char *url,
502                        const char *method,
503                        const char *version,
504                        const char *upload_data,
505                        size_t * upload_data_size, void **httpSessionCache)
506 {
507   struct Plugin *plugin = cls;
508   struct MHD_Response *response;
509   const union MHD_ConnectionInfo * conn_info;
510
511   struct sockaddr_in  *addrin;
512   struct sockaddr_in6 *addrin6;
513
514   char address[INET6_ADDRSTRLEN+14];
515   struct GNUNET_PeerIdentity pi_in;
516
517   struct IPv4HttpAddress ipv4addr;
518   struct IPv6HttpAddress ipv6addr;
519
520   struct HTTP_PeerContext *pc;
521   struct Session *ps;
522
523   int res = GNUNET_NO;
524   int send_error_to_client;
525   void * addr;
526   size_t addr_len;
527
528   GNUNET_assert(cls !=NULL);
529   send_error_to_client = GNUNET_NO;
530
531   if (NULL == *httpSessionCache)
532   {
533     /* check url for peer identity , if invalid send HTTP 404*/
534     res = GNUNET_CRYPTO_hash_from_string ( &url[1], &(pi_in.hashPubKey));
535     if ( GNUNET_SYSERR == res )
536     {
537       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
538       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
539       MHD_destroy_response (response);
540       if (res == MHD_YES)
541         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, sent HTTP 1.1/404\n");
542       else
543         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, could not send error\n");
544       return res;
545     }
546   }
547   else
548   {
549     ps = *httpSessionCache;
550     pc = ps->peercontext;
551   }
552
553   if (NULL == *httpSessionCache)
554   {
555     /* get peer context */
556     pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &pi_in.hashPubKey);
557     /* Peer unknown */
558     if (pc==NULL)
559     {
560       pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
561       pc->plugin = plugin;
562       memcpy(&pc->identity, &pi_in, sizeof(struct GNUNET_PeerIdentity));
563       GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
564     }
565
566     conn_info = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
567     /* Incoming IPv4 connection */
568     if ( AF_INET == conn_info->client_addr->sin_family)
569     {
570       addrin = conn_info->client_addr;
571       inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
572       memcpy(&ipv4addr.ipv4_addr,&(addrin->sin_addr),sizeof(struct in_addr));
573       ipv4addr.u_port = addrin->sin_port;
574       addr = &ipv4addr;
575       addr_len = sizeof(struct IPv4HttpAddress);
576       //con = session_check_inbound_address (plugin, cs, (const void *) &ipv4addr, sizeof (struct IPv4HttpAddress));
577     }
578     /* Incoming IPv6 connection */
579     if ( AF_INET6 == conn_info->client_addr->sin_family)
580     {
581       addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
582       inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
583       memcpy(&ipv6addr.ipv6_addr,&(addrin6->sin6_addr),sizeof(struct in6_addr));
584       ipv6addr.u6_port = addrin6->sin6_port;
585       addr = &ipv6addr;
586       addr_len = sizeof(struct IPv6HttpAddress);
587     }
588     /* Set closure and update current session*/
589     ps = get_Session(plugin, pc, addr, addr_len);
590     if (ps==NULL)
591     {
592       ps = GNUNET_malloc(sizeof (struct Session));
593       ps->addr = GNUNET_malloc(addr_len);
594       memcpy(ps->addr,addr,addr_len);
595       ps->addrlen = addr_len;
596       ps->direction=INBOUND;
597       ps->pending_msgs_head = NULL;
598       ps->pending_msgs_tail = NULL;
599       ps->send_connected=GNUNET_NO;
600       ps->send_active=GNUNET_NO;
601       ps->recv_connected=GNUNET_NO;
602       ps->recv_active=GNUNET_NO;
603       ps->peercontext=pc;
604       ps->url = create_url (plugin, ps->addr, ps->addrlen);
605       GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
606     }
607
608     *httpSessionCache = ps;
609     if (ps->msgtok==NULL)
610       ps->msgtok = GNUNET_SERVER_mst_create (&mhd_write_mst_cb, ps);
611
612     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Daemon has new an incoming `%s' request from peer `%s' (`%s')\n",
613                 method,
614                 GNUNET_i2s(&pc->identity),
615                 http_plugin_address_to_string(NULL, ps->addr, ps->addrlen));
616   }
617
618   /* Is it a PUT or a GET request */
619   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
620   {
621     if ((*upload_data_size == 0) && (ps->recv_active==GNUNET_NO))
622     {
623       ps->recv_active = GNUNET_YES;
624       return MHD_YES;
625     }
626
627     /* Transmission of all data complete */
628     if ((*upload_data_size == 0) && (ps->recv_active == GNUNET_YES))
629     {
630       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
631       res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
632       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Sent HTTP/1.1: 200 OK as PUT Response\n",HTTP_PUT_RESPONSE, strlen (HTTP_PUT_RESPONSE), res );
633       MHD_destroy_response (response);
634       ps->recv_active=GNUNET_NO;
635       return MHD_YES;
636     }
637
638     /* Recieving data */
639     if ((*upload_data_size > 0) && (ps->recv_active == GNUNET_YES))
640     {
641       res = GNUNET_SERVER_mst_receive(ps->msgtok, ps, upload_data,*upload_data_size, GNUNET_NO, GNUNET_NO);
642       (*upload_data_size) = 0;
643       return MHD_YES;
644     }
645     else
646       return MHD_NO;
647   }
648   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
649   {
650     response = MHD_create_response_from_callback(-1,32 * 1024, &server_read_callback, ps, NULL);
651     res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
652     MHD_destroy_response (response);
653     return res;
654   }
655   return MHD_NO;
656 }
657
658
659 /**
660  * Call MHD to process pending ipv4 requests and then go back
661  * and schedule the next run.
662  */
663 static void http_server_daemon_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
664 /**
665  * Call MHD to process pending ipv6 requests and then go back
666  * and schedule the next run.
667  */
668 static void http_server_daemon_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
669
670 /**
671  * Function that queries MHD's select sets and
672  * starts the task waiting for them.
673  */
674 static GNUNET_SCHEDULER_TaskIdentifier
675 http_server_daemon_prepare (void * cls, struct MHD_Daemon *daemon_handle)
676 {
677   struct Plugin *plugin = cls;
678   GNUNET_SCHEDULER_TaskIdentifier ret;
679   fd_set rs;
680   fd_set ws;
681   fd_set es;
682   struct GNUNET_NETWORK_FDSet *wrs;
683   struct GNUNET_NETWORK_FDSet *wws;
684   struct GNUNET_NETWORK_FDSet *wes;
685   int max;
686   unsigned long long timeout;
687   int haveto;
688   struct GNUNET_TIME_Relative tv;
689
690   GNUNET_assert(cls !=NULL);
691   ret = GNUNET_SCHEDULER_NO_TASK;
692   FD_ZERO(&rs);
693   FD_ZERO(&ws);
694   FD_ZERO(&es);
695   wrs = GNUNET_NETWORK_fdset_create ();
696   wes = GNUNET_NETWORK_fdset_create ();
697   wws = GNUNET_NETWORK_fdset_create ();
698   max = -1;
699   GNUNET_assert (MHD_YES ==
700                  MHD_get_fdset (daemon_handle,
701                                 &rs,
702                                 &ws,
703                                 &es,
704                                 &max));
705   haveto = MHD_get_timeout (daemon_handle, &timeout);
706   if (haveto == MHD_YES)
707     tv.value = (uint64_t) timeout;
708   else
709     tv = GNUNET_TIME_UNIT_FOREVER_REL;
710   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
711   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
712   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
713   if (daemon_handle == plugin->http_server_daemon_v4)
714   {
715     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
716                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
717                                        GNUNET_SCHEDULER_NO_TASK,
718                                        tv,
719                                        wrs,
720                                        wws,
721                                        &http_server_daemon_v4_run,
722                                        plugin);
723   }
724   if (daemon_handle == plugin->http_server_daemon_v6)
725   {
726     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
727                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
728                                        GNUNET_SCHEDULER_NO_TASK,
729                                        tv,
730                                        wrs,
731                                        wws,
732                                        &http_server_daemon_v6_run,
733                                        plugin);
734   }
735   GNUNET_NETWORK_fdset_destroy (wrs);
736   GNUNET_NETWORK_fdset_destroy (wws);
737   GNUNET_NETWORK_fdset_destroy (wes);
738   return ret;
739 }
740
741 /**
742  * Call MHD to process pending requests and then go back
743  * and schedule the next run.
744  */
745 static void http_server_daemon_v4_run (void *cls,
746                              const struct GNUNET_SCHEDULER_TaskContext *tc)
747 {
748   struct Plugin *plugin = cls;
749
750   GNUNET_assert(cls !=NULL);
751   if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
752     plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
753
754   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
755     return;
756
757   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v4));
758   plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
759   return;
760 }
761
762
763 /**
764  * Call MHD to process pending requests and then go back
765  * and schedule the next run.
766  */
767 static void http_server_daemon_v6_run (void *cls,
768                              const struct GNUNET_SCHEDULER_TaskContext *tc)
769 {
770   struct Plugin *plugin = cls;
771
772   GNUNET_assert(cls !=NULL);
773   if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
774     plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
775
776   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
777     return;
778
779   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v6));
780   plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
781   return;
782 }
783
784 /**
785  * Function setting up curl handle and selecting message to send
786  * @param cls plugin
787  * @param ses session to send data to
788  * @param con connection
789  * @return bytes sent to peer
790  */
791 static ssize_t send_check_connections (void *cls, struct Session* ses , struct Session *ps);
792
793
794 static size_t curl_get_header_function( void *ptr, size_t size, size_t nmemb, void *stream)
795 {
796   struct Session * ps = stream;
797
798   char * tmp;
799   size_t len = size * nmemb;
800   long http_result = 0;
801   int res;
802   /* Getting last http result code */
803   if (ps->recv_connected==GNUNET_NO)
804   {
805     GNUNET_assert(NULL!=ps);
806     res = curl_easy_getinfo(ps->recv_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
807     if (CURLE_OK == res)
808     {
809       if (http_result == 200)
810       {
811         ps->recv_connected = GNUNET_YES;
812         ps->recv_active = GNUNET_YES;
813         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to recieve data\n",ps);
814         // Calling send_check_connections again since receive is established
815         send_check_connections (ps->peercontext->plugin, NULL, ps);
816       }
817     }
818   }
819
820   tmp = NULL;
821   if ((size * nmemb) < SIZE_MAX)
822     tmp = GNUNET_malloc (len+1);
823
824   if ((tmp != NULL) && (len > 0))
825   {
826     memcpy(tmp,ptr,len);
827     if (len>=2)
828     {
829       if (tmp[len-2] == 13)
830         tmp[len-2]= '\0';
831     }
832 #if DEBUG_HTTP
833     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Header: `%s' %u \n",tmp, http_result);
834 #endif
835   }
836   if (NULL != tmp)
837     GNUNET_free (tmp);
838
839   return size * nmemb;
840 }
841
842 static size_t curl_put_header_function( void *ptr, size_t size, size_t nmemb, void *stream)
843 {
844   struct Session * ps = stream;
845
846   char * tmp;
847   size_t len = size * nmemb;
848   long http_result = 0;
849   int res;
850
851   /* Getting last http result code */
852   GNUNET_assert(NULL!=ps);
853   res = curl_easy_getinfo(ps->send_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
854   if (CURLE_OK == res)
855   {
856     if ((http_result == 100) && (ps->send_connected==GNUNET_NO))
857     {
858       ps->send_connected = GNUNET_YES;
859       ps->send_active = GNUNET_YES;
860       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to send data\n",ps);
861     }
862     if ((http_result == 200) && (ps->send_connected==GNUNET_YES))
863     {
864       ps->send_connected = GNUNET_NO;
865       ps->send_active = GNUNET_NO;
866       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: sending disconnected\n",ps);
867     }
868   }
869
870   tmp = NULL;
871   if ((size * nmemb) < SIZE_MAX)
872     tmp = GNUNET_malloc (len+1);
873
874   if ((tmp != NULL) && (len > 0))
875   {
876     memcpy(tmp,ptr,len);
877     if (len>=2)
878     {
879       if (tmp[len-2] == 13)
880         tmp[len-2]= '\0';
881     }
882 #if DEBUG_HTTP
883     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Header: `%s' %u \n",tmp, http_result);
884 #endif
885   }
886   if (NULL != tmp)
887     GNUNET_free (tmp);
888
889   return size * nmemb;
890 }
891
892 /**
893  * Callback method used with libcurl
894  * Method is called when libcurl needs to read data during sending
895  * @param stream pointer where to write data
896  * @param size size of an individual element
897  * @param nmemb count of elements that can be written to the buffer
898  * @param ptr source pointer, passed to the libcurl handle
899  * @return bytes written to stream
900  */
901 static size_t send_curl_send_callback(void *stream, size_t size, size_t nmemb, void *ptr)
902 {
903   struct Session * ps = ptr;
904   struct HTTP_Message * msg = ps->pending_msgs_tail;
905   size_t bytes_sent;
906   size_t len;
907
908   if (ps->pending_msgs_tail == NULL)
909   {
910     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: No Message to send, pausing connection\n",ps);
911     ps->send_active = GNUNET_NO;
912     return CURL_READFUNC_PAUSE;
913   }
914
915   msg = ps->pending_msgs_tail;
916   /* data to send */
917   if (msg->pos < msg->size)
918   {
919     /* data fit in buffer */
920     if ((msg->size - msg->pos) <= (size * nmemb))
921     {
922       len = (msg->size - msg->pos);
923       memcpy(stream, &msg->buf[msg->pos], len);
924       msg->pos += len;
925       bytes_sent = len;
926     }
927     else
928     {
929       len = size*nmemb;
930       memcpy(stream, &msg->buf[msg->pos], len);
931       msg->pos += len;
932       bytes_sent = len;
933     }
934   }
935   /* no data to send */
936   else
937   {
938     bytes_sent = 0;
939   }
940
941   if ( msg->pos == msg->size)
942   {
943     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Message with %u bytes sent, removing message from queue \n",ps, msg->pos);
944     /* Calling transmit continuation  */
945     if (( NULL != ps->pending_msgs_tail) && (NULL != ps->pending_msgs_tail->transmit_cont))
946       msg->transmit_cont (ps->pending_msgs_tail->transmit_cont_cls,&(ps->peercontext)->identity,GNUNET_OK);
947     remove_http_message(ps, msg);
948   }
949   return bytes_sent;
950 }
951
952 /**
953 * Callback method used with libcurl
954 * Method is called when libcurl needs to write data during sending
955 * @param stream pointer where to write data
956 * @param size size of an individual element
957 * @param nmemb count of elements that can be written to the buffer
958 * @param ptr destination pointer, passed to the libcurl handle
959 * @return bytes read from stream
960 */
961 static size_t send_curl_receive_callback( void *stream, size_t size, size_t nmemb, void *ptr)
962 {
963   struct Session * ps = ptr;
964
965   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: %u bytes recieved\n",ps, size*nmemb);
966   GNUNET_SERVER_mst_receive(ps->msgtok, ps, stream, size*nmemb, GNUNET_NO, GNUNET_NO);
967
968   return (size * nmemb);
969
970 }
971
972 /**
973  * Function setting up file descriptors and scheduling task to run
974  * @param cls closure
975  * @param ses session to send data to
976  * @return bytes sent to peer
977  */
978 static size_t send_schedule(void *cls, struct Session* ses );
979
980
981
982 /**
983  * Function setting up curl handle and selecting message to send
984  * @param cls plugin
985  * @param ses session to send data to
986  * @param con connection
987  * @return bytes sent to peer
988  */
989 static ssize_t send_check_connections (void *cls, struct Session* ses , struct Session *ps)
990 {
991   struct Plugin *plugin = cls;
992   int bytes_sent = 0;
993   CURLMcode mret;
994   struct HTTP_Message * msg;
995   struct GNUNET_TIME_Relative timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
996
997   GNUNET_assert(cls !=NULL);
998
999   if (ps->direction == OUTBOUND)
1000   {
1001     /* RECV DIRECTION */
1002     /* Check if session is connected to receive data, otherwise connect to peer */
1003     if (ps->recv_connected == GNUNET_NO)
1004     {
1005         if (ps->recv_endpoint == NULL)
1006         {
1007           ps->recv_endpoint = curl_easy_init();
1008 #if DEBUG_CURL
1009         curl_easy_setopt(ps->recv_endpoint, CURLOPT_VERBOSE, 1L);
1010 #endif
1011         curl_easy_setopt(ps->recv_endpoint, CURLOPT_URL, ps->url);
1012         curl_easy_setopt(ps->recv_endpoint, CURLOPT_HEADERFUNCTION, &curl_get_header_function);
1013         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEHEADER, ps);
1014         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READFUNCTION, send_curl_send_callback);
1015         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READDATA, ps);
1016         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEFUNCTION, send_curl_receive_callback);
1017         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEDATA, ps);
1018         curl_easy_setopt(ps->recv_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
1019         curl_easy_setopt(ps->recv_endpoint, CURLOPT_PRIVATE, ps);
1020         curl_easy_setopt(ps->recv_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
1021         curl_easy_setopt(ps->recv_endpoint, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);
1022
1023         mret = curl_multi_add_handle(plugin->multi_handle, ps->recv_endpoint);
1024         if (mret != CURLM_OK)
1025         {
1026           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1027                       _("%s failed at %s:%d: `%s'\n"),
1028                       "curl_multi_add_handle", __FILE__, __LINE__,
1029                       curl_multi_strerror (mret));
1030           return -1;
1031         }
1032         bytes_sent = send_schedule (plugin, NULL);
1033         if (ps->msgtok != NULL)
1034           ps->msgtok = GNUNET_SERVER_mst_create (&curl_write_mst_cb, ps);
1035         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound not connected, initiating connection\n",ps);
1036       }
1037     }
1038
1039     /* waiting for receive direction */
1040     if (ps->recv_connected==GNUNET_NO)
1041       return 0;
1042
1043     /* SEND DIRECTION */
1044     /* Check if session is connected to send data, otherwise connect to peer */
1045     if ((ps->send_connected == GNUNET_YES) && (ps->send_endpoint!= NULL))
1046     {
1047       if (ps->send_active == GNUNET_YES)
1048       {
1049         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound active, enqueueing message\n",ps);
1050         return bytes_sent;
1051       }
1052       if (ps->send_active == GNUNET_NO)
1053       {
1054         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound paused, unpausing existing connection and enqueueing message\n",ps);
1055         curl_easy_pause(ps->send_endpoint,CURLPAUSE_CONT);
1056         ps->send_active=GNUNET_YES;
1057         return bytes_sent;
1058       }
1059     }
1060     /* not connected, initiate connection */
1061     if ((ps->send_connected==GNUNET_NO) && (NULL == ps->send_endpoint))
1062       ps->send_endpoint = curl_easy_init();
1063     GNUNET_assert (ps->send_endpoint != NULL);
1064     GNUNET_assert (NULL != ps->pending_msgs_tail);
1065     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound not connected, initiating connection\n",ps);
1066     ps->send_active = GNUNET_NO;
1067     msg = ps->pending_msgs_tail;
1068
1069   #if DEBUG_CURL
1070     curl_easy_setopt(ps->send_endpoint, CURLOPT_VERBOSE, 1L);
1071   #endif
1072     curl_easy_setopt(ps->send_endpoint, CURLOPT_URL, ps->url);
1073     curl_easy_setopt(ps->send_endpoint, CURLOPT_PUT, 1L);
1074     curl_easy_setopt(ps->send_endpoint, CURLOPT_HEADERFUNCTION, &curl_put_header_function);
1075     curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEHEADER, ps);
1076     curl_easy_setopt(ps->send_endpoint, CURLOPT_READFUNCTION, send_curl_send_callback);
1077     curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
1078     curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEFUNCTION, send_curl_receive_callback);
1079     curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
1080     curl_easy_setopt(ps->send_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
1081     curl_easy_setopt(ps->send_endpoint, CURLOPT_PRIVATE, ps);
1082     curl_easy_setopt(ps->send_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
1083     curl_easy_setopt(ps->send_endpoint, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);
1084
1085     mret = curl_multi_add_handle(plugin->multi_handle, ps->send_endpoint);
1086     if (mret != CURLM_OK)
1087     {
1088       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1089                   _("%s failed at %s:%d: `%s'\n"),
1090                   "curl_multi_add_handle", __FILE__, __LINE__,
1091                   curl_multi_strerror (mret));
1092       return -1;
1093     }
1094     bytes_sent = send_schedule (plugin, NULL);
1095     return bytes_sent;
1096   }
1097   if (ps->direction == INBOUND)
1098   {
1099     GNUNET_assert (NULL != ps->pending_msgs_tail);
1100     msg = ps->pending_msgs_tail;
1101     if ((ps->recv_connected==GNUNET_YES) && (ps->recv_connected==GNUNET_YES))
1102         bytes_sent = msg->size;
1103     return bytes_sent;
1104   }
1105   return 0;
1106 }
1107
1108 static void send_execute (void *cls,
1109              const struct GNUNET_SCHEDULER_TaskContext *tc)
1110 {
1111   struct Plugin *plugin = cls;
1112   static unsigned int handles_last_run;
1113   int running;
1114   struct CURLMsg *msg;
1115   CURLMcode mret;
1116   struct Session *ps = NULL;
1117   struct HTTP_PeerContext *pc = NULL;
1118   struct HTTP_Message * cur_msg = NULL;
1119   long http_result;
1120
1121   GNUNET_assert(cls !=NULL);
1122   plugin->http_server_task_send = GNUNET_SCHEDULER_NO_TASK;
1123   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1124     return;
1125
1126   do
1127     {
1128       running = 0;
1129       mret = curl_multi_perform (plugin->multi_handle, &running);
1130       if (running < handles_last_run)
1131         {
1132           do
1133             {
1134
1135               msg = curl_multi_info_read (plugin->multi_handle, &running);
1136               if (msg == NULL)
1137                 break;
1138               /* get session for affected curl handle */
1139               GNUNET_assert ( msg->easy_handle != NULL );
1140               curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char *) &ps);
1141               GNUNET_assert ( ps != NULL );
1142               pc = ps->peercontext;
1143               GNUNET_assert ( pc != NULL );
1144               switch (msg->msg)
1145                 {
1146
1147                 case CURLMSG_DONE:
1148                   if ( (msg->data.result != CURLE_OK) &&
1149                        (msg->data.result != CURLE_GOT_NOTHING) )
1150                   {
1151                     /* sending msg failed*/
1152                     if (msg->easy_handle == ps->send_endpoint)
1153                     {
1154                       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1155                                  _("Connection %X: HTTP PUT to peer `%s' (`%s') failed: `%s' `%s'\n"),
1156                                  ps,
1157                                  GNUNET_i2s(&pc->identity),
1158                                  http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1159                                  "curl_multi_perform",
1160                                  curl_easy_strerror (msg->data.result));
1161
1162                       ps->send_connected = GNUNET_NO;
1163                       ps->send_active = GNUNET_NO;
1164                       curl_multi_remove_handle(plugin->multi_handle,msg->easy_handle);
1165                       curl_easy_cleanup(ps->send_endpoint);
1166                       ps->send_endpoint=NULL;
1167                       cur_msg = ps->pending_msgs_tail;
1168                       if (( NULL != cur_msg) && ( NULL != cur_msg->transmit_cont))
1169                         cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1170                     }
1171                     /* GET connection failed */
1172                     if (msg->easy_handle == ps->recv_endpoint)
1173                     {
1174                       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1175                            _("Connection %X: HTTP GET to peer `%s' (`%s') failed: `%s' `%s'\n"),
1176                            ps,
1177                            GNUNET_i2s(&pc->identity),
1178                            http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1179                            "curl_multi_perform",
1180                            curl_easy_strerror (msg->data.result));
1181                       ps->recv_connected = GNUNET_NO;
1182                       ps->recv_active = GNUNET_NO;
1183                       curl_multi_remove_handle(plugin->multi_handle,msg->easy_handle);
1184                       curl_easy_cleanup(ps->recv_endpoint);
1185                       ps->recv_endpoint=NULL;
1186                     }
1187                   }
1188                   else
1189                   {
1190                     if (msg->easy_handle == ps->send_endpoint)
1191                     {
1192                       GNUNET_assert (CURLE_OK == curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_result));
1193                       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1194                                   "Connection %X: HTTP PUT connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1195                                    ps,
1196                                    GNUNET_i2s(&pc->identity),
1197                                    http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1198                                    http_result);
1199
1200                       /* Calling transmit continuation  */
1201                       cur_msg = ps->pending_msgs_tail;
1202                       if (( NULL != cur_msg) && (NULL != cur_msg->transmit_cont))
1203                       {
1204                         /* HTTP 1xx : Last message before here was informational */
1205                         if ((http_result >=100) && (http_result < 200))
1206                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1207                         /* HTTP 2xx: successful operations */
1208                         if ((http_result >=200) && (http_result < 300))
1209                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1210                         /* HTTP 3xx..5xx: error */
1211                         if ((http_result >=300) && (http_result < 600))
1212                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1213                       }
1214                       ps->send_connected = GNUNET_NO;
1215                       ps->send_active = GNUNET_NO;
1216                       curl_multi_remove_handle(plugin->multi_handle,msg->easy_handle);
1217                       curl_easy_cleanup(ps->send_endpoint);
1218                       ps->send_endpoint =NULL;
1219                     }
1220                     if (msg->easy_handle == ps->recv_endpoint)
1221                     {
1222                       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1223                                   "Connection %X: HTTP GET connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1224                                    ps,
1225                                    GNUNET_i2s(&pc->identity),
1226                                    http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1227                                    http_result);
1228
1229                       ps->recv_connected = GNUNET_NO;
1230                       ps->recv_active = GNUNET_NO;
1231                       curl_multi_remove_handle(plugin->multi_handle,msg->easy_handle);
1232                       curl_easy_cleanup(ps->recv_endpoint);
1233                       ps->recv_endpoint=NULL;
1234                     }
1235                   }
1236                   if (ps->pending_msgs_tail != NULL)
1237                   {
1238                     if (ps->pending_msgs_tail->pos>0)
1239                       remove_http_message(ps, ps->pending_msgs_tail);
1240                   }
1241                   return;
1242                 default:
1243                   break;
1244                 }
1245
1246             }
1247           while ( (running > 0) );
1248         }
1249       handles_last_run = running;
1250     }
1251   while (mret == CURLM_CALL_MULTI_PERFORM);
1252   send_schedule(plugin, cls);
1253 }
1254
1255
1256 /**
1257  * Function setting up file descriptors and scheduling task to run
1258  * @param ses session to send data to
1259  * @return bytes sent to peer
1260  */
1261 static size_t send_schedule(void *cls, struct Session* ses )
1262 {
1263   struct Plugin *plugin = cls;
1264   fd_set rs;
1265   fd_set ws;
1266   fd_set es;
1267   int max;
1268   struct GNUNET_NETWORK_FDSet *grs;
1269   struct GNUNET_NETWORK_FDSet *gws;
1270   long to;
1271   CURLMcode mret;
1272
1273   GNUNET_assert(cls !=NULL);
1274   max = -1;
1275   FD_ZERO (&rs);
1276   FD_ZERO (&ws);
1277   FD_ZERO (&es);
1278   mret = curl_multi_fdset (plugin->multi_handle, &rs, &ws, &es, &max);
1279   if (mret != CURLM_OK)
1280     {
1281       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1282                   _("%s failed at %s:%d: `%s'\n"),
1283                   "curl_multi_fdset", __FILE__, __LINE__,
1284                   curl_multi_strerror (mret));
1285       return -1;
1286     }
1287   mret = curl_multi_timeout (plugin->multi_handle, &to);
1288   if (mret != CURLM_OK)
1289     {
1290       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1291                   _("%s failed at %s:%d: `%s'\n"),
1292                   "curl_multi_timeout", __FILE__, __LINE__,
1293                   curl_multi_strerror (mret));
1294       return -1;
1295     }
1296
1297   grs = GNUNET_NETWORK_fdset_create ();
1298   gws = GNUNET_NETWORK_fdset_create ();
1299   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1300   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1301   plugin->http_server_task_send = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1302                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1303                                    GNUNET_SCHEDULER_NO_TASK,
1304                                    GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 0),
1305                                    grs,
1306                                    gws,
1307                                    &send_execute,
1308                                    plugin);
1309   GNUNET_NETWORK_fdset_destroy (gws);
1310   GNUNET_NETWORK_fdset_destroy (grs);
1311
1312   /* FIXME: return bytes REALLY sent */
1313   return 0;
1314 }
1315
1316
1317 /**
1318  * Function that can be used by the transport service to transmit
1319  * a message using the plugin.   Note that in the case of a
1320  * peer disconnecting, the continuation MUST be called
1321  * prior to the disconnect notification itself.  This function
1322  * will be called with this peer's HELLO message to initiate
1323  * a fresh connection to another peer.
1324  *
1325  * @param cls closure
1326  * @param target who should receive this message
1327  * @param msgbuf the message to transmit
1328  * @param msgbuf_size number of bytes in 'msgbuf'
1329  * @param priority how important is the message (most plugins will
1330  *                 ignore message priority and just FIFO)
1331  * @param timeout how long to wait at most for the transmission (does not
1332  *                require plugins to discard the message after the timeout,
1333  *                just advisory for the desired delay; most plugins will ignore
1334  *                this as well)
1335  * @param session which session must be used (or NULL for "any")
1336  * @param addr the address to use (can be NULL if the plugin
1337  *                is "on its own" (i.e. re-use existing TCP connection))
1338  * @param addrlen length of the address in bytes
1339  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1340  *                GNUNET_NO means the plugin may use any other address and
1341  *                GNUNET_SYSERR means that only reliable existing
1342  *                bi-directional connections should be used (regardless
1343  *                of address)
1344  * @param cont continuation to call once the message has
1345  *        been transmitted (or if the transport is ready
1346  *        for the next transmission call; or if the
1347  *        peer disconnected...); can be NULL
1348  * @param cont_cls closure for cont
1349  * @return number of bytes used (on the physical network, with overheads);
1350  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1351  *         and does NOT mean that the message was not transmitted (DV)
1352  */
1353 static ssize_t
1354 http_plugin_send (void *cls,
1355                   const struct GNUNET_PeerIdentity *target,
1356                   const char *msgbuf,
1357                   size_t msgbuf_size,
1358                   unsigned int priority,
1359                   struct GNUNET_TIME_Relative to,
1360                   struct Session *session,
1361                   const void *addr,
1362                   size_t addrlen,
1363                   int force_address,
1364                   GNUNET_TRANSPORT_TransmitContinuation cont,
1365                   void *cont_cls)
1366 {
1367   struct Plugin *plugin = cls;
1368   struct HTTP_Message *msg;
1369
1370   struct HTTP_PeerContext * pc;
1371   struct Session * ps;
1372
1373   GNUNET_assert(cls !=NULL);
1374   GNUNET_assert ((addr!=NULL) && (addrlen != 0));
1375
1376   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
1377   /* Peer unknown */
1378   if (pc==NULL)
1379   {
1380     pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
1381     pc->plugin = plugin;
1382     memcpy(&pc->identity, target, sizeof(struct GNUNET_PeerIdentity));
1383     GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1384   }
1385   ps = get_Session(plugin, pc, addr, addrlen);
1386   /* session not existing, but address forced -> creating new session */
1387   if ((ps==NULL) && (force_address == GNUNET_YES))
1388   {
1389     ps = GNUNET_malloc(sizeof (struct Session));
1390     ps->addr = GNUNET_malloc(addrlen);
1391     memcpy(ps->addr,addr,addrlen);
1392     ps->addrlen = addrlen;
1393     ps->direction=OUTBOUND;
1394     ps->recv_connected = GNUNET_NO;
1395     ps->send_connected = GNUNET_NO;
1396     ps->pending_msgs_head = NULL;
1397     ps->pending_msgs_tail = NULL;
1398     ps->peercontext=pc;
1399     ps->url = create_url (plugin, ps->addr, ps->addrlen);
1400     GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
1401   }
1402   /* session not existing, address not forced -> looking for other session */
1403   if ((ps==NULL) && (force_address == GNUNET_NO))
1404   {
1405     /* FIXME: CREATING SESSION, SHOULD CHOOSE EXISTING */
1406     ps = GNUNET_malloc(sizeof (struct Session));
1407     ps->addr = GNUNET_malloc(addrlen);
1408     memcpy(ps->addr,addr,addrlen);
1409     ps->addrlen = addrlen;
1410     ps->direction=OUTBOUND;
1411     ps->recv_connected = GNUNET_NO;
1412     ps->send_connected = GNUNET_NO;
1413     ps->pending_msgs_head = NULL;
1414     ps->pending_msgs_tail = NULL;
1415     ps->peercontext=pc;
1416     ps->url = create_url (plugin, ps->addr, ps->addrlen);
1417     GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
1418   }
1419   if ((ps==NULL) && (force_address == GNUNET_SYSERR))
1420   {
1421     /* FIXME: CREATING SESSION, SHOULD CHOOSE EXISTING */
1422     ps = GNUNET_malloc(sizeof (struct Session));
1423     ps->addr = GNUNET_malloc(addrlen);
1424     memcpy(ps->addr,addr,addrlen);
1425     ps->addrlen = addrlen;
1426     ps->direction=OUTBOUND;
1427     ps->recv_connected = GNUNET_NO;
1428     ps->send_connected = GNUNET_NO;
1429     ps->pending_msgs_head = NULL;
1430     ps->pending_msgs_tail = NULL;
1431     ps->peercontext=pc;
1432     ps->url = create_url (plugin, ps->addr, ps->addrlen);
1433     GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
1434   }
1435
1436   char * force = GNUNET_malloc(30);
1437   if (force_address == GNUNET_YES)
1438     strcpy(force,"forced addr.");
1439   if (force_address == GNUNET_NO)
1440     strcpy(force,"any addr.");
1441   if (force_address == GNUNET_SYSERR)
1442     strcpy(force,"reliable bi-direc. address addr.");
1443   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Transport tells me to send %u bytes to `%s' %s (%s), session: %X\n",
1444                                       msgbuf_size,
1445                                       GNUNET_i2s(&pc->identity),
1446                                       force,
1447                                       http_plugin_address_to_string(NULL, addr, addrlen),
1448                                       ps);
1449
1450   GNUNET_free(force);
1451   /* create msg */
1452   msg = GNUNET_malloc (sizeof (struct HTTP_Message) + msgbuf_size);
1453   msg->next = NULL;
1454   msg->size = msgbuf_size;
1455   msg->pos = 0;
1456   msg->buf = (char *) &msg[1];
1457   msg->transmit_cont = cont;
1458   msg->transmit_cont_cls = cont_cls;
1459   memcpy (msg->buf,msgbuf, msgbuf_size);
1460   GNUNET_CONTAINER_DLL_insert(ps->pending_msgs_head,ps->pending_msgs_tail,msg);
1461
1462   return send_check_connections (plugin, session, ps);
1463 }
1464
1465
1466
1467 /**
1468  * Function that can be used to force the plugin to disconnect
1469  * from the given peer and cancel all previous transmissions
1470  * (and their continuationc).
1471  *
1472  * @param cls closure
1473  * @param target peer from which to disconnect
1474  */
1475 static void
1476 http_plugin_disconnect (void *cls,
1477                             const struct GNUNET_PeerIdentity *target)
1478 {
1479
1480   struct Plugin *plugin = cls;
1481   struct HTTP_PeerContext *pc = NULL;
1482   struct Session *ps = NULL;
1483
1484   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
1485   if (pc==NULL)
1486     return;
1487
1488   ps = pc->head;
1489
1490   while (ps!=NULL)
1491   {
1492     if (ps->direction==OUTBOUND)
1493     {
1494       if (ps->send_endpoint!=NULL)
1495       {
1496         curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint);
1497         curl_easy_cleanup(ps->send_endpoint);
1498         ps->send_endpoint=NULL;
1499       }
1500       if (ps->recv_endpoint!=NULL)
1501       {
1502        curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint);
1503        curl_easy_cleanup(ps->recv_endpoint);
1504        ps->recv_endpoint=NULL;
1505       }
1506     }
1507     if (ps->direction==INBOUND)
1508     {
1509
1510     }
1511     while (ps->pending_msgs_head!=NULL)
1512     {
1513       remove_http_message(ps, ps->pending_msgs_head);
1514     }
1515     ps->recv_connected = GNUNET_NO;
1516     ps->recv_active = GNUNET_NO;
1517     ps->send_connected = GNUNET_NO;
1518     ps->send_active = GNUNET_NO;
1519     ps=ps->next;
1520   }
1521   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"All connections to peer `%s' terminated\n", GNUNET_i2s(target));
1522 }
1523
1524
1525 /**
1526  * Convert the transports address to a nice, human-readable
1527  * format.
1528  *
1529  * @param cls closure
1530  * @param type name of the transport that generated the address
1531  * @param addr one of the addresses of the host, NULL for the last address
1532  *        the specific address format depends on the transport
1533  * @param addrlen length of the address
1534  * @param numeric should (IP) addresses be displayed in numeric form?
1535  * @param timeout after how long should we give up?
1536  * @param asc function to call on each string
1537  * @param asc_cls closure for asc
1538  */
1539 static void
1540 http_plugin_address_pretty_printer (void *cls,
1541                                         const char *type,
1542                                         const void *addr,
1543                                         size_t addrlen,
1544                                         int numeric,
1545                                         struct GNUNET_TIME_Relative timeout,
1546                                         GNUNET_TRANSPORT_AddressStringCallback
1547                                         asc, void *asc_cls)
1548 {
1549   const struct IPv4HttpAddress *t4;
1550   const struct IPv6HttpAddress *t6;
1551   struct sockaddr_in a4;
1552   struct sockaddr_in6 a6;
1553   char * address;
1554   char * ret;
1555   unsigned int port;
1556   unsigned int res;
1557
1558   GNUNET_assert(cls !=NULL);
1559   if (addrlen == sizeof (struct IPv6HttpAddress))
1560   {
1561     address = GNUNET_malloc (INET6_ADDRSTRLEN);
1562     t6 = addr;
1563     a6.sin6_addr = t6->ipv6_addr;
1564     inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
1565     port = ntohs(t6->u6_port);
1566   }
1567   else if (addrlen == sizeof (struct IPv4HttpAddress))
1568   {
1569     address = GNUNET_malloc (INET_ADDRSTRLEN);
1570     t4 = addr;
1571     a4.sin_addr.s_addr =  t4->ipv4_addr;
1572     inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
1573     port = ntohs(t4->u_port);
1574   }
1575   else
1576   {
1577     /* invalid address */
1578     GNUNET_break_op (0);
1579     asc (asc_cls, NULL);
1580     return;
1581   }
1582   res = GNUNET_asprintf(&ret,"http://%s:%u/",address,port);
1583   GNUNET_free (address);
1584   GNUNET_assert(res != 0);
1585
1586   asc (asc_cls, ret);
1587 }
1588
1589
1590
1591 /**
1592  * Another peer has suggested an address for this
1593  * peer and transport plugin.  Check that this could be a valid
1594  * address.  If so, consider adding it to the list
1595  * of addresses.
1596  *
1597  * @param cls closure
1598  * @param addr pointer to the address
1599  * @param addrlen length of addr
1600  * @return GNUNET_OK if this is a plausible address for this peer
1601  *         and transport
1602  */
1603 static int
1604 http_plugin_address_suggested (void *cls,
1605                                const void *addr, size_t addrlen)
1606 {
1607   struct Plugin *plugin = cls;
1608   struct IPv4HttpAddress *v4;
1609   struct IPv6HttpAddress *v6;
1610   unsigned int port;
1611
1612   GNUNET_assert(cls !=NULL);
1613   if ((addrlen != sizeof (struct IPv4HttpAddress)) &&
1614       (addrlen != sizeof (struct IPv6HttpAddress)))
1615     {
1616       return GNUNET_SYSERR;
1617     }
1618   if (addrlen == sizeof (struct IPv4HttpAddress))
1619     {
1620       v4 = (struct IPv4HttpAddress *) addr;
1621       if (INADDR_LOOPBACK == ntohl(v4->ipv4_addr))
1622       {
1623         return GNUNET_SYSERR;
1624       }
1625       port = ntohs (v4->u_port);
1626       if (port != plugin->port_inbound)
1627       {
1628         return GNUNET_SYSERR;
1629       }
1630     }
1631   else
1632     {
1633       v6 = (struct IPv6HttpAddress *) addr;
1634       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1635         {
1636           return GNUNET_SYSERR;
1637         }
1638       port = ntohs (v6->u6_port);
1639       if (port != plugin->port_inbound)
1640       {
1641         return GNUNET_SYSERR;
1642       }
1643     }
1644   return GNUNET_OK;
1645 }
1646
1647
1648 /**
1649  * Function called for a quick conversion of the binary address to
1650  * a numeric address.  Note that the caller must not free the
1651  * address and that the next call to this function is allowed
1652  * to override the address again.
1653  *
1654  * @param cls closure
1655  * @param addr binary address
1656  * @param addrlen length of the address
1657  * @return string representing the same address
1658  */
1659 static const char*
1660 http_plugin_address_to_string (void *cls,
1661                                    const void *addr,
1662                                    size_t addrlen)
1663 {
1664   const struct IPv4HttpAddress *t4;
1665   const struct IPv6HttpAddress *t6;
1666   struct sockaddr_in a4;
1667   struct sockaddr_in6 a6;
1668   char * address;
1669   char * ret;
1670   uint16_t port;
1671   unsigned int res;
1672
1673   if (addrlen == sizeof (struct IPv6HttpAddress))
1674     {
1675       address = GNUNET_malloc (INET6_ADDRSTRLEN);
1676       t6 = addr;
1677       a6.sin6_addr = t6->ipv6_addr;
1678       inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
1679       port = ntohs(t6->u6_port);
1680     }
1681   else if (addrlen == sizeof (struct IPv4HttpAddress))
1682     {
1683       address = GNUNET_malloc (INET_ADDRSTRLEN);
1684       t4 = addr;
1685       a4.sin_addr.s_addr =  t4->ipv4_addr;
1686       inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
1687       port = ntohs(t4->u_port);
1688     }
1689   else
1690     {
1691       /* invalid address */
1692       return NULL;
1693     }
1694   res = GNUNET_asprintf(&ret,"%s:%u",address,port);
1695   GNUNET_free (address);
1696   GNUNET_assert(res != 0);
1697   return ret;
1698 }
1699
1700 /**
1701  * Add the IP of our network interface to the list of
1702  * our external IP addresses.
1703  *
1704  * @param cls the 'struct Plugin*'
1705  * @param name name of the interface
1706  * @param isDefault do we think this may be our default interface
1707  * @param addr address of the interface
1708  * @param addrlen number of bytes in addr
1709  * @return GNUNET_OK to continue iterating
1710  */
1711 static int
1712 process_interfaces (void *cls,
1713                     const char *name,
1714                     int isDefault,
1715                     const struct sockaddr *addr, socklen_t addrlen)
1716 {
1717   struct Plugin *plugin = cls;
1718   struct IPv4HttpAddress * t4;
1719   struct IPv6HttpAddress * t6;
1720   int af;
1721
1722   GNUNET_assert(cls !=NULL);
1723   af = addr->sa_family;
1724   if (af == AF_INET)
1725     {
1726       t4 = GNUNET_malloc(sizeof(struct IPv4HttpAddress));
1727       if (INADDR_LOOPBACK == ntohl(((struct sockaddr_in *) addr)->sin_addr.s_addr))
1728       {
1729         /* skip loopback addresses */
1730         return GNUNET_OK;
1731       }
1732       t4->ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1733       t4->u_port = htons (plugin->port_inbound);
1734       plugin->env->notify_address(plugin->env->cls,"http",t4, sizeof (struct IPv4HttpAddress), GNUNET_TIME_UNIT_FOREVER_REL);
1735
1736     }
1737   else if (af == AF_INET6)
1738     {
1739       t6 = GNUNET_malloc(sizeof(struct IPv6HttpAddress));
1740       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1741         {
1742           /* skip link local addresses */
1743           return GNUNET_OK;
1744         }
1745       if (IN6_IS_ADDR_LOOPBACK (&((struct sockaddr_in6 *) addr)->sin6_addr))
1746         {
1747           /* skip loopback addresses */
1748           return GNUNET_OK;
1749         }
1750       memcpy (&t6->ipv6_addr,
1751               &((struct sockaddr_in6 *) addr)->sin6_addr,
1752               sizeof (struct in6_addr));
1753       t6->u6_port = htons (plugin->port_inbound);
1754       plugin->env->notify_address(plugin->env->cls,"http",t6,sizeof (struct IPv6HttpAddress) , GNUNET_TIME_UNIT_FOREVER_REL);
1755     }
1756   return GNUNET_OK;
1757 }
1758
1759 int peer_context_Iterator (void *cls, const GNUNET_HashCode *key, void *value)
1760 {
1761   struct HTTP_PeerContext * pc = value;
1762   struct Session * ps = pc->head;
1763   struct Session * tmp = NULL;
1764   struct HTTP_Message * msg = NULL;
1765   struct HTTP_Message * msg_tmp = NULL;
1766
1767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing context for peer `%s'\n",GNUNET_i2s(&pc->identity));
1768
1769   while (ps!=NULL)
1770   {
1771     tmp = ps->next;
1772
1773     GNUNET_free(ps->addr);
1774     GNUNET_free(ps->url);
1775     if (ps->msgtok != NULL)
1776       GNUNET_SERVER_mst_destroy (ps->msgtok);
1777
1778     msg = ps->pending_msgs_head;
1779     while (msg!=NULL)
1780     {
1781       msg_tmp = msg->next;
1782       GNUNET_free(msg);
1783       msg = msg_tmp;
1784     }
1785     if (ps->direction==OUTBOUND)
1786     {
1787       if (ps->send_endpoint!=NULL)
1788         curl_easy_cleanup(ps->send_endpoint);
1789       if (ps->recv_endpoint!=NULL)
1790         curl_easy_cleanup(ps->recv_endpoint);
1791     }
1792
1793     GNUNET_free(ps);
1794     ps=tmp;
1795   }
1796   GNUNET_free(pc);
1797   return GNUNET_YES;
1798 }
1799
1800
1801 /**
1802  * Exit point from the plugin.
1803  */
1804 void *
1805 libgnunet_plugin_transport_http_done (void *cls)
1806 {
1807   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1808   struct Plugin *plugin = api->cls;
1809   CURLMcode mret;
1810
1811   GNUNET_assert(cls !=NULL);
1812
1813   if ( plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1814   {
1815     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
1816     plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
1817   }
1818
1819   if ( plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1820   {
1821     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
1822     plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1823   }
1824
1825   if ( plugin->http_server_task_send != GNUNET_SCHEDULER_NO_TASK)
1826   {
1827     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_send);
1828     plugin->http_server_task_send = GNUNET_SCHEDULER_NO_TASK;
1829   }
1830
1831   if (plugin->http_server_daemon_v4 != NULL)
1832   {
1833     MHD_stop_daemon (plugin->http_server_daemon_v4);
1834     plugin->http_server_daemon_v4 = NULL;
1835   }
1836   if (plugin->http_server_daemon_v6 != NULL)
1837   {
1838     MHD_stop_daemon (plugin->http_server_daemon_v6);
1839     plugin->http_server_daemon_v6 = NULL;
1840   }
1841
1842   /* free all peer information */
1843   GNUNET_CONTAINER_multihashmap_iterate (plugin->peers,
1844                                          &peer_context_Iterator,
1845                                          NULL);
1846   GNUNET_CONTAINER_multihashmap_destroy (plugin->peers);
1847
1848   mret = curl_multi_cleanup(plugin->multi_handle);
1849   if ( CURLM_OK != mret)
1850     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed");
1851
1852   GNUNET_free (plugin);
1853   GNUNET_free (api);
1854   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unload http plugin complete...\n");
1855   return NULL;
1856 }
1857
1858
1859 /**
1860  * Entry point for the plugin.
1861  */
1862 void *
1863 libgnunet_plugin_transport_http_init (void *cls)
1864 {
1865   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1866   struct Plugin *plugin;
1867   struct GNUNET_TRANSPORT_PluginFunctions *api;
1868   struct GNUNET_TIME_Relative gn_timeout;
1869   long long unsigned int port;
1870
1871   GNUNET_assert(cls !=NULL);
1872   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
1873
1874   plugin = GNUNET_malloc (sizeof (struct Plugin));
1875   plugin->env = env;
1876   plugin->peers = NULL;
1877
1878   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1879   api->cls = plugin;
1880   api->send = &http_plugin_send;
1881   api->disconnect = &http_plugin_disconnect;
1882   api->address_pretty_printer = &http_plugin_address_pretty_printer;
1883   api->check_address = &http_plugin_address_suggested;
1884   api->address_to_string = &http_plugin_address_to_string;
1885
1886   /* Hashing our identity to use it in URLs */
1887   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &plugin->my_ascii_hash_ident);
1888
1889   /* Reading port number from config file */
1890   if ((GNUNET_OK !=
1891        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1892                                               "transport-http",
1893                                               "PORT",
1894                                               &port)) ||
1895       (port > 65535) )
1896     {
1897       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1898                        "http",
1899                        _
1900                        ("Require valid port number for transport plugin `%s' in configuration!\n"),
1901                        "transport-http");
1902       libgnunet_plugin_transport_http_done (api);
1903       return NULL;
1904     }
1905   GNUNET_assert ((port > 0) && (port <= 65535));
1906   plugin->port_inbound = port;
1907   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1908   if ((plugin->http_server_daemon_v4 == NULL) && (plugin->http_server_daemon_v6 == NULL) && (port != 0))
1909     {
1910     plugin->http_server_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
1911                                        port,
1912                                        &acceptPolicyCallback,
1913                                        plugin , &accessHandlerCallback, plugin,
1914                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1915                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1916                                        MHD_OPTION_CONNECTION_TIMEOUT, (gn_timeout.value / 1000),
1917                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1918                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1919                                        MHD_OPTION_END);
1920     plugin->http_server_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
1921                                        port,
1922                                        &acceptPolicyCallback,
1923                                        plugin , &accessHandlerCallback, plugin,
1924                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1925                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1926                                        MHD_OPTION_CONNECTION_TIMEOUT, (gn_timeout.value / 1000),
1927                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1928                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1929                                        MHD_OPTION_END);
1930     }
1931   if (plugin->http_server_daemon_v4 != NULL)
1932     plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
1933   if (plugin->http_server_daemon_v6 != NULL)
1934     plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
1935
1936   if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1937     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
1938   else if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1939     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
1940   else
1941   {
1942     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No MHD was started, transport plugin not functional!\n");
1943     libgnunet_plugin_transport_http_done (api);
1944     return NULL;
1945   }
1946
1947   /* Initializing cURL */
1948   curl_global_init(CURL_GLOBAL_ALL);
1949   plugin->multi_handle = curl_multi_init();
1950
1951   if ( NULL == plugin->multi_handle )
1952   {
1953     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1954                      "http",
1955                      _("Could not initialize curl multi handle, failed to start http plugin!\n"),
1956                      "transport-http");
1957     libgnunet_plugin_transport_http_done (api);
1958     return NULL;
1959   }
1960
1961   plugin->peers = GNUNET_CONTAINER_multihashmap_create (10);
1962   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1963
1964   return api;
1965 }
1966
1967 /* end of plugin_transport_http.c */