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