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