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