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