dabb57a8e99831539896783baa8943474ddeac1f
[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 2, 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_server_lib.h"
32 #include "gnunet_service_lib.h"
33 #include "gnunet_statistics_service.h"
34 #include "gnunet_transport_service.h"
35 #include "gnunet_resolver_service.h"
36 #include "gnunet_server_lib.h"
37 #include "gnunet_container_lib.h"
38 #include "plugin_transport.h"
39 #include "gnunet_os_lib.h"
40 #include "microhttpd.h"
41 #include <curl/curl.h>
42
43
44 #define DEBUG_CURL GNUNET_NO
45 #define DEBUG_HTTP GNUNET_NO
46
47 /**
48  * Text of the response sent back after the last bytes of a PUT
49  * request have been received (just to formally obey the HTTP
50  * protocol).
51  */
52 #define HTTP_PUT_RESPONSE "Thank you!"
53
54 /**
55  * After how long do we expire an address that we
56  * learned from another peer if it is not reconfirmed
57  * by anyone?
58  */
59 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
60
61 /**
62  * Page returned if request invalid
63  */
64 #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>"
65
66 /**
67  * Timeout for a http connect
68  */
69 #define HTTP_CONNECT_TIMEOUT 30
70
71 /**
72  * Timeout for a http connect
73  */
74 #define HTTP_MESSAGE_INITIAL_BUFFERSIZE GNUNET_SERVER_MAX_MESSAGE_SIZE
75
76
77 /**
78  * Network format for IPv4 addresses.
79  */
80 struct IPv4HttpAddress
81 {
82   /**
83    * IPv4 address, in network byte order.
84    */
85   uint32_t ipv4_addr;
86
87   /**
88    * Port number, in network byte order.
89    */
90   uint16_t u_port;
91
92 };
93
94
95 /**
96  * Network format for IPv6 addresses.
97  */
98 struct IPv6HttpAddress
99 {
100   /**
101    * IPv6 address.
102    */
103   struct in6_addr ipv6_addr;
104
105   /**
106    * Port number, in network byte order.
107    */
108   uint16_t u6_port;
109
110 };
111
112
113
114 /**
115  *  Message to send using http
116  */
117 struct HTTP_Message
118 {
119   /**
120    * next pointer for double linked list
121    */
122   struct HTTP_Message * next;
123
124   /**
125    * previous pointer for double linked list
126    */
127   struct HTTP_Message * prev;
128
129   /**
130    * buffer containing data to send
131    */
132   char *buf;
133
134   /**
135    * amount of data already sent
136    */
137   size_t pos;
138
139   /**
140    * buffer length
141    */
142   size_t len;
143   
144   char * dest_url;
145
146   /**
147    * Continuation function to call once the transmission buffer
148    * has again space available.  NULL if there is no
149    * continuation to call.
150    */
151   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
152
153   /**
154    * Closure for transmit_cont.
155    */
156   void *transmit_cont_cls;
157 };
158
159
160 /**
161  * Session handle for connections.
162  */
163 struct Session
164 {
165
166   /**
167    * Stored in a linked list.
168    */
169   struct Session *next;
170
171   /**
172    * Pointer to the global plugin struct.
173    */
174   struct Plugin *plugin;
175
176   /**
177    * To whom are we talking to (set to our identity
178    * if we are still waiting for the welcome message)
179    */
180   struct GNUNET_PeerIdentity partner;
181
182   /**
183    * Sender's ip address to distinguish between incoming connections
184    */
185   //struct sockaddr_in * addr_inbound;
186
187   /**
188    * Sender's ip address to distinguish between incoming connections
189    */
190   void * addr_in;
191
192   size_t addr_in_len;
193
194   void * addr_out;
195
196   size_t addr_out_len;
197
198   /**
199    * Did we initiate the connection (GNUNET_YES) or the other peer (GNUNET_NO)?
200    */
201   int is_client;
202
203   /**
204    * Is the connection active (GNUNET_YES) or terminated (GNUNET_NO)?
205    */
206   int is_active;
207
208   /**
209    * At what time did we reset last_received last?
210    */
211   struct GNUNET_TIME_Absolute last_quota_update;
212
213   /**
214    * How many bytes have we received since the "last_quota_update"
215    * timestamp?
216    */
217   uint64_t last_received;
218
219   /**
220    * Number of bytes per ms that this peer is allowed
221    * to send to us.
222    */
223   uint32_t quota;
224
225   /**
226    * Is there a HTTP/PUT in progress?
227    */
228   int is_put_in_progress;
229
230   /**
231    * Is the http request invalid?
232    */
233   int is_bad_request;
234
235   /**
236    * Encoded hash
237    */
238   struct GNUNET_CRYPTO_HashAsciiEncoded hash;
239
240   /**
241    * Head of dll used to store outbound messages
242    */
243   struct HTTP_Message * pending_outbound_msg_head;
244
245   /**
246    * Tail of dll used to store outbound messages
247    */
248   struct HTTP_Message * pending_outbound_msg_tail;
249
250   /**
251    * Incoming message
252    */
253   struct HTTP_Message * pending_inbound_msg;
254
255   /**
256    * curl handle for outbound transmissions
257    */
258   CURL *curl_handle;
259
260   /**
261    * Message tokenizer for incoming data
262    */
263   struct GNUNET_SERVER_MessageStreamTokenizer * msgtok;
264 };
265
266 /**
267  * Encapsulation of all of the state of the plugin.
268  */
269 struct Plugin
270 {
271   /**
272    * Our environment.
273    */
274   struct GNUNET_TRANSPORT_PluginEnvironment *env;
275
276   unsigned int port_inbound;
277
278   /**
279    * Hashmap for all existing sessions.
280    */
281   struct GNUNET_CONTAINER_MultiHashMap *sessions;
282
283   /**
284    * Daemon for listening for new IPv4 connections.
285    */
286   struct MHD_Daemon *http_daemon_v4;
287
288   /**
289    * Daemon for listening for new IPv6connections.
290    */
291   struct MHD_Daemon *http_daemon_v6;
292
293   /**
294    * Our primary task for http daemon handling IPv4 connections
295    */
296   GNUNET_SCHEDULER_TaskIdentifier http_task_v4;
297
298   /**
299    * Our primary task for http daemon handling IPv6 connections
300    */
301   GNUNET_SCHEDULER_TaskIdentifier http_task_v6;
302
303   /**
304    * The task sending data
305    */
306   GNUNET_SCHEDULER_TaskIdentifier http_task_send;
307
308   /**
309    * cURL Multihandle
310    */
311   CURLM * multi_handle;
312
313   /**
314    * Our ASCII encoded, hashed peer identity
315    * This string is used to distinguish between connections and is added to the urls
316    */
317   struct GNUNET_CRYPTO_HashAsciiEncoded my_ascii_hash_ident;
318 };
319
320 /**
321  * Create a new session
322  *
323  * @param addr_in address the peer is using inbound
324  * @param addr_out address the peer is using outbound
325  * @param peer identity
326  * @return created session object
327  */
328 static struct Session * create_session (void * cls, char * addr_in, size_t addrlen_in, char * addr_out, size_t addrlen_out, const struct GNUNET_PeerIdentity *peer)
329 {
330   struct Plugin *plugin = cls;
331   struct Session * ses = GNUNET_malloc ( sizeof( struct Session) );
332
333   GNUNET_assert(cls !=NULL);
334   if (addrlen_in != 0)
335   {
336     ses->addr_in = GNUNET_malloc (addrlen_in);
337     ses->addr_in_len = addrlen_in;
338     memcpy(ses->addr_in,addr_in,addrlen_in);
339   }
340
341   if (addrlen_out != 0)
342   {
343     ses->addr_out = GNUNET_malloc (addrlen_out);
344     ses->addr_out_len = addrlen_out;
345     memcpy(ses->addr_out,addr_out,addrlen_out);
346   }
347   ses->plugin = plugin;
348   memcpy(&ses->partner, peer, sizeof (struct GNUNET_PeerIdentity));
349   GNUNET_CRYPTO_hash_to_enc(&ses->partner.hashPubKey,&(ses->hash));
350   ses->is_active = GNUNET_NO;
351   ses->pending_inbound_msg = GNUNET_malloc( sizeof (struct HTTP_Message));
352   ses->pending_inbound_msg->buf = GNUNET_malloc(GNUNET_SERVER_MAX_MESSAGE_SIZE);
353   ses->pending_inbound_msg->len = GNUNET_SERVER_MAX_MESSAGE_SIZE;
354   ses->pending_inbound_msg->pos = 0;
355   ses->msgtok = NULL;
356   return ses;
357 }
358
359 /**
360  * Callback called by MHD when a connection is terminated
361  */
362 static void requestCompletedCallback (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
363 {
364   struct Session * cs;
365
366   cs = *httpSessionCache;
367   if (cs == NULL)
368     return;
369     /*GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection from peer `%s' was terminated\n",GNUNET_i2s(&cs->partner));*/
370     /* session set to inactive */
371     cs->is_active = GNUNET_NO;
372     cs->is_put_in_progress = GNUNET_NO;
373 }
374
375
376 static void messageTokenizerCallback (void *cls,
377                                       void *client,
378                                       const struct GNUNET_MessageHeader *message)
379 {
380   struct Session * cs = cls;
381   GNUNET_assert(cs != NULL);
382
383   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
384               "Received message with type %u and size %u from `%s'\n",
385               ntohs(message->type),
386               ntohs(message->size),
387               GNUNET_i2s(&(cs->partner)));
388   cs->plugin->env->receive(cs->plugin->env->cls,
389                            &cs->partner,
390                            message, 1, NULL,
391                            NULL, 0);
392 }
393
394 /**
395  * Check if ip is allowed to connect.
396  */
397 static int
398 acceptPolicyCallback (void *cls,
399                       const struct sockaddr *addr, socklen_t addr_len)
400 {
401 #if 0
402   struct Plugin *plugin = cls;
403 #endif
404   /* Every connection is accepted, nothing more to do here */
405   return MHD_YES;
406 }
407
408 /**
409  * Process GET or PUT request received via MHD.  For
410  * GET, queue response that will send back our pending
411  * messages.  For PUT, process incoming data and send
412  * to GNUnet core.  In either case, check if a session
413  * already exists and create a new one if not.
414  */
415 static int
416 accessHandlerCallback (void *cls,
417                        struct MHD_Connection *session,
418                        const char *url,
419                        const char *method,
420                        const char *version,
421                        const char *upload_data,
422                        size_t * upload_data_size, void **httpSessionCache)
423 {
424   struct Plugin *plugin = cls;
425   struct MHD_Response *response;
426   struct Session * cs;
427   const union MHD_ConnectionInfo * conn_info;
428   struct sockaddr_in  *addrin;
429   struct sockaddr_in6 *addrin6;
430   char address[INET6_ADDRSTRLEN+14];
431   struct GNUNET_PeerIdentity pi_in;
432   int res = GNUNET_NO;
433   struct GNUNET_MessageHeader *cur_msg;
434   int send_error_to_client;
435   struct IPv4HttpAddress ipv4addr;
436   struct IPv6HttpAddress ipv6addr;
437
438   GNUNET_assert(cls !=NULL);
439   cur_msg = NULL;
440   send_error_to_client = GNUNET_NO;
441
442   if ( NULL == *httpSessionCache)
443   {
444     /* check url for peer identity */
445     res = GNUNET_CRYPTO_hash_from_string ( &url[1], &(pi_in.hashPubKey));
446     if ( GNUNET_SYSERR == res )
447     {
448       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
449       res = MHD_queue_response (session, MHD_HTTP_NOT_FOUND, response);
450       MHD_destroy_response (response);
451       if (res == MHD_YES)
452         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, sent HTTP 1.1/404\n");
453       else
454         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, could not send error\n");
455       return res;
456     }
457
458     conn_info = MHD_get_connection_info(session, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
459     /* Incoming IPv4 connection */
460     if ( AF_INET == conn_info->client_addr->sin_family)
461     {
462       addrin = conn_info->client_addr;
463       inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
464       memcpy(&ipv4addr.ipv4_addr,&(addrin->sin_addr),sizeof(struct in_addr));
465       ipv4addr.u_port = addrin->sin_port;
466     }
467     /* Incoming IPv6 connection */
468     if ( AF_INET6 == conn_info->client_addr->sin_family)
469     {
470       addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
471       inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
472       memcpy(&ipv6addr.ipv6_addr,&(addrin6->sin6_addr),sizeof(struct in_addr));
473       ipv6addr.u6_port = addrin6->sin6_port;
474     }
475     /* find existing session for address */
476     cs = GNUNET_CONTAINER_multihashmap_get (plugin->sessions, &pi_in.hashPubKey);
477     /* no existing session, create a new one*/
478     if (cs == NULL )
479     {
480       /* create new session object */
481       if ( AF_INET6 == conn_info->client_addr->sin_family)
482         cs = create_session(plugin, (char *) &ipv6addr, sizeof(struct IPv6HttpAddress),NULL, 0, &pi_in);
483       if ( AF_INET == conn_info->client_addr->sin_family)
484         cs = create_session(plugin, (char *) &ipv4addr, sizeof(struct IPv4HttpAddress),NULL, 0, &pi_in);
485
486       /* Insert session into hashmap */
487       GNUNET_CONTAINER_multihashmap_put ( plugin->sessions,
488                                           &cs->partner.hashPubKey,
489                                           cs,
490                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
491
492       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"New Session for peer `%s' inserted\n", GNUNET_i2s(&cs->partner));
493     }
494
495     /* Set closure and update current session*/
496     if (*httpSessionCache == NULL)
497     {
498       *httpSessionCache = cs;
499       /* Updating session */
500       /*
501       memcpy(cs->addr_inbound,conn_info->client_addr, sizeof(struct sockaddr_in));
502       if ( AF_INET == cs->addr_inbound->sin_family)
503       {
504         GNUNET_asprintf(&cs->addr_inbound_str,"%s:%u",address,ntohs(cs->addr_inbound->sin_port));
505       }
506
507       if ( AF_INET6 == cs->addr_inbound->sin_family)
508       {
509         GNUNET_asprintf(&cs->addr_inbound_str,"[%s]:%u",address,ntohs(cs->addr_inbound->sin_port));
510
511       }
512       */
513       if (cs->msgtok==NULL)
514         cs->msgtok = GNUNET_SERVER_mst_create (GNUNET_SERVER_MAX_MESSAGE_SIZE, &messageTokenizerCallback, cs);
515     }
516     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Daemon has new an incoming `%s' request from peer `%s'\n",method, GNUNET_i2s(&cs->partner));
517   }
518   else
519   {
520     cs = *httpSessionCache;
521   }
522   /* Is it a PUT or a GET request */
523   if ( 0 == strcmp (MHD_HTTP_METHOD_PUT, method) )
524   {
525     /* New  */
526     if ((*upload_data_size == 0) && (cs->is_put_in_progress == GNUNET_NO))
527     {
528       if (cs->pending_inbound_msg->pos !=0 )
529       {
530         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
531                     _("Incoming message from peer `%s', while existing message with %u bytes was not forwarded to transport'\n"),
532                     GNUNET_i2s(&cs->partner), cs->pending_inbound_msg->pos);
533         cs->pending_inbound_msg->pos = 0;
534       }
535       /* not yet ready */
536       cs->is_put_in_progress = GNUNET_YES;
537       cs->is_bad_request = GNUNET_NO;
538       cs->is_active = GNUNET_YES;
539       return MHD_YES;
540     }
541
542     if ((*upload_data_size > 0) && (cs->is_bad_request != GNUNET_YES))
543     {
544       if ((*upload_data_size + cs->pending_inbound_msg->pos < cs->pending_inbound_msg->len) && (*upload_data_size + cs->pending_inbound_msg->pos <= GNUNET_SERVER_MAX_MESSAGE_SIZE))
545       {
546         /* copy uploaded data to buffer */
547
548         res = GNUNET_SERVER_mst_receive(cs->msgtok, cs, upload_data,*upload_data_size, GNUNET_YES, GNUNET_NO);
549         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"%u bytes forwarded to MST: result: %u\n",*upload_data_size, res);
550         cs->pending_inbound_msg->pos += *upload_data_size;
551         *upload_data_size = 0;
552         return MHD_YES;
553       }
554       else
555       {
556         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"%u bytes not added to message of %u bytes, message to big\n",*upload_data_size, cs->pending_inbound_msg->pos);
557         cs->is_bad_request = GNUNET_YES;
558         /* (*upload_data_size) bytes not processed */
559         return MHD_YES;
560       }
561     }
562
563     if ((cs->is_put_in_progress == GNUNET_YES) && (cs->is_bad_request == GNUNET_YES))
564     {
565       *upload_data_size = 0;
566       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
567       res = MHD_queue_response (session, MHD_HTTP_REQUEST_ENTITY_TOO_LARGE, response);
568       if (res == MHD_YES)
569       {
570         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Sent HTTP/1.1: 413 Request Entity Too Large as PUT Response\n");
571         cs->is_bad_request = GNUNET_NO;
572         cs->is_put_in_progress =GNUNET_NO;
573         cs->pending_inbound_msg->pos = 0;
574       }
575       MHD_destroy_response (response);
576       return MHD_YES;
577     }
578
579     /* Transmission of all data complete */
580     if ((*upload_data_size == 0) && (cs->is_put_in_progress == GNUNET_YES) && (cs->is_bad_request == GNUNET_NO))
581     {
582       send_error_to_client = GNUNET_YES;
583       cur_msg = NULL;
584       if (cs->pending_inbound_msg->pos >= sizeof (struct GNUNET_MessageHeader))
585       {
586         cur_msg = (struct GNUNET_MessageHeader *) cs->pending_inbound_msg->buf;
587         //res = GNUNET_SERVER_mst_receive(cs->msgtok, cs, cs->pending_inbound_msg->buf,cs->pending_inbound_msg->pos, GNUNET_YES, GNUNET_NO);
588         res = GNUNET_OK;
589         if ((res != GNUNET_SYSERR) && (res != GNUNET_NO))
590           send_error_to_client = GNUNET_NO;
591       }
592       if (send_error_to_client == GNUNET_NO)
593       {
594         response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
595         res = MHD_queue_response (session, MHD_HTTP_OK, response);
596         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Sent HTTP/1.1: 200 OK as PUT Response\n",HTTP_PUT_RESPONSE, strlen (HTTP_PUT_RESPONSE), res );
597         MHD_destroy_response (response);
598       }
599       else
600       {
601         response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
602         res = MHD_queue_response (session, MHD_HTTP_BAD_REQUEST, response);
603         MHD_destroy_response (response);
604         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Sent HTTP/1.1: 400 BAD REQUEST as PUT Response\n");
605       }
606       cs->is_put_in_progress = GNUNET_NO;
607       cs->is_bad_request = GNUNET_NO;
608       cs->pending_inbound_msg->pos = 0;
609       return res;
610     }
611   }
612   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
613   {
614     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request\n");
615     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"URL: `%s'\n",url);
616     response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
617     res = MHD_queue_response (session, MHD_HTTP_OK, response);
618     MHD_destroy_response (response);
619     return res;
620   }
621   return MHD_NO;
622 }
623
624
625 /**
626  * Call MHD to process pending ipv4 requests and then go back
627  * and schedule the next run.
628  */
629 static void http_daemon_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
630 /**
631  * Call MHD to process pending ipv6 requests and then go back
632  * and schedule the next run.
633  */
634 static void http_daemon_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
635
636 /**
637  * Function that queries MHD's select sets and
638  * starts the task waiting for them.
639  */
640 static GNUNET_SCHEDULER_TaskIdentifier
641 http_daemon_prepare (void * cls, struct MHD_Daemon *daemon_handle)
642 {
643   struct Plugin *plugin = cls;
644   GNUNET_SCHEDULER_TaskIdentifier ret;
645   fd_set rs;
646   fd_set ws;
647   fd_set es;
648   struct GNUNET_NETWORK_FDSet *wrs;
649   struct GNUNET_NETWORK_FDSet *wws;
650   struct GNUNET_NETWORK_FDSet *wes;
651   int max;
652   unsigned long long timeout;
653   int haveto;
654   struct GNUNET_TIME_Relative tv;
655
656   GNUNET_assert(cls !=NULL);
657   FD_ZERO(&rs);
658   FD_ZERO(&ws);
659   FD_ZERO(&es);
660   wrs = GNUNET_NETWORK_fdset_create ();
661   wes = GNUNET_NETWORK_fdset_create ();
662   wws = GNUNET_NETWORK_fdset_create ();
663   max = -1;
664   GNUNET_assert (MHD_YES ==
665                  MHD_get_fdset (daemon_handle,
666                                 &rs,
667                                 &ws,
668                                 &es,
669                                 &max));
670   haveto = MHD_get_timeout (daemon_handle, &timeout);
671   if (haveto == MHD_YES)
672     tv.value = (uint64_t) timeout;
673   else
674     tv = GNUNET_TIME_UNIT_FOREVER_REL;
675   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
676   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
677   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
678   if (daemon_handle == plugin->http_daemon_v4)
679   {
680     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
681                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
682                                        GNUNET_SCHEDULER_NO_TASK,
683                                        tv,
684                                        wrs,
685                                        wws,
686                                        &http_daemon_v4_run,
687                                        plugin);
688   }
689   if (daemon_handle == plugin->http_daemon_v6)
690   {
691     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
692                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
693                                        GNUNET_SCHEDULER_NO_TASK,
694                                        tv,
695                                        wrs,
696                                        wws,
697                                        &http_daemon_v6_run,
698                                        plugin);
699   }
700   GNUNET_NETWORK_fdset_destroy (wrs);
701   GNUNET_NETWORK_fdset_destroy (wws);
702   GNUNET_NETWORK_fdset_destroy (wes);
703   return ret;
704 }
705
706 /**
707  * Call MHD to process pending requests and then go back
708  * and schedule the next run.
709  */
710 static void http_daemon_v4_run (void *cls,
711                              const struct GNUNET_SCHEDULER_TaskContext *tc)
712 {
713   struct Plugin *plugin = cls;
714
715   GNUNET_assert(cls !=NULL);
716   if (plugin->http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
717     plugin->http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
718
719   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
720     return;
721
722   GNUNET_assert (MHD_YES == MHD_run (plugin->http_daemon_v4));
723   plugin->http_task_v4 = http_daemon_prepare (plugin, plugin->http_daemon_v4);
724   return;
725 }
726
727
728 /**
729  * Call MHD to process pending requests and then go back
730  * and schedule the next run.
731  */
732 static void http_daemon_v6_run (void *cls,
733                              const struct GNUNET_SCHEDULER_TaskContext *tc)
734 {
735   struct Plugin *plugin = cls;
736
737   GNUNET_assert(cls !=NULL);
738   if (plugin->http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
739     plugin->http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
740
741   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
742     return;
743
744   GNUNET_assert (MHD_YES == MHD_run (plugin->http_daemon_v6));
745   plugin->http_task_v6 = http_daemon_prepare (plugin, plugin->http_daemon_v6);
746   return;
747 }
748
749 /**
750  * Removes a message from the linked list of messages
751  * @param ses session to remove message from
752  * @param msg message to remove
753  * @return GNUNET_SYSERR if msg not found, GNUNET_OK on success
754  */
755
756 static int remove_http_message(struct Session * ses, struct HTTP_Message * msg)
757 {
758   GNUNET_free (msg->buf);
759   GNUNET_free (msg->dest_url);
760
761   GNUNET_CONTAINER_DLL_remove(ses->pending_outbound_msg_head,ses->pending_outbound_msg_tail,msg);
762   return GNUNET_OK;
763 }
764
765
766 static size_t header_function( void *ptr, size_t size, size_t nmemb, void *stream)
767 {
768   char * tmp;
769   size_t len = size * nmemb;
770
771   tmp = NULL;
772   if ((size * nmemb) < SIZE_MAX)
773     tmp = GNUNET_malloc (len+1);
774
775   if ((tmp != NULL) && (len > 0))
776   {
777     memcpy(tmp,ptr,len);
778     if (len>=2)
779     {
780       if (tmp[len-2] == 13)
781         tmp[len-2]= '\0';
782     }
783 #if DEBUG_CURL
784     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Header: `%s'\n",tmp);
785 #endif
786   }
787   if (NULL != tmp)
788     GNUNET_free (tmp);
789
790   return size * nmemb;
791 }
792
793 /**
794  * Callback method used with libcurl
795  * Method is called when libcurl needs to read data during sending
796  * @param stream pointer where to write data
797  * @param size size of an individual element
798  * @param nmemb count of elements that can be written to the buffer
799  * @param ptr source pointer, passed to the libcurl handle
800  * @return bytes written to stream
801  */
802 static size_t send_read_callback(void *stream, size_t size, size_t nmemb, void *ptr)
803 {
804   struct Session * ses = ptr;
805   struct HTTP_Message * msg = ses->pending_outbound_msg_tail;
806   size_t bytes_sent;
807   size_t len;
808
809   /* data to send */
810   if (( msg->pos < msg->len))
811   {
812     /* data fit in buffer */
813     if ((msg->len - msg->pos) <= (size * nmemb))
814     {
815       len = (msg->len - msg->pos);
816       memcpy(stream, &msg->buf[msg->pos], len);
817       msg->pos += len;
818       bytes_sent = len;
819     }
820     else
821     {
822       len = size*nmemb;
823       memcpy(stream, &msg->buf[msg->pos], len);
824       msg->pos += len;
825       bytes_sent = len;
826     }
827   }
828   /* no data to send */
829   else
830   {
831     bytes_sent = 0;
832   }
833   return bytes_sent;
834 }
835
836 /**
837 * Callback method used with libcurl
838 * Method is called when libcurl needs to write data during sending
839 * @param stream pointer where to write data
840 * @param size size of an individual element
841 * @param nmemb count of elements that can be written to the buffer
842 * @param ptr destination pointer, passed to the libcurl handle
843 * @return bytes read from stream
844 */
845 static size_t send_write_callback( void *stream, size_t size, size_t nmemb, void *ptr)
846 {
847   char * data = NULL;
848
849   if ((size * nmemb) < SIZE_MAX)
850     data = GNUNET_malloc(size*nmemb +1);
851   if (data != NULL)
852   {
853     memcpy( data, stream, size*nmemb);
854     data[size*nmemb] = '\0';
855     free (data);
856   }
857   return (size * nmemb);
858
859 }
860
861 /**
862  * Function setting up file descriptors and scheduling task to run
863  * @param ses session to send data to
864  * @return bytes sent to peer
865  */
866 static size_t send_prepare(void *cls, struct Session* ses );
867
868 /**
869  * Function setting up curl handle and selecting message to send
870  * @param ses session to send data to
871  * @return bytes sent to peer
872  */
873 static ssize_t send_select_init (void *cls, struct Session* ses )
874 {
875   struct Plugin *plugin = cls;
876   int bytes_sent = 0;
877   CURLMcode mret;
878   struct HTTP_Message * msg;
879
880   GNUNET_assert(cls !=NULL);
881   if ( NULL == ses->curl_handle)
882     ses->curl_handle = curl_easy_init();
883   if( NULL == ses->curl_handle)
884   {
885     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Getting cURL handle failed\n");
886     return -1;
887   }
888   GNUNET_assert (NULL != ses->pending_outbound_msg_tail);
889   msg = ses->pending_outbound_msg_tail;
890
891 #if DEBUG_CURL
892   curl_easy_setopt(ses->curl_handle, CURLOPT_VERBOSE, 1L);
893 #endif
894   curl_easy_setopt(ses->curl_handle, CURLOPT_URL, msg->dest_url);
895   curl_easy_setopt(ses->curl_handle, CURLOPT_PUT, 1L);
896   curl_easy_setopt(ses->curl_handle, CURLOPT_HEADERFUNCTION, &header_function);
897   curl_easy_setopt(ses->curl_handle, CURLOPT_WRITEHEADER, ses);
898   curl_easy_setopt(ses->curl_handle, CURLOPT_READFUNCTION, send_read_callback);
899   curl_easy_setopt(ses->curl_handle, CURLOPT_READDATA, ses);
900   curl_easy_setopt(ses->curl_handle, CURLOPT_WRITEFUNCTION, send_write_callback);
901   curl_easy_setopt(ses->curl_handle, CURLOPT_READDATA, ses);
902   curl_easy_setopt(ses->curl_handle, CURLOPT_INFILESIZE_LARGE, (curl_off_t) msg->len);
903   curl_easy_setopt(ses->curl_handle, CURLOPT_TIMEOUT, GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
904   GNUNET_assert (CURLE_OK == curl_easy_setopt(ses->curl_handle, CURLOPT_PRIVATE, ses));
905   curl_easy_setopt(ses->curl_handle, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
906   curl_easy_setopt(ses->curl_handle, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);
907
908   mret = curl_multi_add_handle(plugin->multi_handle, ses->curl_handle);
909   if (mret != CURLM_OK)
910   {
911     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
912                 _("%s failed at %s:%d: `%s'\n"),
913                 "curl_multi_add_handle", __FILE__, __LINE__,
914                 curl_multi_strerror (mret));
915     return -1;
916   }
917   bytes_sent = send_prepare (plugin, ses );
918   return bytes_sent;
919 }
920
921 static void send_execute (void *cls,
922              const struct GNUNET_SCHEDULER_TaskContext *tc)
923 {
924   struct Plugin *plugin = cls;
925   static unsigned int handles_last_run;
926   int running;
927   struct CURLMsg *msg;
928   CURLMcode mret;
929   struct Session * cs = NULL;
930   long http_result;
931
932   GNUNET_assert(cls !=NULL);
933   plugin->http_task_send = GNUNET_SCHEDULER_NO_TASK;
934   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
935     return;
936
937   do
938     {
939       running = 0;
940       mret = curl_multi_perform (plugin->multi_handle, &running);
941       if (running < handles_last_run)
942         {
943           do
944             {
945
946               msg = curl_multi_info_read (plugin->multi_handle, &running);
947               GNUNET_break (msg != NULL);
948               if (msg == NULL)
949                 break;
950               /* get session for affected curl handle */
951               GNUNET_assert ( msg->easy_handle != NULL );
952               curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &cs);
953               GNUNET_assert ( cs != NULL );
954               GNUNET_assert ( cs->pending_outbound_msg_tail != NULL );
955               switch (msg->msg)
956                 {
957
958                 case CURLMSG_DONE:
959                   if ( (msg->data.result != CURLE_OK) &&
960                        (msg->data.result != CURLE_GOT_NOTHING) )
961                   {
962                     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
963                                _("%s failed for `%s' at %s:%d: `%s'\n"),
964                                "curl_multi_perform",
965                                GNUNET_i2s(&cs->partner),
966                                __FILE__,
967                                __LINE__,
968                                curl_easy_strerror (msg->data.result));
969                     /* sending msg failed*/
970                     if (( NULL != cs->pending_outbound_msg_tail) && ( NULL != cs->pending_outbound_msg_tail->transmit_cont))
971                       cs->pending_outbound_msg_tail->transmit_cont (cs->pending_outbound_msg_tail->transmit_cont_cls,&cs->partner,GNUNET_SYSERR);
972                   }
973                   else
974                   {
975                     GNUNET_assert (CURLE_OK == curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_result));
976                     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
977                                 "Send to peer `%s' completed with code %u\n", GNUNET_i2s(&cs->partner), http_result );
978
979                     curl_easy_cleanup(cs->curl_handle);
980                     cs->curl_handle=NULL;
981
982                     /* Calling transmit continuation  */
983                     if (( NULL != cs->pending_outbound_msg_tail) && (NULL != cs->pending_outbound_msg_tail->transmit_cont))
984                     {
985                       /* HTTP 1xx : Last message before here was informational */
986                       if ((http_result >=100) && (http_result < 200))
987                         cs->pending_outbound_msg_tail->transmit_cont (cs->pending_outbound_msg_tail->transmit_cont_cls,&cs->partner,GNUNET_OK);
988                       /* HTTP 2xx: successful operations */
989                       if ((http_result >=200) && (http_result < 300))
990                         cs->pending_outbound_msg_tail->transmit_cont (cs->pending_outbound_msg_tail->transmit_cont_cls,&cs->partner,GNUNET_OK);
991                       /* HTTP 3xx..5xx: error */
992                       if ((http_result >=300) && (http_result < 600))
993                         cs->pending_outbound_msg_tail->transmit_cont (cs->pending_outbound_msg_tail->transmit_cont_cls,&cs->partner,GNUNET_SYSERR);
994                     }
995                   }
996
997                   if (GNUNET_OK != remove_http_message(cs, cs->pending_outbound_msg_tail))
998                     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message could not be removed from session `%s'", GNUNET_i2s(&cs->partner));
999                   /* send pending messages */
1000                   if (cs->pending_outbound_msg_tail!= NULL)
1001                   {
1002                     send_select_init (plugin, cs);
1003                   }
1004                   return;
1005                 default:
1006                   break;
1007                 }
1008
1009             }
1010           while ( (running > 0) );
1011         }
1012       handles_last_run = running;
1013     }
1014   while (mret == CURLM_CALL_MULTI_PERFORM);
1015   send_prepare(plugin, cls);
1016 }
1017
1018
1019 /**
1020  * Function setting up file descriptors and scheduling task to run
1021  * @param ses session to send data to
1022  * @return bytes sent to peer
1023  */
1024 static size_t send_prepare(void *cls, struct Session* ses )
1025 {
1026   struct Plugin *plugin = cls;
1027   fd_set rs;
1028   fd_set ws;
1029   fd_set es;
1030   int max;
1031   struct GNUNET_NETWORK_FDSet *grs;
1032   struct GNUNET_NETWORK_FDSet *gws;
1033   long to;
1034   CURLMcode mret;
1035
1036   GNUNET_assert(cls !=NULL);
1037   max = -1;
1038   FD_ZERO (&rs);
1039   FD_ZERO (&ws);
1040   FD_ZERO (&es);
1041   mret = curl_multi_fdset (plugin->multi_handle, &rs, &ws, &es, &max);
1042   if (mret != CURLM_OK)
1043     {
1044       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1045                   _("%s failed at %s:%d: `%s'\n"),
1046                   "curl_multi_fdset", __FILE__, __LINE__,
1047                   curl_multi_strerror (mret));
1048       return -1;
1049     }
1050   mret = curl_multi_timeout (plugin->multi_handle, &to);
1051   if (mret != CURLM_OK)
1052     {
1053       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1054                   _("%s failed at %s:%d: `%s'\n"),
1055                   "curl_multi_timeout", __FILE__, __LINE__,
1056                   curl_multi_strerror (mret));
1057       return -1;
1058     }
1059
1060   grs = GNUNET_NETWORK_fdset_create ();
1061   gws = GNUNET_NETWORK_fdset_create ();
1062   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1063   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1064   plugin->http_task_send = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1065                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1066                                    GNUNET_SCHEDULER_NO_TASK,
1067                                    GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 0),
1068                                    grs,
1069                                    gws,
1070                                    &send_execute,
1071                                    plugin);
1072   GNUNET_NETWORK_fdset_destroy (gws);
1073   GNUNET_NETWORK_fdset_destroy (grs);
1074
1075   /* FIXME: return bytes REALLY sent */
1076   return 0;
1077 }
1078
1079 /**
1080  * Function that can be used by the transport service to transmit
1081  * a message using the plugin.
1082  *
1083  * @param cls closure
1084  * @param target who should receive this message
1085  * @param priority how important is the message
1086  * @param msgbuf the message to transmit
1087  * @param msgbuf_size number of bytes in 'msgbuf'
1088  * @param to when should we time out
1089  * @param session which session must be used (or NULL for "any")
1090  * @param addr the address to use (can be NULL if the plugin
1091  *                is "on its own" (i.e. re-use existing TCP connection))
1092  * @param addrlen length of the address in bytes
1093  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1094  *                otherwise the plugin may use other addresses or
1095  *                existing connections (if available)
1096  * @param cont continuation to call once the message has
1097  *        been transmitted (or if the transport is ready
1098  *        for the next transmission call; or if the
1099  *        peer disconnected...)
1100  * @param cont_cls closure for cont
1101  * @return number of bytes used (on the physical network, with overheads);
1102  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1103  *         and does NOT mean that the message was not transmitted (DV)
1104  */
1105 static ssize_t
1106 http_plugin_send (void *cls,
1107                   const struct GNUNET_PeerIdentity *target,
1108                   const char *msgbuf,
1109                   size_t msgbuf_size,
1110                   unsigned int priority,
1111                   struct GNUNET_TIME_Relative to,
1112                   struct Session *session,
1113                   const void *addr,
1114                   size_t addrlen,
1115                   int force_address,
1116                   GNUNET_TRANSPORT_TransmitContinuation cont,
1117                   void *cont_cls)
1118 {
1119   struct Plugin *plugin = cls;
1120   char *address;
1121   char *url;
1122   struct Session *cs;
1123   struct HTTP_Message *msg;
1124   unsigned int res;
1125
1126   GNUNET_assert(cls !=NULL);
1127   url = NULL;
1128   address = NULL;
1129
1130   cs = GNUNET_CONTAINER_multihashmap_get (plugin->sessions, &target->hashPubKey);
1131   if ( cs == NULL)
1132   {
1133     cs = create_session(plugin, (char *) addr, addrlen, NULL, 0, target);
1134     cs->is_active = GNUNET_YES;
1135     res = GNUNET_CONTAINER_multihashmap_put ( plugin->sessions,
1136                                         &cs->partner.hashPubKey,
1137                                         cs,
1138                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1139     if (res == GNUNET_OK)
1140       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1141                   "New Session `%s' inserted\n", GNUNET_i2s(target));
1142   }
1143   if (cs != NULL)
1144     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1145                 "Session `%s' found\n", GNUNET_i2s(target));
1146
1147   GNUNET_assert ((addr!=NULL) && (addrlen != 0));
1148   if (addrlen == (sizeof (struct IPv4HttpAddress)))
1149   {
1150     address = GNUNET_malloc(INET_ADDRSTRLEN + 1);
1151     inet_ntop(AF_INET, &((struct IPv4HttpAddress *) addr)->ipv4_addr,address,INET_ADDRSTRLEN);
1152     GNUNET_asprintf (&url,
1153                      "http://%s:%u/%s",
1154                      address,
1155                      ntohs(((struct IPv4HttpAddress *) addr)->u_port),
1156                      (char *) (&plugin->my_ascii_hash_ident));
1157     GNUNET_free(address);
1158   }
1159   else if (addrlen == (sizeof (struct IPv6HttpAddress)))
1160   {
1161     address = GNUNET_malloc(INET6_ADDRSTRLEN + 1);
1162     inet_ntop(AF_INET6, &((struct IPv6HttpAddress *) addr)->ipv6_addr,address,INET6_ADDRSTRLEN);
1163     GNUNET_asprintf(&url,
1164                     "http://%s:%u/%s",
1165                     address,
1166                     ntohs(((struct IPv6HttpAddress *) addr)->u6_port),
1167                     (char *) (&plugin->my_ascii_hash_ident));
1168     GNUNET_free(address);
1169   }
1170
1171   /* setting up message */
1172   msg = GNUNET_malloc (sizeof (struct HTTP_Message));
1173   msg->next = NULL;
1174   msg->len = msgbuf_size;
1175   msg->pos = 0;
1176   msg->buf = GNUNET_malloc (msgbuf_size);
1177   msg->dest_url = url;
1178   msg->transmit_cont = cont;
1179   msg->transmit_cont_cls = cont_cls;
1180   memcpy (msg->buf,msgbuf, msgbuf_size);
1181   /* insert created message in double linked list of pending messages */
1182   GNUNET_CONTAINER_DLL_insert (cs->pending_outbound_msg_head, cs->pending_outbound_msg_tail, msg);
1183
1184   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: sending %u bytes of data from peer `%4.4s' to peer `%s'\n",msgbuf_size,(char *) &plugin->my_ascii_hash_ident,GNUNET_i2s(target));
1185   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: url `%s'\n",url);
1186   if (msg == cs->pending_outbound_msg_tail)
1187   {
1188     return send_select_init (plugin, cs);
1189   }
1190   return msgbuf_size;
1191 }
1192
1193
1194
1195 /**
1196  * Function that can be used to force the plugin to disconnect
1197  * from the given peer and cancel all previous transmissions
1198  * (and their continuationc).
1199  *
1200  * @param cls closure
1201  * @param target peer from which to disconnect
1202  */
1203 static void
1204 http_plugin_disconnect (void *cls,
1205                             const struct GNUNET_PeerIdentity *target)
1206 {
1207   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_disconnect\n");
1208   // struct Plugin *plugin = cls;
1209   // FIXME
1210 }
1211
1212
1213 /**
1214  * Convert the transports address to a nice, human-readable
1215  * format.
1216  *
1217  * @param cls closure
1218  * @param type name of the transport that generated the address
1219  * @param addr one of the addresses of the host, NULL for the last address
1220  *        the specific address format depends on the transport
1221  * @param addrlen length of the address
1222  * @param numeric should (IP) addresses be displayed in numeric form?
1223  * @param timeout after how long should we give up?
1224  * @param asc function to call on each string
1225  * @param asc_cls closure for asc
1226  */
1227 static void
1228 http_plugin_address_pretty_printer (void *cls,
1229                                         const char *type,
1230                                         const void *addr,
1231                                         size_t addrlen,
1232                                         int numeric,
1233                                         struct GNUNET_TIME_Relative timeout,
1234                                         GNUNET_TRANSPORT_AddressStringCallback
1235                                         asc, void *asc_cls)
1236 {
1237   const struct IPv4HttpAddress *t4;
1238   const struct IPv6HttpAddress *t6;
1239   struct sockaddr_in a4;
1240   struct sockaddr_in6 a6;
1241   char * address;
1242   char * ret;
1243   unsigned int port;
1244   unsigned int res;
1245
1246   GNUNET_assert(cls !=NULL);
1247   if (addrlen == sizeof (struct IPv6HttpAddress))
1248   {
1249     address = GNUNET_malloc (INET6_ADDRSTRLEN);
1250     t6 = addr;
1251     a6.sin6_addr = t6->ipv6_addr;
1252     inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
1253     port = ntohs(t6->u6_port);
1254   }
1255   else if (addrlen == sizeof (struct IPv4HttpAddress))
1256   {
1257     address = GNUNET_malloc (INET_ADDRSTRLEN);
1258     t4 = addr;
1259     a4.sin_addr.s_addr =  t4->ipv4_addr;
1260     inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
1261     port = ntohs(t4->u_port);
1262   }
1263   else
1264   {
1265     /* invalid address */
1266     GNUNET_break_op (0);
1267     asc (asc_cls, NULL);
1268     return;
1269   }
1270   res = GNUNET_asprintf(&ret,"http://%s:%u/",address,port);
1271   GNUNET_free (address);
1272   GNUNET_assert(res != 0);
1273
1274   asc (asc_cls, ret);
1275 }
1276
1277
1278
1279 /**
1280  * Another peer has suggested an address for this
1281  * peer and transport plugin.  Check that this could be a valid
1282  * address.  If so, consider adding it to the list
1283  * of addresses.
1284  *
1285  * @param cls closure
1286  * @param addr pointer to the address
1287  * @param addrlen length of addr
1288  * @return GNUNET_OK if this is a plausible address for this peer
1289  *         and transport
1290  */
1291 static int
1292 http_plugin_address_suggested (void *cls,
1293                                   void *addr, size_t addrlen)
1294 {
1295   struct Plugin *plugin = cls;
1296   struct IPv4HttpAddress *v4;
1297   struct IPv6HttpAddress *v6;
1298   unsigned int port;
1299
1300   GNUNET_assert(cls !=NULL);
1301   if ((addrlen != sizeof (struct IPv4HttpAddress)) &&
1302       (addrlen != sizeof (struct IPv6HttpAddress)))
1303     {
1304       return GNUNET_SYSERR;
1305     }
1306   if (addrlen == sizeof (struct IPv4HttpAddress))
1307     {
1308       v4 = (struct IPv4HttpAddress *) addr;
1309       if (INADDR_LOOPBACK == ntohl(v4->ipv4_addr))
1310       {
1311         return GNUNET_SYSERR;
1312       }
1313       port = ntohs (v4->u_port);
1314       if (port != plugin->port_inbound)
1315       {
1316         return GNUNET_SYSERR;
1317       }
1318     }
1319   else
1320     {
1321       v6 = (struct IPv6HttpAddress *) addr;
1322       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1323         {
1324           return GNUNET_SYSERR;
1325         }
1326       port = ntohs (v6->u6_port);
1327       if (port != plugin->port_inbound)
1328       {
1329         return GNUNET_SYSERR;
1330       }
1331     }
1332
1333
1334   return GNUNET_OK;
1335 }
1336
1337
1338 /**
1339  * Function called for a quick conversion of the binary address to
1340  * a numeric address.  Note that the caller must not free the
1341  * address and that the next call to this function is allowed
1342  * to override the address again.
1343  *
1344  * @param cls closure
1345  * @param addr binary address
1346  * @param addrlen length of the address
1347  * @return string representing the same address
1348  */
1349 static const char*
1350 http_plugin_address_to_string (void *cls,
1351                                    const void *addr,
1352                                    size_t addrlen)
1353 {
1354   const struct IPv4HttpAddress *t4;
1355   const struct IPv6HttpAddress *t6;
1356   struct sockaddr_in a4;
1357   struct sockaddr_in6 a6;
1358   char * address;
1359   char * ret;
1360   unsigned int port;
1361   unsigned int res;
1362
1363   GNUNET_assert(cls !=NULL);
1364   if (addrlen == sizeof (struct IPv6HttpAddress))
1365     {
1366       address = GNUNET_malloc (INET6_ADDRSTRLEN);
1367       t6 = addr;
1368       a6.sin6_addr = t6->ipv6_addr;
1369       inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
1370       port = ntohs(t6->u6_port);
1371     }
1372   else if (addrlen == sizeof (struct IPv4HttpAddress))
1373     {
1374       address = GNUNET_malloc (INET_ADDRSTRLEN);
1375       t4 = addr;
1376       a4.sin_addr.s_addr =  t4->ipv4_addr;
1377       inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
1378       port = ntohs(t4->u_port);
1379     }
1380   else
1381     {
1382       /* invalid address */
1383       return NULL;
1384     }
1385   res = GNUNET_asprintf(&ret,"%s:%u",address,port);
1386   GNUNET_free (address);
1387   GNUNET_assert(res != 0);
1388   return ret;
1389 }
1390
1391 /**
1392  * Add the IP of our network interface to the list of
1393  * our external IP addresses.
1394  *
1395  * @param cls the 'struct Plugin*'
1396  * @param name name of the interface
1397  * @param isDefault do we think this may be our default interface
1398  * @param addr address of the interface
1399  * @param addrlen number of bytes in addr
1400  * @return GNUNET_OK to continue iterating
1401  */
1402 static int
1403 process_interfaces (void *cls,
1404                     const char *name,
1405                     int isDefault,
1406                     const struct sockaddr *addr, socklen_t addrlen)
1407 {
1408   struct Plugin *plugin = cls;
1409   struct IPv4HttpAddress t4;
1410   struct IPv6HttpAddress t6;
1411   int af;
1412   void *arg;
1413   uint16_t args;
1414
1415   GNUNET_assert(cls !=NULL);
1416   af = addr->sa_family;
1417   if (af == AF_INET)
1418     {
1419       if (INADDR_LOOPBACK == ntohl(((struct sockaddr_in *) addr)->sin_addr.s_addr))
1420       {
1421         /* skip loopback addresses */
1422         return GNUNET_OK;
1423       }
1424       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1425       t4.u_port = htons (plugin->port_inbound);
1426       arg = &t4;
1427       args = sizeof (t4);
1428     }
1429   else if (af == AF_INET6)
1430     {
1431       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1432         {
1433           /* skip link local addresses */
1434           return GNUNET_OK;
1435         }
1436       if (IN6_IS_ADDR_LOOPBACK (&((struct sockaddr_in6 *) addr)->sin6_addr))
1437         {
1438           /* skip loopback addresses */
1439           return GNUNET_OK;
1440         }
1441       memcpy (&t6.ipv6_addr,
1442               &((struct sockaddr_in6 *) addr)->sin6_addr,
1443               sizeof (struct in6_addr));
1444       t6.u6_port = htons (plugin->port_inbound);
1445       arg = &t6;
1446       args = sizeof (t6);
1447     }
1448   else
1449     {
1450       GNUNET_break (0);
1451       return GNUNET_OK;
1452     }
1453   plugin->env->notify_address(plugin->env->cls,"http",arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1454   return GNUNET_OK;
1455 }
1456
1457 int hashMapFreeIterator (void *cls, const GNUNET_HashCode *key, void *value)
1458 {
1459   struct Session * cs = value;
1460
1461   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing session for peer `%s'\n",GNUNET_i2s(&cs->partner));
1462
1463   /* freeing messages */
1464   struct HTTP_Message *cur;
1465   struct HTTP_Message *tmp;
1466   cur = cs->pending_outbound_msg_head;
1467
1468   while (cur != NULL)
1469   {
1470     tmp = cur->next;
1471     GNUNET_free_non_null(cur->dest_url);
1472     GNUNET_free_non_null (cur->buf);
1473     GNUNET_free (cur);
1474     cur = tmp;
1475   }
1476   GNUNET_SERVER_mst_destroy (cs->msgtok);
1477   GNUNET_free (cs->pending_inbound_msg->buf);
1478   GNUNET_free (cs->pending_inbound_msg);
1479   GNUNET_free_non_null (cs->addr_in);
1480   GNUNET_free_non_null (cs->addr_out);
1481   GNUNET_free (cs);
1482
1483   return GNUNET_YES;
1484 }
1485
1486 /**
1487  * Exit point from the plugin.
1488  */
1489 void *
1490 libgnunet_plugin_transport_http_done (void *cls)
1491 {
1492   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1493   struct Plugin *plugin = api->cls;
1494   CURLMcode mret;
1495
1496   GNUNET_assert(cls !=NULL);
1497   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unloading http plugin...\n");
1498
1499   if ( plugin->http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1500   {
1501     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_task_v4);
1502     plugin->http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
1503   }
1504
1505   if ( plugin->http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1506   {
1507     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_task_v6);
1508     plugin->http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1509   }
1510
1511   if ( plugin->http_task_send != GNUNET_SCHEDULER_NO_TASK)
1512   {
1513     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_task_send);
1514     plugin->http_task_send = GNUNET_SCHEDULER_NO_TASK;
1515   }
1516
1517   if (plugin->http_daemon_v4 != NULL)
1518   {
1519     MHD_stop_daemon (plugin->http_daemon_v4);
1520     plugin->http_daemon_v4 = NULL;
1521   }
1522   if (plugin->http_daemon_v6 != NULL)
1523   {
1524     MHD_stop_daemon (plugin->http_daemon_v6);
1525     plugin->http_daemon_v6 = NULL;
1526   }
1527
1528   /* free all sessions */
1529   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions,
1530                                          &hashMapFreeIterator,
1531                                          NULL);
1532
1533   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
1534
1535   mret = curl_multi_cleanup(plugin->multi_handle);
1536   if ( CURLM_OK != mret)
1537     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed");
1538
1539   GNUNET_free (plugin);
1540   GNUNET_free (api);
1541   return NULL;
1542 }
1543
1544
1545 /**
1546  * Entry point for the plugin.
1547  */
1548 void *
1549 libgnunet_plugin_transport_http_init (void *cls)
1550 {
1551   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1552   struct Plugin *plugin;
1553   struct GNUNET_TRANSPORT_PluginFunctions *api;
1554   struct GNUNET_TIME_Relative gn_timeout;
1555   long long unsigned int port;
1556
1557   GNUNET_assert(cls !=NULL);
1558   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
1559
1560   plugin = GNUNET_malloc (sizeof (struct Plugin));
1561   plugin->env = env;
1562   plugin->sessions = NULL;
1563   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1564   api->cls = plugin;
1565   api->send = &http_plugin_send;
1566   api->disconnect = &http_plugin_disconnect;
1567   api->address_pretty_printer = &http_plugin_address_pretty_printer;
1568   api->check_address = &http_plugin_address_suggested;
1569   api->address_to_string = &http_plugin_address_to_string;
1570
1571   /* Hashing our identity to use it in URLs */
1572   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &plugin->my_ascii_hash_ident);
1573
1574   /* Reading port number from config file */
1575   if ((GNUNET_OK !=
1576        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1577                                               "transport-http",
1578                                               "PORT",
1579                                               &port)) ||
1580       (port > 65535) )
1581     {
1582       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1583                        "http",
1584                        _
1585                        ("Require valid port number for transport plugin `%s' in configuration!\n"),
1586                        "transport-http");
1587       libgnunet_plugin_transport_http_done (api);
1588       return NULL;
1589     }
1590   GNUNET_assert ((port > 0) && (port <= 65535));
1591   plugin->port_inbound = port;
1592   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1593   if ((plugin->http_daemon_v4 == NULL) && (plugin->http_daemon_v6 == NULL) && (port != 0))
1594     {
1595     plugin->http_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
1596                                        port,
1597                                        &acceptPolicyCallback,
1598                                        plugin , &accessHandlerCallback, plugin,
1599                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1600                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1601                                        MHD_OPTION_CONNECTION_TIMEOUT, (gn_timeout.value / 1000),
1602                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1603                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1604                                        MHD_OPTION_END);
1605     plugin->http_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
1606                                        port,
1607                                        &acceptPolicyCallback,
1608                                        plugin , &accessHandlerCallback, plugin,
1609                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1610                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1611                                        MHD_OPTION_CONNECTION_TIMEOUT, (gn_timeout.value / 1000),
1612                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1613                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1614                                        MHD_OPTION_END);
1615     }
1616   if (plugin->http_daemon_v4 != NULL)
1617     plugin->http_task_v4 = http_daemon_prepare (plugin, plugin->http_daemon_v4);
1618   if (plugin->http_daemon_v6 != NULL)
1619     plugin->http_task_v6 = http_daemon_prepare (plugin, plugin->http_daemon_v6);
1620
1621   if (plugin->http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1622     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
1623   else if (plugin->http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1624     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
1625   else
1626   {
1627     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No MHD was started, transport plugin not functional!\n");
1628     libgnunet_plugin_transport_http_done (api);
1629     return NULL;
1630   }
1631
1632   /* Initializing cURL */
1633   plugin->multi_handle = curl_multi_init();
1634   if ( NULL == plugin->multi_handle )
1635   {
1636     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1637                      "http",
1638                      _("Could not initialize curl multi handle, failed to start http plugin!\n"),
1639                      "transport-http");
1640     libgnunet_plugin_transport_http_done (api);
1641     return NULL;
1642   }
1643
1644   plugin->sessions = GNUNET_CONTAINER_multihashmap_create (10);
1645   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1646
1647   return api;
1648 }
1649
1650 /* end of plugin_transport_http.c */