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