(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         return MHD_YES;
609       }
610       else
611       {
612         response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
613         res = MHD_queue_response (session, MHD_HTTP_BAD_REQUEST, response);
614         MHD_destroy_response (response);
615         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Sent HTTP/1.1: 400 BAD REQUEST as PUT Response\n");
616       }
617       cs->is_put_in_progress = GNUNET_NO;
618       cs->is_bad_request = GNUNET_NO;
619       cs->pending_inbound_msg.bytes_recv = 0;
620       return res;
621     }
622   }
623   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
624   {
625     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request\n");
626     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"URL: `%s'\n",url);
627     response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
628     res = MHD_queue_response (session, MHD_HTTP_OK, response);
629     MHD_destroy_response (response);
630     return res;
631   }
632   return MHD_NO;
633 }
634
635
636 /**
637  * Call MHD to process pending ipv4 requests and then go back
638  * and schedule the next run.
639  */
640 static void http_server_daemon_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
641 /**
642  * Call MHD to process pending ipv6 requests and then go back
643  * and schedule the next run.
644  */
645 static void http_server_daemon_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
646
647 /**
648  * Function that queries MHD's select sets and
649  * starts the task waiting for them.
650  */
651 static GNUNET_SCHEDULER_TaskIdentifier
652 http_server_daemon_prepare (void * cls, struct MHD_Daemon *daemon_handle)
653 {
654   struct Plugin *plugin = cls;
655   GNUNET_SCHEDULER_TaskIdentifier ret;
656   fd_set rs;
657   fd_set ws;
658   fd_set es;
659   struct GNUNET_NETWORK_FDSet *wrs;
660   struct GNUNET_NETWORK_FDSet *wws;
661   struct GNUNET_NETWORK_FDSet *wes;
662   int max;
663   unsigned long long timeout;
664   int haveto;
665   struct GNUNET_TIME_Relative tv;
666
667   GNUNET_assert(cls !=NULL);
668   ret = GNUNET_SCHEDULER_NO_TASK;
669   FD_ZERO(&rs);
670   FD_ZERO(&ws);
671   FD_ZERO(&es);
672   wrs = GNUNET_NETWORK_fdset_create ();
673   wes = GNUNET_NETWORK_fdset_create ();
674   wws = GNUNET_NETWORK_fdset_create ();
675   max = -1;
676   GNUNET_assert (MHD_YES ==
677                  MHD_get_fdset (daemon_handle,
678                                 &rs,
679                                 &ws,
680                                 &es,
681                                 &max));
682   haveto = MHD_get_timeout (daemon_handle, &timeout);
683   if (haveto == MHD_YES)
684     tv.value = (uint64_t) timeout;
685   else
686     tv = GNUNET_TIME_UNIT_FOREVER_REL;
687   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
688   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
689   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
690   if (daemon_handle == plugin->http_server_daemon_v4)
691   {
692     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
693                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
694                                        GNUNET_SCHEDULER_NO_TASK,
695                                        tv,
696                                        wrs,
697                                        wws,
698                                        &http_server_daemon_v4_run,
699                                        plugin);
700   }
701   if (daemon_handle == plugin->http_server_daemon_v6)
702   {
703     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
704                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
705                                        GNUNET_SCHEDULER_NO_TASK,
706                                        tv,
707                                        wrs,
708                                        wws,
709                                        &http_server_daemon_v6_run,
710                                        plugin);
711   }
712   GNUNET_NETWORK_fdset_destroy (wrs);
713   GNUNET_NETWORK_fdset_destroy (wws);
714   GNUNET_NETWORK_fdset_destroy (wes);
715   return ret;
716 }
717
718 /**
719  * Call MHD to process pending requests and then go back
720  * and schedule the next run.
721  */
722 static void http_server_daemon_v4_run (void *cls,
723                              const struct GNUNET_SCHEDULER_TaskContext *tc)
724 {
725   struct Plugin *plugin = cls;
726
727   GNUNET_assert(cls !=NULL);
728   if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
729     plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
730
731   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
732     return;
733
734   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v4));
735   plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
736   return;
737 }
738
739
740 /**
741  * Call MHD to process pending requests and then go back
742  * and schedule the next run.
743  */
744 static void http_server_daemon_v6_run (void *cls,
745                              const struct GNUNET_SCHEDULER_TaskContext *tc)
746 {
747   struct Plugin *plugin = cls;
748
749   GNUNET_assert(cls !=NULL);
750   if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
751     plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
752
753   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
754     return;
755
756   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v6));
757   plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
758   return;
759 }
760
761 /**
762  * Removes a message from the linked list of messages
763  * @param ses session to remove message from
764  * @param msg message to remove
765  * @return GNUNET_SYSERR if msg not found, GNUNET_OK on success
766  */
767
768 static int remove_http_message(struct HTTP_Connection * con, struct HTTP_Message * msg)
769 {
770   GNUNET_CONTAINER_DLL_remove(con->pending_msgs_head,con->pending_msgs_tail,msg);
771   GNUNET_free(msg);
772   return GNUNET_OK;
773 }
774
775
776 static size_t header_function( void *ptr, size_t size, size_t nmemb, void *stream)
777 {
778   char * tmp;
779   size_t len = size * nmemb;
780
781   tmp = NULL;
782   if ((size * nmemb) < SIZE_MAX)
783     tmp = GNUNET_malloc (len+1);
784
785   if ((tmp != NULL) && (len > 0))
786   {
787     memcpy(tmp,ptr,len);
788     if (len>=2)
789     {
790       if (tmp[len-2] == 13)
791         tmp[len-2]= '\0';
792     }
793 #if DEBUG_HTTP
794     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Header: `%s'\n",tmp);
795 #endif
796   }
797   if (NULL != tmp)
798     GNUNET_free (tmp);
799
800   return size * nmemb;
801 }
802
803 /**
804  * Callback method used with libcurl
805  * Method is called when libcurl needs to read data during sending
806  * @param stream pointer where to write data
807  * @param size size of an individual element
808  * @param nmemb count of elements that can be written to the buffer
809  * @param ptr source pointer, passed to the libcurl handle
810  * @return bytes written to stream
811  */
812 static size_t send_read_callback(void *stream, size_t size, size_t nmemb, void *ptr)
813 {
814   struct HTTP_Connection * con = ptr;
815   struct HTTP_Message * msg = con->pending_msgs_tail;
816   size_t bytes_sent;
817   size_t len;
818
819   msg = con->pending_msgs_head;
820   unsigned int c = 0;
821   while (msg != NULL)
822   {
823     c++;
824     msg = msg->next;
825   }
826   if (con->pending_msgs_tail != NULL)
827     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"readcallback: msg of %u bytes, %u msgs in queue\n", con->pending_msgs_tail->size,c);
828   else
829     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"readcallback: %u msgs in queue\n", c);
830
831   if (con->pending_msgs_tail == NULL)
832   {
833     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"no msgs in queue, pausing \n");
834     return CURL_READFUNC_PAUSE;
835   }
836
837   msg = con->pending_msgs_tail;
838   /* data to send */
839   if (msg->pos < msg->size)
840   {
841     /* data fit in buffer */
842     if ((msg->size - msg->pos) <= (size * nmemb))
843     {
844       len = (msg->size - msg->pos);
845       memcpy(stream, &msg->buf[msg->pos], len);
846       msg->pos += len;
847       bytes_sent = len;
848     }
849     else
850     {
851       len = size*nmemb;
852       memcpy(stream, &msg->buf[msg->pos], len);
853       msg->pos += len;
854       bytes_sent = len;
855     }
856   }
857   /* no data to send */
858   else
859   {
860     bytes_sent = 0;
861   }
862
863   if ( msg->pos == msg->size)
864   {
865     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"msg sent, removing msg \n", bytes_sent);
866     remove_http_message(con, msg);
867
868   }
869   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"readcallback: sent %u bytes \n", bytes_sent);
870
871   return bytes_sent;
872 }
873
874 /**
875 * Callback method used with libcurl
876 * Method is called when libcurl needs to write data during sending
877 * @param stream pointer where to write data
878 * @param size size of an individual element
879 * @param nmemb count of elements that can be written to the buffer
880 * @param ptr destination pointer, passed to the libcurl handle
881 * @return bytes read from stream
882 */
883 static size_t send_write_callback( void *stream, size_t size, size_t nmemb, void *ptr)
884 {
885   char * data = NULL;
886
887   if ((size * nmemb) < SIZE_MAX)
888     data = GNUNET_malloc(size*nmemb +1);
889   if (data != NULL)
890   {
891     memcpy( data, stream, size*nmemb);
892     data[size*nmemb] = '\0';
893     free (data);
894   }
895   return (size * nmemb);
896
897 }
898
899 /**
900  * Function setting up file descriptors and scheduling task to run
901  * @param ses session to send data to
902  * @return bytes sent to peer
903  */
904 static size_t send_prepare(void *cls, struct Session* ses );
905
906 /**
907  * Function setting up curl handle and selecting message to send
908  * @param ses session to send data to
909  * @return bytes sent to peer
910  */
911 static ssize_t send_select_init (void *cls, struct Session* ses , struct HTTP_Connection *con)
912 {
913   struct Plugin *plugin = cls;
914   int bytes_sent = 0;
915   CURLMcode mret;
916   struct HTTP_Message * msg;
917
918   /* already connected, no need to initiate connection */
919   if ((con->connected == GNUNET_YES) && (con->curl_handle != NULL))
920     return bytes_sent;
921
922   /* not connected, initiate connection */
923   GNUNET_assert(cls !=NULL);
924   if ( NULL == con->curl_handle)
925     con->curl_handle = curl_easy_init();
926   GNUNET_assert (con->curl_handle != NULL);
927
928   GNUNET_assert (NULL != con->pending_msgs_tail);
929   msg = con->pending_msgs_tail;
930
931 #if DEBUG_CURL
932   curl_easy_setopt(con->curl_handle, CURLOPT_VERBOSE, 1L);
933 #endif
934   curl_easy_setopt(con->curl_handle, CURLOPT_URL, con->url);
935   curl_easy_setopt(con->curl_handle, CURLOPT_PUT, 1L);
936   curl_easy_setopt(con->curl_handle, CURLOPT_HEADERFUNCTION, &header_function);
937   curl_easy_setopt(con->curl_handle, CURLOPT_WRITEHEADER, con);
938   curl_easy_setopt(con->curl_handle, CURLOPT_READFUNCTION, send_read_callback);
939   curl_easy_setopt(con->curl_handle, CURLOPT_READDATA, con);
940   curl_easy_setopt(con->curl_handle, CURLOPT_WRITEFUNCTION, send_write_callback);
941   curl_easy_setopt(con->curl_handle, CURLOPT_READDATA, con);
942   curl_easy_setopt(con->curl_handle, CURLOPT_INFILESIZE_LARGE, (curl_off_t) msg->size);
943   curl_easy_setopt(con->curl_handle, CURLOPT_TIMEOUT, GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
944   curl_easy_setopt(con->curl_handle, CURLOPT_PRIVATE, con);
945   curl_easy_setopt(con->curl_handle, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT_DBG);
946   curl_easy_setopt(con->curl_handle, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);
947
948   mret = curl_multi_add_handle(plugin->multi_handle, con->curl_handle);
949   if (mret != CURLM_OK)
950   {
951     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
952                 _("%s failed at %s:%d: `%s'\n"),
953                 "curl_multi_add_handle", __FILE__, __LINE__,
954                 curl_multi_strerror (mret));
955     return -1;
956   }
957
958   con->connected = GNUNET_YES;
959
960   bytes_sent = send_prepare (plugin, ses);
961   return bytes_sent;
962 }
963
964 static void send_execute (void *cls,
965              const struct GNUNET_SCHEDULER_TaskContext *tc)
966 {
967   struct Plugin *plugin = cls;
968   static unsigned int handles_last_run;
969   int running;
970   struct CURLMsg *msg;
971   CURLMcode mret;
972   struct HTTP_Connection * con = NULL;
973   struct Session * cs = NULL;
974   long http_result;
975
976   GNUNET_assert(cls !=NULL);
977   plugin->http_server_task_send = GNUNET_SCHEDULER_NO_TASK;
978   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
979     return;
980
981   do
982     {
983       running = 0;
984       mret = curl_multi_perform (plugin->multi_handle, &running);
985       if (running < handles_last_run)
986         {
987           do
988             {
989
990               msg = curl_multi_info_read (plugin->multi_handle, &running);
991               GNUNET_break (msg != NULL);
992               if (msg == NULL)
993                 break;
994               /* get session for affected curl handle */
995               GNUNET_assert ( msg->easy_handle != NULL );
996               curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &con);
997               GNUNET_assert ( con != NULL );
998               cs = con->session;
999               GNUNET_assert ( cs != NULL );
1000               //GNUNET_assert ( cs->pending_outbound_msg_tail != NULL );
1001               switch (msg->msg)
1002                 {
1003
1004                 case CURLMSG_DONE:
1005                   if ( (msg->data.result != CURLE_OK) &&
1006                        (msg->data.result != CURLE_GOT_NOTHING) )
1007                   {
1008                     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1009                                _("%s failed for `%s' at %s:%d: `%s'\n"),
1010                                "curl_multi_perform",
1011                                GNUNET_i2s(&cs->identity),
1012                                __FILE__,
1013                                __LINE__,
1014                                curl_easy_strerror (msg->data.result));
1015                     /* sending msg failed*/
1016                     con->connected = GNUNET_NO;
1017                     if (( NULL != con->pending_msgs_tail) && ( NULL != con->pending_msgs_tail->transmit_cont))
1018                       con->pending_msgs_tail->transmit_cont (con->pending_msgs_tail->transmit_cont_cls,&con->session->identity,GNUNET_SYSERR);
1019
1020                   }
1021                   else
1022                   {
1023                     GNUNET_assert (CURLE_OK == curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_result));
1024                     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1025                                 "Send to peer `%s' completed with code %u\n", GNUNET_i2s(&cs->identity), http_result );
1026
1027                     curl_easy_cleanup(con->curl_handle);
1028                     con->connected = GNUNET_NO;
1029                     con->curl_handle=NULL;
1030
1031                     /* Calling transmit continuation  */
1032                     if (( NULL != con->pending_msgs_tail) && (NULL != con->pending_msgs_tail->transmit_cont))
1033                     {
1034                       /* HTTP 1xx : Last message before here was informational */
1035                       if ((http_result >=100) && (http_result < 200))
1036                         con->pending_msgs_tail->transmit_cont (con->pending_msgs_tail->transmit_cont_cls,&cs->identity,GNUNET_OK);
1037                       /* HTTP 2xx: successful operations */
1038                       if ((http_result >=200) && (http_result < 300))
1039                         con->pending_msgs_tail->transmit_cont (con->pending_msgs_tail->transmit_cont_cls,&cs->identity,GNUNET_OK);
1040                       /* HTTP 3xx..5xx: error */
1041                       if ((http_result >=300) && (http_result < 600))
1042                         con->pending_msgs_tail->transmit_cont (con->pending_msgs_tail->transmit_cont_cls,&cs->identity,GNUNET_SYSERR);
1043                     }
1044                   }
1045
1046                   if (GNUNET_OK != remove_http_message(con, con->pending_msgs_tail))
1047                     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message could not be removed from session `%s'", GNUNET_i2s(&cs->identity));
1048                   /* send pending messages */
1049                   if (con->pending_msgs_tail!= NULL)
1050                   {
1051                     send_select_init (plugin, cs, con);
1052                   }
1053                   return;
1054                 default:
1055                   break;
1056                 }
1057
1058             }
1059           while ( (running > 0) );
1060         }
1061       handles_last_run = running;
1062     }
1063   while (mret == CURLM_CALL_MULTI_PERFORM);
1064   send_prepare(plugin, cls);
1065 }
1066
1067
1068 /**
1069  * Function setting up file descriptors and scheduling task to run
1070  * @param ses session to send data to
1071  * @return bytes sent to peer
1072  */
1073 static size_t send_prepare(void *cls, struct Session* ses )
1074 {
1075   struct Plugin *plugin = cls;
1076   fd_set rs;
1077   fd_set ws;
1078   fd_set es;
1079   int max;
1080   struct GNUNET_NETWORK_FDSet *grs;
1081   struct GNUNET_NETWORK_FDSet *gws;
1082   long to;
1083   CURLMcode mret;
1084
1085   GNUNET_assert(cls !=NULL);
1086   max = -1;
1087   FD_ZERO (&rs);
1088   FD_ZERO (&ws);
1089   FD_ZERO (&es);
1090   mret = curl_multi_fdset (plugin->multi_handle, &rs, &ws, &es, &max);
1091   if (mret != CURLM_OK)
1092     {
1093       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1094                   _("%s failed at %s:%d: `%s'\n"),
1095                   "curl_multi_fdset", __FILE__, __LINE__,
1096                   curl_multi_strerror (mret));
1097       return -1;
1098     }
1099   mret = curl_multi_timeout (plugin->multi_handle, &to);
1100   if (mret != CURLM_OK)
1101     {
1102       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1103                   _("%s failed at %s:%d: `%s'\n"),
1104                   "curl_multi_timeout", __FILE__, __LINE__,
1105                   curl_multi_strerror (mret));
1106       return -1;
1107     }
1108
1109   grs = GNUNET_NETWORK_fdset_create ();
1110   gws = GNUNET_NETWORK_fdset_create ();
1111   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1112   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1113   plugin->http_server_task_send = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1114                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1115                                    GNUNET_SCHEDULER_NO_TASK,
1116                                    GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 0),
1117                                    grs,
1118                                    gws,
1119                                    &send_execute,
1120                                    plugin);
1121   GNUNET_NETWORK_fdset_destroy (gws);
1122   GNUNET_NETWORK_fdset_destroy (grs);
1123
1124   /* FIXME: return bytes REALLY sent */
1125   return 0;
1126 }
1127
1128 /**
1129  * Check if session for this peer is already existing, otherwise create it
1130  * @param cls the plugin used
1131  * @param p peer to get session for
1132  * @return session found or created
1133  */
1134 static struct Session * session_get (void * cls, const struct GNUNET_PeerIdentity *p)
1135 {
1136   struct Plugin *plugin = cls;
1137   struct Session *cs;
1138   unsigned int res;
1139
1140   cs = GNUNET_CONTAINER_multihashmap_get (plugin->sessions, &p->hashPubKey);
1141   if (cs != NULL)
1142   {
1143     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1144                 "Session `%s' found\n", GNUNET_i2s(p));
1145   }
1146   if (cs == NULL)
1147   {
1148     cs = create_session(plugin, NULL, 0, NULL, 0, p);
1149     res = GNUNET_CONTAINER_multihashmap_put ( plugin->sessions,
1150                                         &cs->identity.hashPubKey,
1151                                         cs,
1152                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1153     if (res == GNUNET_OK)
1154       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1155                   "New Session `%s' inserted\n", GNUNET_i2s(p));
1156   }
1157   return cs;
1158 }
1159
1160 static char * create_url(void * cls, const void * addr, size_t addrlen)
1161 {
1162   struct Plugin *plugin = cls;
1163   char *address;
1164   char *url;
1165
1166   GNUNET_assert ((addr!=NULL) && (addrlen != 0));
1167   if (addrlen == (sizeof (struct IPv4HttpAddress)))
1168   {
1169     address = GNUNET_malloc(INET_ADDRSTRLEN + 1);
1170     inet_ntop(AF_INET, &((struct IPv4HttpAddress *) addr)->ipv4_addr,address,INET_ADDRSTRLEN);
1171     GNUNET_asprintf (&url,
1172                      "http://%s:%u/%s",
1173                      address,
1174                      ntohs(((struct IPv4HttpAddress *) addr)->u_port),
1175                      (char *) (&plugin->my_ascii_hash_ident));
1176     GNUNET_free(address);
1177   }
1178   else if (addrlen == (sizeof (struct IPv6HttpAddress)))
1179   {
1180     address = GNUNET_malloc(INET6_ADDRSTRLEN + 1);
1181     inet_ntop(AF_INET6, &((struct IPv6HttpAddress *) addr)->ipv6_addr,address,INET6_ADDRSTRLEN);
1182     GNUNET_asprintf(&url,
1183                     "http://%s:%u/%s",
1184                     address,
1185                     ntohs(((struct IPv6HttpAddress *) addr)->u6_port),
1186                     (char *) (&plugin->my_ascii_hash_ident));
1187     GNUNET_free(address);
1188   }
1189   return url;
1190 }
1191
1192 /**
1193  * Check if session already knows this address for a outbound connection to this peer
1194  * If address not in session, add it to the session
1195  * @param cls the plugin used
1196  * @param p the session
1197  * @param addr address
1198  * @param addr_len address length
1199  * @return GNUNET_NO if address not known, GNUNET_YES if known
1200  */
1201 static struct HTTP_Connection * session_check_address (void * cls, struct Session *cs, const void * addr, size_t addr_len)
1202 {
1203   struct Plugin *plugin = cls;
1204   struct HTTP_Connection * cc = cs->outbound_addresses_head;
1205   struct HTTP_Connection * con = NULL;
1206
1207   GNUNET_assert((addr_len == sizeof (struct IPv4HttpAddress)) || (addr_len == sizeof (struct IPv6HttpAddress)));
1208
1209   while (cc!=NULL)
1210   {
1211     if (addr_len == cc->addrlen)
1212     {
1213       if (0 == memcmp(cc->addr, addr, addr_len))
1214       {
1215         con = cc;
1216         break;
1217       }
1218     }
1219     cc=cc->next;
1220   }
1221   if (con==NULL)
1222   {
1223     con = GNUNET_malloc(sizeof(struct HTTP_Connection) + addr_len);
1224     con->addrlen = addr_len;
1225     con->addr=&con[1];
1226     con->url=create_url(plugin, addr, addr_len);
1227     con->connected = GNUNET_NO;
1228     con->session = cs;
1229     memcpy(con->addr, addr, addr_len);
1230     GNUNET_CONTAINER_DLL_insert(cs->outbound_addresses_head,cs->outbound_addresses_tail,con);
1231   }
1232   return con;
1233 }
1234
1235 /**
1236  * Function that can be used by the transport service to transmit
1237  * a message using the plugin.
1238  *
1239  * @param cls closure
1240  * @param target who should receive this message
1241  * @param priority how important is the message
1242  * @param msgbuf the message to transmit
1243  * @param msgbuf_size number of bytes in 'msgbuf'
1244  * @param to when should we time out
1245  * @param session which session must be used (or NULL for "any")
1246  * @param addr the address to use (can be NULL if the plugin
1247  *                is "on its own" (i.e. re-use existing TCP connection))
1248  * @param addrlen length of the address in bytes
1249  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1250  *                otherwise the plugin may use other addresses or
1251  *                existing connections (if available)
1252  * @param cont continuation to call once the message has
1253  *        been transmitted (or if the transport is ready
1254  *        for the next transmission call; or if the
1255  *        peer disconnected...)
1256  * @param cont_cls closure for cont
1257  * @return number of bytes used (on the physical network, with overheads);
1258  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1259  *         and does NOT mean that the message was not transmitted (DV)
1260  */
1261 static ssize_t
1262 http_plugin_send (void *cls,
1263                   const struct GNUNET_PeerIdentity *target,
1264                   const char *msgbuf,
1265                   size_t msgbuf_size,
1266                   unsigned int priority,
1267                   struct GNUNET_TIME_Relative to,
1268                   struct Session *session,
1269                   const void *addr,
1270                   size_t addrlen,
1271                   int force_address,
1272                   GNUNET_TRANSPORT_TransmitContinuation cont,
1273                   void *cont_cls)
1274 {
1275   struct Plugin *plugin = cls;
1276   char *address;
1277   char *url;
1278   struct Session *cs;
1279   struct HTTP_Message *msg;
1280   struct HTTP_Connection *con;
1281   //unsigned int ret;
1282
1283   GNUNET_assert(cls !=NULL);
1284   url = NULL;
1285   address = NULL;
1286
1287   /* get session from hashmap */
1288   cs = session_get(plugin, target);
1289   con = session_check_address(plugin, cs, addr, addrlen);
1290
1291   /* create msg */
1292   msg = GNUNET_malloc (sizeof (struct HTTP_Message) + msgbuf_size);
1293   msg->next = NULL;
1294   msg->size = msgbuf_size;
1295   msg->pos = 0;
1296   msg->buf = (char *) &msg[1];
1297   msg->dest_url = url;
1298   msg->transmit_cont = cont;
1299   msg->transmit_cont_cls = cont_cls;
1300   memcpy (msg->buf,msgbuf, msgbuf_size);
1301
1302   /* must use this address */
1303   if (force_address == GNUNET_YES)
1304   {
1305     /* enqueue in connection message queue */
1306     GNUNET_CONTAINER_DLL_insert(con->pending_msgs_head,con->pending_msgs_tail,msg);
1307   }
1308   /* can use existing connection to send */
1309   else
1310   {
1311     /* enqueue in connection message queue */
1312     GNUNET_CONTAINER_DLL_insert(con->pending_msgs_head,con->pending_msgs_tail,msg);
1313   }
1314
1315   return send_select_init (plugin, cs, con);
1316
1317
1318   /* insert created message in double linked list of pending messages */
1319   /*
1320   GNUNET_CONTAINER_DLL_insert (cs->pending_outbound_msg_head, cs->pending_outbound_msg_tail, msg);
1321
1322   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));
1323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: url `%s'\n",url);
1324   if (msg == cs->pending_outbound_msg_tail)
1325   {
1326     return send_select_init (plugin, cs);
1327   }
1328   return msgbuf_size;
1329   */
1330 }
1331
1332
1333
1334 /**
1335  * Function that can be used to force the plugin to disconnect
1336  * from the given peer and cancel all previous transmissions
1337  * (and their continuationc).
1338  *
1339  * @param cls closure
1340  * @param target peer from which to disconnect
1341  */
1342 static void
1343 http_plugin_disconnect (void *cls,
1344                             const struct GNUNET_PeerIdentity *target)
1345 {
1346   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_disconnect\n");
1347   // struct Plugin *plugin = cls;
1348   // FIXME
1349 }
1350
1351
1352 /**
1353  * Convert the transports address to a nice, human-readable
1354  * format.
1355  *
1356  * @param cls closure
1357  * @param type name of the transport that generated the address
1358  * @param addr one of the addresses of the host, NULL for the last address
1359  *        the specific address format depends on the transport
1360  * @param addrlen length of the address
1361  * @param numeric should (IP) addresses be displayed in numeric form?
1362  * @param timeout after how long should we give up?
1363  * @param asc function to call on each string
1364  * @param asc_cls closure for asc
1365  */
1366 static void
1367 http_plugin_address_pretty_printer (void *cls,
1368                                         const char *type,
1369                                         const void *addr,
1370                                         size_t addrlen,
1371                                         int numeric,
1372                                         struct GNUNET_TIME_Relative timeout,
1373                                         GNUNET_TRANSPORT_AddressStringCallback
1374                                         asc, void *asc_cls)
1375 {
1376   const struct IPv4HttpAddress *t4;
1377   const struct IPv6HttpAddress *t6;
1378   struct sockaddr_in a4;
1379   struct sockaddr_in6 a6;
1380   char * address;
1381   char * ret;
1382   unsigned int port;
1383   unsigned int res;
1384
1385   GNUNET_assert(cls !=NULL);
1386   if (addrlen == sizeof (struct IPv6HttpAddress))
1387   {
1388     address = GNUNET_malloc (INET6_ADDRSTRLEN);
1389     t6 = addr;
1390     a6.sin6_addr = t6->ipv6_addr;
1391     inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
1392     port = ntohs(t6->u6_port);
1393   }
1394   else if (addrlen == sizeof (struct IPv4HttpAddress))
1395   {
1396     address = GNUNET_malloc (INET_ADDRSTRLEN);
1397     t4 = addr;
1398     a4.sin_addr.s_addr =  t4->ipv4_addr;
1399     inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
1400     port = ntohs(t4->u_port);
1401   }
1402   else
1403   {
1404     /* invalid address */
1405     GNUNET_break_op (0);
1406     asc (asc_cls, NULL);
1407     return;
1408   }
1409   res = GNUNET_asprintf(&ret,"http://%s:%u/",address,port);
1410   GNUNET_free (address);
1411   GNUNET_assert(res != 0);
1412
1413   asc (asc_cls, ret);
1414 }
1415
1416
1417
1418 /**
1419  * Another peer has suggested an address for this
1420  * peer and transport plugin.  Check that this could be a valid
1421  * address.  If so, consider adding it to the list
1422  * of addresses.
1423  *
1424  * @param cls closure
1425  * @param addr pointer to the address
1426  * @param addrlen length of addr
1427  * @return GNUNET_OK if this is a plausible address for this peer
1428  *         and transport
1429  */
1430 static int
1431 http_plugin_address_suggested (void *cls,
1432                                   void *addr, size_t addrlen)
1433 {
1434   struct Plugin *plugin = cls;
1435   struct IPv4HttpAddress *v4;
1436   struct IPv6HttpAddress *v6;
1437   unsigned int port;
1438
1439   GNUNET_assert(cls !=NULL);
1440   if ((addrlen != sizeof (struct IPv4HttpAddress)) &&
1441       (addrlen != sizeof (struct IPv6HttpAddress)))
1442     {
1443       return GNUNET_SYSERR;
1444     }
1445   if (addrlen == sizeof (struct IPv4HttpAddress))
1446     {
1447       v4 = (struct IPv4HttpAddress *) addr;
1448       if (INADDR_LOOPBACK == ntohl(v4->ipv4_addr))
1449       {
1450         return GNUNET_SYSERR;
1451       }
1452       port = ntohs (v4->u_port);
1453       if (port != plugin->port_inbound)
1454       {
1455         return GNUNET_SYSERR;
1456       }
1457     }
1458   else
1459     {
1460       v6 = (struct IPv6HttpAddress *) addr;
1461       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1462         {
1463           return GNUNET_SYSERR;
1464         }
1465       port = ntohs (v6->u6_port);
1466       if (port != plugin->port_inbound)
1467       {
1468         return GNUNET_SYSERR;
1469       }
1470     }
1471
1472
1473   return GNUNET_OK;
1474 }
1475
1476
1477 /**
1478  * Function called for a quick conversion of the binary address to
1479  * a numeric address.  Note that the caller must not free the
1480  * address and that the next call to this function is allowed
1481  * to override the address again.
1482  *
1483  * @param cls closure
1484  * @param addr binary address
1485  * @param addrlen length of the address
1486  * @return string representing the same address
1487  */
1488 static const char*
1489 http_plugin_address_to_string (void *cls,
1490                                    const void *addr,
1491                                    size_t addrlen)
1492 {
1493   const struct IPv4HttpAddress *t4;
1494   const struct IPv6HttpAddress *t6;
1495   struct sockaddr_in a4;
1496   struct sockaddr_in6 a6;
1497   char * address;
1498   char * ret;
1499   unsigned int port;
1500   unsigned int res;
1501
1502   GNUNET_assert(cls !=NULL);
1503   if (addrlen == sizeof (struct IPv6HttpAddress))
1504     {
1505       address = GNUNET_malloc (INET6_ADDRSTRLEN);
1506       t6 = addr;
1507       a6.sin6_addr = t6->ipv6_addr;
1508       inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
1509       port = ntohs(t6->u6_port);
1510     }
1511   else if (addrlen == sizeof (struct IPv4HttpAddress))
1512     {
1513       address = GNUNET_malloc (INET_ADDRSTRLEN);
1514       t4 = addr;
1515       a4.sin_addr.s_addr =  t4->ipv4_addr;
1516       inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
1517       port = ntohs(t4->u_port);
1518     }
1519   else
1520     {
1521       /* invalid address */
1522       return NULL;
1523     }
1524   res = GNUNET_asprintf(&ret,"%s:%u",address,port);
1525   GNUNET_free (address);
1526   GNUNET_assert(res != 0);
1527   return ret;
1528 }
1529
1530 /**
1531  * Add the IP of our network interface to the list of
1532  * our external IP addresses.
1533  *
1534  * @param cls the 'struct Plugin*'
1535  * @param name name of the interface
1536  * @param isDefault do we think this may be our default interface
1537  * @param addr address of the interface
1538  * @param addrlen number of bytes in addr
1539  * @return GNUNET_OK to continue iterating
1540  */
1541 static int
1542 process_interfaces (void *cls,
1543                     const char *name,
1544                     int isDefault,
1545                     const struct sockaddr *addr, socklen_t addrlen)
1546 {
1547   struct Plugin *plugin = cls;
1548   struct IPv4HttpAddress t4;
1549   struct IPv6HttpAddress t6;
1550   int af;
1551   void *arg;
1552   uint16_t args;
1553
1554   GNUNET_assert(cls !=NULL);
1555   af = addr->sa_family;
1556   if (af == AF_INET)
1557     {
1558       if (INADDR_LOOPBACK == ntohl(((struct sockaddr_in *) addr)->sin_addr.s_addr))
1559       {
1560         /* skip loopback addresses */
1561         return GNUNET_OK;
1562       }
1563       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1564       t4.u_port = htons (plugin->port_inbound);
1565       arg = &t4;
1566       args = sizeof (t4);
1567     }
1568   else if (af == AF_INET6)
1569     {
1570       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1571         {
1572           /* skip link local addresses */
1573           return GNUNET_OK;
1574         }
1575       if (IN6_IS_ADDR_LOOPBACK (&((struct sockaddr_in6 *) addr)->sin6_addr))
1576         {
1577           /* skip loopback addresses */
1578           return GNUNET_OK;
1579         }
1580       memcpy (&t6.ipv6_addr,
1581               &((struct sockaddr_in6 *) addr)->sin6_addr,
1582               sizeof (struct in6_addr));
1583       t6.u6_port = htons (plugin->port_inbound);
1584       arg = &t6;
1585       args = sizeof (t6);
1586     }
1587   else
1588     {
1589       GNUNET_break (0);
1590       return GNUNET_OK;
1591     }
1592   plugin->env->notify_address(plugin->env->cls,"http",arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1593   return GNUNET_OK;
1594 }
1595
1596 int hashMapFreeIterator (void *cls, const GNUNET_HashCode *key, void *value)
1597 {
1598   struct Session * cs = value;
1599
1600   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing session for peer `%s'\n",GNUNET_i2s(&cs->identity));
1601
1602   /* freeing messages */
1603   struct HTTP_Message *cur;
1604   struct HTTP_Message *tmp;
1605   cur = cs->pending_outbound_msg_head;
1606
1607   while (cur != NULL)
1608   {
1609     tmp = cur->next;
1610     GNUNET_free_non_null(cur->dest_url);
1611     GNUNET_free (cur);
1612     cur = tmp;
1613   }
1614   GNUNET_SERVER_mst_destroy (cs->msgtok);
1615   GNUNET_free_non_null (cs->addr_in);
1616   GNUNET_free_non_null (cs->addr_out);
1617   GNUNET_free (cs);
1618   return GNUNET_YES;
1619 }
1620
1621 /**
1622  * Exit point from the plugin.
1623  */
1624 void *
1625 libgnunet_plugin_transport_http_done (void *cls)
1626 {
1627   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1628   struct Plugin *plugin = api->cls;
1629   CURLMcode mret;
1630
1631   GNUNET_assert(cls !=NULL);
1632
1633
1634   if ( plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1635   {
1636     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
1637     plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
1638   }
1639
1640   if ( plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1641   {
1642     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
1643     plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1644   }
1645
1646   if ( plugin->http_server_task_send != GNUNET_SCHEDULER_NO_TASK)
1647   {
1648     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_send);
1649     plugin->http_server_task_send = GNUNET_SCHEDULER_NO_TASK;
1650   }
1651
1652   if (plugin->http_server_daemon_v4 != NULL)
1653   {
1654     MHD_stop_daemon (plugin->http_server_daemon_v4);
1655     plugin->http_server_daemon_v4 = NULL;
1656   }
1657   if (plugin->http_server_daemon_v6 != NULL)
1658   {
1659     MHD_stop_daemon (plugin->http_server_daemon_v6);
1660     plugin->http_server_daemon_v6 = NULL;
1661   }
1662
1663   /* free all sessions */
1664   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions,
1665                                          &hashMapFreeIterator,
1666                                          NULL);
1667
1668   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
1669
1670   mret = curl_multi_cleanup(plugin->multi_handle);
1671   if ( CURLM_OK != mret)
1672     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed");
1673
1674   GNUNET_free (plugin);
1675   GNUNET_free (api);
1676   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unload http plugin complete...\n");
1677   return NULL;
1678 }
1679
1680
1681 /**
1682  * Entry point for the plugin.
1683  */
1684 void *
1685 libgnunet_plugin_transport_http_init (void *cls)
1686 {
1687   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1688   struct Plugin *plugin;
1689   struct GNUNET_TRANSPORT_PluginFunctions *api;
1690   struct GNUNET_TIME_Relative gn_timeout;
1691   long long unsigned int port;
1692
1693   GNUNET_assert(cls !=NULL);
1694   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
1695
1696   plugin = GNUNET_malloc (sizeof (struct Plugin));
1697   plugin->env = env;
1698   plugin->sessions = NULL;
1699
1700   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1701   api->cls = plugin;
1702   api->send = &http_plugin_send;
1703   api->disconnect = &http_plugin_disconnect;
1704   api->address_pretty_printer = &http_plugin_address_pretty_printer;
1705   api->check_address = &http_plugin_address_suggested;
1706   api->address_to_string = &http_plugin_address_to_string;
1707
1708   /* Hashing our identity to use it in URLs */
1709   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &plugin->my_ascii_hash_ident);
1710
1711   /* Reading port number from config file */
1712   if ((GNUNET_OK !=
1713        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1714                                               "transport-http",
1715                                               "PORT",
1716                                               &port)) ||
1717       (port > 65535) )
1718     {
1719       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1720                        "http",
1721                        _
1722                        ("Require valid port number for transport plugin `%s' in configuration!\n"),
1723                        "transport-http");
1724       libgnunet_plugin_transport_http_done (api);
1725       return NULL;
1726     }
1727   GNUNET_assert ((port > 0) && (port <= 65535));
1728   plugin->port_inbound = port;
1729   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1730   if ((plugin->http_server_daemon_v4 == NULL) && (plugin->http_server_daemon_v6 == NULL) && (port != 0))
1731     {
1732     plugin->http_server_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
1733                                        port,
1734                                        &acceptPolicyCallback,
1735                                        plugin , &accessHandlerCallback, plugin,
1736                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1737                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1738                                        MHD_OPTION_CONNECTION_TIMEOUT, (gn_timeout.value / 1000),
1739                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1740                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1741                                        MHD_OPTION_END);
1742     plugin->http_server_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
1743                                        port,
1744                                        &acceptPolicyCallback,
1745                                        plugin , &accessHandlerCallback, plugin,
1746                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1747                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1748                                        MHD_OPTION_CONNECTION_TIMEOUT, (gn_timeout.value / 1000),
1749                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1750                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1751                                        MHD_OPTION_END);
1752     }
1753   if (plugin->http_server_daemon_v4 != NULL)
1754     plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
1755   if (plugin->http_server_daemon_v6 != NULL)
1756     plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
1757
1758   if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1759     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
1760   else if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1761     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
1762   else
1763   {
1764     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No MHD was started, transport plugin not functional!\n");
1765     libgnunet_plugin_transport_http_done (api);
1766     return NULL;
1767   }
1768
1769   /* Initializing cURL */
1770   curl_global_init(CURL_GLOBAL_ALL);
1771   plugin->multi_handle = curl_multi_init();
1772
1773   if ( NULL == plugin->multi_handle )
1774   {
1775     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1776                      "http",
1777                      _("Could not initialize curl multi handle, failed to start http plugin!\n"),
1778                      "transport-http");
1779     libgnunet_plugin_transport_http_done (api);
1780     return NULL;
1781   }
1782
1783   plugin->sessions = GNUNET_CONTAINER_multihashmap_create (10);
1784   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1785
1786   return api;
1787 }
1788
1789 /* end of plugin_transport_http.c */