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