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