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