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