(no commit message)
[oweals/gnunet.git] / src / transport / plugin_transport_http.c
1 /*
2      This file is part of GNUnet
3      (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file transport/plugin_transport_template.c
23  * @brief template for a new transport service
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_connection_lib.h"
31 #include "gnunet_server_lib.h"
32 #include "gnunet_service_lib.h"
33 #include "gnunet_statistics_service.h"
34 #include "gnunet_transport_service.h"
35 #include "gnunet_resolver_service.h"
36 #include "plugin_transport.h"
37 #include "microhttpd.h"
38 #include <curl/curl.h>
39
40 #define DEBUG_HTTP GNUNET_NO
41
42 /**
43  * Text of the response sent back after the last bytes of a PUT
44  * request have been received (just to formally obey the HTTP
45  * protocol).
46  */
47 #define HTTP_PUT_RESPONSE "Thank you!"
48
49 /**
50  * After how long do we expire an address that we
51  * learned from another peer if it is not reconfirmed
52  * by anyone?
53  */
54 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
55
56 /**
57  * Page returned if request invalid
58  */
59 #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>"
60
61 /**
62  * Timeout for a http connect
63  */
64 #define HTTP_CONNECT_TIMEOUT 30
65
66
67 /**
68  * Encapsulation of all of the state of the plugin.
69  */
70 struct Plugin;
71
72
73 /**
74  * Session handle for connections.
75  */
76 struct Session
77 {
78
79   /**
80    * Stored in a linked list.
81    */
82   struct Session *next;
83
84   /**
85    * Pointer to the global plugin struct.
86    */
87   struct Plugin *plugin;
88
89   /**
90    * Continuation function to call once the transmission buffer
91    * has again space available.  NULL if there is no
92    * continuation to call.
93    */
94   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
95
96   /**
97    * Closure for transmit_cont.
98    */
99   void *transmit_cont_cls;
100
101   /**
102    * To whom are we talking to (set to our identity
103    * if we are still waiting for the welcome message)
104    */
105   struct GNUNET_PeerIdentity sender;
106
107   /**
108    * Sender's url
109    */
110   char * url;
111
112   /**
113    * Sender's ip address to distinguish between incoming connections
114    */
115   char * ip;
116
117   /**
118    * Sender's ip address to distinguish between incoming connections
119    */
120   struct sockaddr_in * addr;
121
122   /**
123    * Did we initiate the connection (GNUNET_YES) or the other peer (GNUNET_NO)?
124    */
125   unsigned int is_client;
126
127   /**
128    * Is the connection active (GNUNET_YES) or terminated (GNUNET_NO)?
129    */
130   unsigned int is_active;
131
132   /**
133    * At what time did we reset last_received last?
134    */
135   struct GNUNET_TIME_Absolute last_quota_update;
136
137   /**
138    * How many bytes have we received since the "last_quota_update"
139    * timestamp?
140    */
141   uint64_t last_received;
142
143   /**
144    * Number of bytes per ms that this peer is allowed
145    * to send to us.
146    */
147   uint32_t quota;
148
149   /**
150    * Is there a HTTP/PUT in progress?
151    */
152   unsigned int is_put_in_progress;
153
154   /**
155    * Encoded hash
156    */
157   struct GNUNET_CRYPTO_HashAsciiEncoded hash;
158 };
159
160 /**
161  * Encapsulation of all of the state of the plugin.
162  */
163 struct Plugin
164 {
165   /**
166    * Our environment.
167    */
168   struct GNUNET_TRANSPORT_PluginEnvironment *env;
169
170   /**
171    * Handle to the network service.
172    */
173   struct GNUNET_SERVICE_Context *service;
174
175   /**
176    * List of open sessions.
177    */
178   struct Session *sessions;
179
180   /**
181    * Number of active sessions
182    */
183
184   unsigned int session_count;
185
186 };
187
188 /**
189  * Daemon for listening for new IPv4 connections.
190  */
191 static struct MHD_Daemon *http_daemon_v4;
192
193 /**
194  * Daemon for listening for new IPv6connections.
195  */
196 static struct MHD_Daemon *http_daemon_v6;
197
198 /**
199  * Our primary task for http daemon handling IPv4 connections
200  */
201 static GNUNET_SCHEDULER_TaskIdentifier http_task_v4;
202
203 /**
204  * Our primary task for http daemon handling IPv6 connections
205  */
206 static GNUNET_SCHEDULER_TaskIdentifier http_task_v6;
207
208
209 /**
210  * Our primary task for http daemon handling IPv6 connections
211  */
212 static GNUNET_SCHEDULER_TaskIdentifier http_task_send;
213
214
215 /**
216  * Information about this plugin
217  */
218 static struct Plugin *plugin;
219
220 /**
221  * cURL Multihandle
222  */
223 static CURLM *multi_handle;
224
225 /**
226  * Our hostname
227  */
228 static char * hostname;
229
230 /**
231  * Our ASCII encoded, hashed peer identity
232  * This string is used to distinguish between connections and is added to the urls
233  */
234 static struct GNUNET_CRYPTO_HashAsciiEncoded my_ascii_hash_ident;
235
236 /**
237  * Message-Packet header.
238  */
239 struct HTTPMessage
240 {
241   /**
242    * size of the message, in bytes, including this header.
243    */
244   struct GNUNET_MessageHeader header;
245
246   /**
247    * What is the identity of the sender (GNUNET_hash of public key)
248    */
249   struct GNUNET_PeerIdentity sender;
250
251 };
252
253 struct CBC
254 {
255   char *buf;
256   size_t pos;
257   size_t size;
258   size_t len;
259 };
260
261
262 /**
263  * Finds a http session in our linked list using peer identity as a key
264  * @param peer peeridentity
265  * @return http session corresponding to peer identity
266  */
267 static struct Session * find_session_by_pi( const struct GNUNET_PeerIdentity *peer )
268 {
269   struct Session * cur;
270   GNUNET_HashCode hc_peer;
271   GNUNET_HashCode hc_current;
272
273   cur = plugin->sessions;
274   hc_peer = peer->hashPubKey;
275   while (cur != NULL)
276   {
277     hc_current = cur->sender.hashPubKey;
278     if ( 0 == GNUNET_CRYPTO_hash_cmp( &hc_peer, &hc_current))
279       return cur;
280     cur = plugin->sessions->next;
281   }
282   return NULL;
283 }
284
285 #if 0
286 /**
287  * Finds a http session in our linked list using peer identity as a key
288  * @param peer peeridentity
289  * @return http session corresponding to peer identity
290  */
291 static struct Session * find_session_by_ip( char * ip )
292 {
293   /*
294   struct Session * cur;
295
296   cur = plugin->sessions;
297   while (cur != NULL)
298   {
299     hc_current = cur->sender.hashPubKey;
300     if ( 0 == GNUNET_CRYPTO_hash_cmp( &hc_peer, &hc_current))
301       return cur;
302     cur = plugin->sessions->next;
303   }
304   */
305   return NULL;
306 }
307 #endif
308
309 #if 0
310 /**
311  * Creates a http session in our linked list by ip address
312  * Only ip is set here, all other fields have to be set by calling method
313  * @param peer peeridentity
314  * @return created http session
315  */
316 static struct Session * create_session_by_ip ( struct sockaddr_in * addr )
317 {
318   struct Session * cur;
319   struct Session * last_in_list;
320   /* Create a new session object */
321   cur = GNUNET_malloc (sizeof (struct Session));
322   // FIXME: memcpy( &(cur->ip), , sizeof( struct GNUNET_PeerIdentity ) );
323
324   cur->next = NULL;
325
326   /* Insert into linked list */
327   last_in_list = plugin->sessions;
328   while (last_in_list->next != NULL)
329   {
330     last_in_list = last_in_list->next;
331   }
332   last_in_list->next = cur;
333
334   return cur;
335 }
336 #endif
337
338 /**
339  * Callback called by MHD when a connection is terminated
340  */
341 static void requestCompletedCallback (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
342 {
343   struct Session * cs;
344
345   cs = *httpSessionCache;
346   if (cs != NULL)
347   {
348     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection from peer `%s' was terminated\n",GNUNET_i2s(&cs->sender));
349     /* session set to inactive */
350     cs->is_active = GNUNET_NO;
351     cs->is_put_in_progress = GNUNET_NO;
352   }
353   return;
354 }
355
356 /**
357  * Check if we are allowed to connect to the given IP.
358  */
359 static int
360 acceptPolicyCallback (void *cls,
361                       const struct sockaddr *addr, socklen_t addr_len)
362 {
363   /* Every connection is accepted, nothing more to do here */
364   return MHD_YES;
365 }
366
367
368 /**
369  * Process GET or PUT request received via MHD.  For
370  * GET, queue response that will send back our pending
371  * messages.  For PUT, process incoming data and send
372  * to GNUnet core.  In either case, check if a session
373  * already exists and create a new one if not.
374  */
375 static int
376 accessHandlerCallback (void *cls,
377                        struct MHD_Connection *session,
378                        const char *url,
379                        const char *method,
380                        const char *version,
381                        const char *upload_data,
382                        size_t * upload_data_size, void **httpSessionCache)
383 {
384   struct MHD_Response *response;
385   struct Session * cs;
386   struct Session * cs_temp;
387   const union MHD_ConnectionInfo * conn_info;
388   struct sockaddr_in  *addrin;
389   struct sockaddr_in6 *addrin6;
390   char * address = NULL;
391   struct GNUNET_PeerIdentity pi_in;
392   int res = GNUNET_NO;
393   size_t bytes_recv;
394   struct GNUNET_MessageHeader *gn_msg;
395
396   gn_msg = NULL;
397
398   if ( NULL == *httpSessionCache)
399   {
400     /* check url for peer identity */
401     res = GNUNET_CRYPTO_hash_from_string ( &url[1], &(pi_in.hashPubKey));
402     if ( GNUNET_SYSERR == res )
403     {
404       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident\n");
405       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
406       res = MHD_queue_response (session, MHD_HTTP_NOT_FOUND, response);
407       MHD_destroy_response (response);
408       return res;
409     }
410
411     conn_info = MHD_get_connection_info(session, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
412     /* Incoming IPv4 connection */
413     if ( AF_INET == conn_info->client_addr->sin_family)
414     {
415       address = GNUNET_malloc (INET_ADDRSTRLEN);
416       addrin = conn_info->client_addr;
417       inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
418     }
419     /* Incoming IPv6 connection */
420     if ( AF_INET6 == conn_info->client_addr->sin_family)
421     {
422       address = GNUNET_malloc (INET6_ADDRSTRLEN);
423       addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
424       inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
425     }
426     /* find existing session for address */
427     cs = NULL;
428     if (plugin->session_count > 0)
429     {
430       cs = plugin->sessions;
431       while ( NULL != cs)
432       {
433
434         /* Comparison based on ip address */
435         // res = (0 == memcmp(&(conn_info->client_addr->sin_addr),&(cs->addr->sin_addr), sizeof (struct in_addr))) ? GNUNET_YES : GNUNET_NO;
436
437         /* Comparison based on ip address, port number and address family */
438         // res = (0 == memcmp((conn_info->client_addr),(cs->addr), sizeof (struct sockaddr_in))) ? GNUNET_YES : GNUNET_NO;
439
440         /* Comparison based on PeerIdentity */
441         res = (0 == memcmp(&pi_in,&(cs->sender), sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_YES : GNUNET_NO;
442
443         if ( GNUNET_YES  == res)
444         {
445           /* existing session for this address found */
446           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session `%s' found\n",address);
447           break;
448         }
449         cs = cs->next;
450       }
451     }
452     /* no existing session, create a new one*/
453     if (cs == NULL )
454     {
455       /* create new session object */
456       cs = GNUNET_malloc ( sizeof( struct Session) );
457       cs->addr = GNUNET_malloc ( sizeof (struct sockaddr_in) );
458
459       cs->ip = address;
460       memcpy(cs->addr, conn_info->client_addr, sizeof (struct sockaddr_in));
461       memcpy(&cs->sender, &pi_in, sizeof (struct GNUNET_PeerIdentity));
462       memcpy(&cs->hash,&url[1],104);
463       cs->next = NULL;
464       cs->is_active = GNUNET_YES;
465
466       /* Insert session into linked list */
467       if ( plugin->sessions == NULL)
468       {
469         plugin->sessions = cs;
470         plugin->session_count = 1;
471       }
472       cs_temp = plugin->sessions;
473       while ( cs_temp->next != NULL )
474       {
475         cs_temp = cs_temp->next;
476       }
477       if (cs_temp != cs )
478       {
479         cs_temp->next = cs;
480         plugin->session_count++;
481       }
482       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"New Session `%s' inserted, count %u \n", address, plugin->session_count);
483     }
484     /* Set closure */
485     if (*httpSessionCache == NULL)
486     {
487       *httpSessionCache = cs;
488     }
489     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Daemon has new an incoming `%s' request from peer `%s' (`[%s]:%u')\n",method, GNUNET_i2s(&cs->sender),cs->ip,cs->addr->sin_port);
490   }
491   else
492   {
493     cs = *httpSessionCache;
494   }
495   /* Is it a PUT or a GET request */
496   if ( 0 == strcmp (MHD_HTTP_METHOD_PUT, method) )
497   {
498     /* New  */
499     if ((*upload_data_size == 0) && (cs->is_put_in_progress == GNUNET_NO))
500     {
501       /* not yet ready */
502       cs->is_put_in_progress = GNUNET_YES;
503       return MHD_YES;
504     }
505     if ( *upload_data_size > 0 )
506     {
507       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"PUT URL: `%s'\n",url);
508       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"PUT Request: %lu bytes: `%s' \n", (*upload_data_size), upload_data);
509       /* No data left */
510       bytes_recv = *upload_data_size ;
511       *upload_data_size = 0;
512
513       /* checking size */
514       if (bytes_recv < sizeof (struct GNUNET_MessageHeader))
515       {
516         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Message too small, is %u bytes, has to be at least %u '\n",bytes_recv, sizeof(struct GNUNET_MessageHeader));
517         return MHD_NO;
518       }
519
520       if ( bytes_recv > GNUNET_SERVER_MAX_MESSAGE_SIZE)
521       {
522         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Message too big, is %u bytes, maximum %u '\n",bytes_recv, GNUNET_SERVER_MAX_MESSAGE_SIZE);
523         return MHD_NO;
524       }
525
526       struct GNUNET_MessageHeader * gn_msg = GNUNET_malloc (bytes_recv);
527       memcpy (gn_msg,upload_data,bytes_recv);
528
529       if ( ntohs(gn_msg->size) != bytes_recv )
530       {
531         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Message has incorrect size, is %u bytes vs %u recieved'\n",ntohs(gn_msg->size) , bytes_recv);
532         GNUNET_free (gn_msg);
533         return MHD_NO;
534       }
535       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));
536       /* forwarding message to transport */
537       plugin->env->receive(plugin->env, &(cs->sender), gn_msg, 1, cs , cs->ip, strlen(cs->ip) );
538       return MHD_YES;
539     }
540     if ((*upload_data_size == 0) && (cs->is_put_in_progress == GNUNET_YES))
541     {
542       cs->is_put_in_progress = GNUNET_NO;
543       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
544       res = MHD_queue_response (session, MHD_HTTP_OK, response);
545       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Sent HTTP/1.1: 200 OK as PUT Response\n",HTTP_PUT_RESPONSE, strlen (HTTP_PUT_RESPONSE), res );
546       MHD_destroy_response (response);
547       return res;
548     }
549   }
550   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
551   {
552     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request\n");
553     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"URL: `%s'\n",url);
554     response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
555     res = MHD_queue_response (session, MHD_HTTP_OK, response);
556     MHD_destroy_response (response);
557     return res;
558   }
559   return MHD_NO;
560 }
561
562
563 /**
564  * Call MHD to process pending requests and then go back
565  * and schedule the next run.
566  */
567 static void http_daemon_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
568
569 /**
570  * Function that queries MHD's select sets and
571  * starts the task waiting for them.
572  */
573 static GNUNET_SCHEDULER_TaskIdentifier
574 http_daemon_prepare (struct MHD_Daemon *daemon_handle)
575 {
576   GNUNET_SCHEDULER_TaskIdentifier ret;
577   fd_set rs;
578   fd_set ws;
579   fd_set es;
580   struct GNUNET_NETWORK_FDSet *wrs;
581   struct GNUNET_NETWORK_FDSet *wws;
582   struct GNUNET_NETWORK_FDSet *wes;
583   int max;
584   unsigned long long timeout;
585   int haveto;
586   struct GNUNET_TIME_Relative tv;
587
588   FD_ZERO(&rs);
589   FD_ZERO(&ws);
590   FD_ZERO(&es);
591   wrs = GNUNET_NETWORK_fdset_create ();
592   wes = GNUNET_NETWORK_fdset_create ();
593   wws = GNUNET_NETWORK_fdset_create ();
594   max = -1;
595   GNUNET_assert (MHD_YES ==
596                  MHD_get_fdset (daemon_handle,
597                                 &rs,
598                                 &ws,
599                                 &es,
600                                 &max));
601   haveto = MHD_get_timeout (daemon_handle, &timeout);
602   if (haveto == MHD_YES)
603     tv.value = (uint64_t) timeout;
604   else
605     tv = GNUNET_TIME_UNIT_FOREVER_REL;
606   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
607   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
608   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
609   ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
610                                      GNUNET_SCHEDULER_PRIORITY_HIGH,
611                                      GNUNET_SCHEDULER_NO_TASK,
612                                      tv,
613                                      wrs,
614                                      wws,
615                                      &http_daemon_run,
616                                      daemon_handle);
617   GNUNET_NETWORK_fdset_destroy (wrs);
618   GNUNET_NETWORK_fdset_destroy (wws);
619   GNUNET_NETWORK_fdset_destroy (wes);
620   return ret;
621 }
622
623 /**
624  * Call MHD to process pending requests and then go back
625  * and schedule the next run.
626  */
627 static void
628 http_daemon_run (void *cls,
629             const struct GNUNET_SCHEDULER_TaskContext *tc)
630 {
631   struct MHD_Daemon *daemon_handle = cls;
632
633   if (daemon_handle == http_daemon_v4)
634     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
635
636   if (daemon_handle == http_daemon_v6)
637     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
638
639   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
640     return;
641
642
643
644   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
645   if (daemon_handle == http_daemon_v4)
646     http_task_v4 = http_daemon_prepare (daemon_handle);
647   if (daemon_handle == http_daemon_v6)
648     http_task_v6 = http_daemon_prepare (daemon_handle);
649   return;
650 }
651
652 static size_t send_read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
653 {
654   struct CBC  * cbc = ptr;
655   if (cbc->len > (size * nmemb))
656     return CURL_READFUNC_ABORT;
657
658   if (( cbc->pos == cbc->len) && (cbc->len < (size * nmemb)))
659     return 0;
660   memcpy(stream, cbc->buf, cbc->len);
661   cbc->pos = cbc->len;
662   return cbc->len;
663 }
664
665 static size_t send_prepare(struct Session* session );
666
667 static void send_execute (void *cls,
668              const struct GNUNET_SCHEDULER_TaskContext *tc)
669 {
670   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"send task");
671   int running;
672   struct CURLMsg *msg;
673   CURLMcode mret;
674   char * current_url= "test";
675
676   http_task_send = GNUNET_SCHEDULER_NO_TASK;
677   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
678     return;
679
680   do
681     {
682       running = 0;
683       mret = curl_multi_perform (multi_handle, &running);
684       if (running == 0)
685         {
686           do
687             {
688
689
690               msg = curl_multi_info_read (multi_handle, &running);
691               GNUNET_break (msg != NULL);
692               if (msg == NULL)
693                 break;
694               switch (msg->msg)
695                 {
696                 case CURLMSG_DONE:
697                   if ( (msg->data.result != CURLE_OK) &&
698                        (msg->data.result != CURLE_GOT_NOTHING) )
699                     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
700                                _("%s failed for `%s' at %s:%d: `%s'\n"),
701                                "curl_multi_perform",
702                                current_url,
703                                __FILE__,
704                                __LINE__,
705                                curl_easy_strerror (msg->data.result));
706                   else
707                     {
708                     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
709                                 _("Download of hostlist `%s' completed.\n"),
710                                 current_url);
711                     }
712                   return;
713                 default:
714                   break;
715                 }
716
717             }
718           while ( (running > 0) );
719         }
720     }
721   while (mret == CURLM_CALL_MULTI_PERFORM);
722
723   if (mret != CURLM_OK)
724     {
725       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
726                   _("%s failed at %s:%d: `%s'\n"),
727                   "curl_multi_perform", __FILE__, __LINE__,
728                   curl_multi_strerror (mret));
729     }
730   send_prepare(cls);
731 }
732
733
734 static size_t send_prepare(struct Session* session )
735 {
736   fd_set rs;
737   fd_set ws;
738   fd_set es;
739   int max;
740   struct GNUNET_NETWORK_FDSet *grs;
741   struct GNUNET_NETWORK_FDSet *gws;
742   long to;
743   CURLMcode mret;
744
745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"send_prepare\n");
746   max = -1;
747   FD_ZERO (&rs);
748   FD_ZERO (&ws);
749   FD_ZERO (&es);
750   mret = curl_multi_fdset (multi_handle, &rs, &ws, &es, &max);
751   if (mret != CURLM_OK)
752     {
753       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
754                   _("%s failed at %s:%d: `%s'\n"),
755                   "curl_multi_fdset", __FILE__, __LINE__,
756                   curl_multi_strerror (mret));
757       return -1;
758     }
759   mret = curl_multi_timeout (multi_handle, &to);
760   if (mret != CURLM_OK)
761     {
762       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
763                   _("%s failed at %s:%d: `%s'\n"),
764                   "curl_multi_timeout", __FILE__, __LINE__,
765                   curl_multi_strerror (mret));
766       return -1;
767     }
768
769   grs = GNUNET_NETWORK_fdset_create ();
770   gws = GNUNET_NETWORK_fdset_create ();
771   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
772   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
773   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"send_prepare\n");
774   http_task_send = GNUNET_SCHEDULER_add_select (plugin->env->sched,
775                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
776                                    GNUNET_SCHEDULER_NO_TASK,
777                                    GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 0),
778                                    grs,
779                                    gws,
780                                    &send_execute,
781                                    session);
782   GNUNET_NETWORK_fdset_destroy (gws);
783   GNUNET_NETWORK_fdset_destroy (grs);
784
785   /* FIXME: return bytes REALLY sent */
786   return 0;
787 }
788
789
790 /**
791  * Function that can be used by the transport service to transmit
792  * a message using the plugin.
793  *
794  * @param cls closure
795  * @param target who should receive this message
796  * @param priority how important is the message
797  * @param msgbuf the message to transmit
798  * @param msgbuf_size number of bytes in 'msgbuf'
799  * @param timeout when should we time out
800  * @param session which session must be used (or NULL for "any")
801  * @param addr the address to use (can be NULL if the plugin
802  *                is "on its own" (i.e. re-use existing TCP connection))
803  * @param addrlen length of the address in bytes
804  * @param force_address GNUNET_YES if the plugin MUST use the given address,
805  *                otherwise the plugin may use other addresses or
806  *                existing connections (if available)
807  * @param cont continuation to call once the message has
808  *        been transmitted (or if the transport is ready
809  *        for the next transmission call; or if the
810  *        peer disconnected...)
811  * @param cont_cls closure for cont
812  * @return number of bytes used (on the physical network, with overheads);
813  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
814  *         and does NOT mean that the message was not transmitted (DV)
815  */
816 static ssize_t
817 http_plugin_send (void *cls,
818                       const struct GNUNET_PeerIdentity *
819                       target,
820                       const char *msgbuf,
821                       size_t msgbuf_size,
822                       unsigned int priority,
823                       struct GNUNET_TIME_Relative timeout,
824                       struct Session *session,
825                       const void *addr,
826                       size_t addrlen,
827                       int force_address,
828                       GNUNET_TRANSPORT_TransmitContinuation
829                       cont, void *cont_cls)
830 {
831   struct Session* ses;
832   struct Session* ses_temp;
833   int bytes_sent = 0;
834   CURL *curl_handle;
835   CURLMcode mret;
836
837   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"http_plugin_send\n");
838
839   /* find session for peer */
840   ses = find_session_by_pi (target);
841   if (NULL != ses )
842     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session not found\n");
843   if ( ses == NULL)
844   {
845     /* create new session object */
846     ses = GNUNET_malloc ( sizeof( struct Session) );
847     ses->addr = GNUNET_malloc ( sizeof (struct sockaddr_in) );
848
849     //ses->ip = address;
850     // memcpy(ses->addr, conn_info->client_addr, sizeof (struct sockaddr_in));
851     memcpy(&ses->sender, &target, sizeof (struct GNUNET_PeerIdentity));
852     ses->next = NULL;
853     ses->is_active = GNUNET_YES;
854
855     /* Insert session into linked list */
856     if ( plugin->sessions == NULL)
857     {
858       plugin->sessions = ses;
859       plugin->session_count = 1;
860     }
861     ses_temp = plugin->sessions;
862     while ( ses_temp->next != NULL )
863     {
864       ses_temp = ses_temp->next;
865     }
866     if (ses_temp != ses )
867     {
868       ses_temp->next = ses;
869       plugin->session_count++;
870     }
871     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"New Session `%s' inserted, count %u \n", GNUNET_i2s(target), plugin->session_count);
872   }
873
874   curl_handle = curl_easy_init();
875   if( NULL == curl_handle)
876   {
877     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Getting cURL handle failed\n");
878     return -1;
879   }
880
881   char * url;
882   GNUNET_asprintf(&url,"http://%s:%u/%s",ses->ip,ses->addr->sin_port,ses->hash);
883   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"url: %s\n",url);
884
885   curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
886   curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION, send_read_callback);
887   curl_easy_setopt(curl_handle, CURLOPT_UPLOAD, 1L);
888   curl_easy_setopt(curl_handle, CURLOPT_PUT, 1L);
889   curl_easy_setopt(curl_handle, CURLOPT_URL, url);
890   curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, (timeout.value / 1000 ));
891   curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
892   curl_easy_setopt(curl_handle, CURLOPT_READDATA, msgbuf);
893   curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE_LARGE,
894                   (curl_off_t)msgbuf_size);
895
896   mret = curl_multi_add_handle(multi_handle, curl_handle);
897   if (mret != CURLM_OK)
898   {
899     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
900                 _("%s failed at %s:%d: `%s'\n"),
901                 "curl_multi_add_handle", __FILE__, __LINE__,
902                 curl_multi_strerror (mret));
903     return -1;
904   }
905
906   bytes_sent = send_prepare (ses );
907   return bytes_sent;
908 }
909
910
911
912 /**
913  * Function that can be used to force the plugin to disconnect
914  * from the given peer and cancel all previous transmissions
915  * (and their continuationc).
916  *
917  * @param cls closure
918  * @param target peer from which to disconnect
919  */
920 static void
921 http_plugin_disconnect (void *cls,
922                             const struct GNUNET_PeerIdentity *target)
923 {
924   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_disconnect\n");
925   // struct Plugin *plugin = cls;
926   // FIXME
927 }
928
929
930 /**
931  * Convert the transports address to a nice, human-readable
932  * format.
933  *
934  * @param cls closure
935  * @param type name of the transport that generated the address
936  * @param addr one of the addresses of the host, NULL for the last address
937  *        the specific address format depends on the transport
938  * @param addrlen length of the address
939  * @param numeric should (IP) addresses be displayed in numeric form?
940  * @param timeout after how long should we give up?
941  * @param asc function to call on each string
942  * @param asc_cls closure for asc
943  */
944 static void
945 http_plugin_address_pretty_printer (void *cls,
946                                         const char *type,
947                                         const void *addr,
948                                         size_t addrlen,
949                                         int numeric,
950                                         struct GNUNET_TIME_Relative timeout,
951                                         GNUNET_TRANSPORT_AddressStringCallback
952                                         asc, void *asc_cls)
953 {
954   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_address_pretty_printer\n");
955   asc (asc_cls, NULL);
956 }
957
958
959
960 /**
961  * Another peer has suggested an address for this
962  * peer and transport plugin.  Check that this could be a valid
963  * address.  If so, consider adding it to the list
964  * of addresses.
965  *
966  * @param cls closure
967  * @param addr pointer to the address
968  * @param addrlen length of addr
969  * @return GNUNET_OK if this is a plausible address for this peer
970  *         and transport
971  */
972 static int
973 http_plugin_address_suggested (void *cls,
974                                   void *addr, size_t addrlen)
975 {
976   /* struct Plugin *plugin = cls; */
977
978   /* check if the address is plausible; if so,
979      add it to our list! */
980   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_address_suggested\n");
981   return GNUNET_OK;
982 }
983
984
985 /**
986  * Function called for a quick conversion of the binary address to
987  * a numeric address.  Note that the caller must not free the
988  * address and that the next call to this function is allowed
989  * to override the address again.
990  *
991  * @param cls closure
992  * @param addr binary address
993  * @param addrlen length of the address
994  * @return string representing the same address
995  */
996 static const char*
997 http_plugin_address_to_string (void *cls,
998                                    const void *addr,
999                                    size_t addrlen)
1000 {
1001   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_address_to_string\n");
1002   GNUNET_break (0);
1003   return NULL;
1004 }
1005
1006 /**
1007  * Exit point from the plugin.
1008  */
1009 void *
1010 libgnunet_plugin_transport_http_done (void *cls)
1011 {
1012   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1013   struct Plugin *plugin = api->cls;
1014   struct Session * cs;
1015   struct Session * cs_next;
1016   CURLMcode mret;
1017
1018   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unloading http plugin...\n");
1019
1020   if ( http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1021   {
1022     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v4);
1023     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
1024   }
1025
1026   if ( http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1027   {
1028     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v6);
1029     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1030   }
1031
1032   if ( http_task_send != GNUNET_SCHEDULER_NO_TASK)
1033   {
1034     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_send);
1035     http_task_send = GNUNET_SCHEDULER_NO_TASK;
1036   }
1037
1038   if (http_daemon_v4 != NULL)
1039   {
1040     MHD_stop_daemon (http_daemon_v4);
1041     http_daemon_v4 = NULL;
1042   }
1043   if (http_daemon_v6 != NULL)
1044   {
1045     MHD_stop_daemon (http_daemon_v6);
1046     http_daemon_v6 = NULL;
1047   }
1048
1049   mret = curl_multi_cleanup(multi_handle);
1050   if ( CURLM_OK != mret)
1051     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed");
1052
1053   /* free all sessions */
1054   cs = plugin->sessions;
1055   while ( NULL != cs)
1056     {
1057       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing session to `%s'\n",cs->ip);
1058       cs_next = cs->next;
1059       GNUNET_free (cs->ip);
1060       GNUNET_free (cs->addr);
1061       GNUNET_free (cs);
1062       plugin->session_count--;
1063       cs = cs_next;
1064     }
1065
1066   /* GNUNET_SERVICE_stop (plugin->service); */
1067
1068   GNUNET_free (plugin);
1069   GNUNET_free (api);
1070   return NULL;
1071 }
1072
1073
1074 /**
1075  * Entry point for the plugin.
1076  */
1077 void *
1078 libgnunet_plugin_transport_http_init (void *cls)
1079 {
1080   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1081   struct GNUNET_TRANSPORT_PluginFunctions *api;
1082   struct GNUNET_SERVICE_Context *service;
1083   unsigned int timeout;
1084   struct GNUNET_TIME_Relative gn_timeout;
1085   long long unsigned int port;
1086
1087   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
1088
1089   service = NULL;
1090   /*
1091   service = GNUNET_SERVICE_start ("transport-http", env->sched, env->cfg);
1092   if (service == NULL)
1093     {
1094       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "", _
1095                        ("Failed to start service for `%s' transport plugin.\n"),
1096                        "http");
1097       return NULL;
1098     }
1099     */
1100
1101   plugin = GNUNET_malloc (sizeof (struct Plugin));
1102   plugin->env = env;
1103   plugin->sessions = NULL;
1104   plugin->service = service;
1105   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1106   api->cls = plugin;
1107   api->send = &http_plugin_send;
1108   api->disconnect = &http_plugin_disconnect;
1109   api->address_pretty_printer = &http_plugin_address_pretty_printer;
1110   api->check_address = &http_plugin_address_suggested;
1111   api->address_to_string = &http_plugin_address_to_string;
1112
1113   hostname = GNUNET_RESOLVER_local_fqdn_get ();
1114
1115   /* Hashing our identity to use it in URLs */
1116   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &my_ascii_hash_ident);
1117
1118   /* Reading port number from config file */
1119   if ((GNUNET_OK !=
1120        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1121                                               "transport-http",
1122                                               "PORT",
1123                                               &port)) ||
1124       (port > 65535) )
1125     {
1126       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1127                        "http",
1128                        _
1129                        ("Require valid port number for transport plugin `%s' in configuration!\n"),
1130                        "transport-http");
1131       libgnunet_plugin_transport_http_done (api);
1132       return NULL;
1133     }
1134
1135   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1136   timeout = ( gn_timeout.value / 1000);
1137   if ((http_daemon_v4 == NULL) && (http_daemon_v6 == NULL) && (port != 0))
1138     {
1139     http_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
1140                                        port,
1141                                        &acceptPolicyCallback,
1142                                        NULL , &accessHandlerCallback, NULL,
1143                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1144                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1145                                        MHD_OPTION_CONNECTION_TIMEOUT, timeout,
1146                                        /* FIXME: set correct limit */
1147                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1148                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1149                                        MHD_OPTION_END);
1150     http_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
1151                                        port,
1152                                        &acceptPolicyCallback,
1153                                        NULL , &accessHandlerCallback, NULL,
1154                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1155                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1156                                        MHD_OPTION_CONNECTION_TIMEOUT, timeout,
1157                                        /* FIXME: set correct limit */
1158                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1159                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1160                                        MHD_OPTION_END);
1161     }
1162   if (http_daemon_v4 != NULL)
1163     http_task_v4 = http_daemon_prepare (http_daemon_v4);
1164   if (http_daemon_v6 != NULL)
1165     http_task_v6 = http_daemon_prepare (http_daemon_v6);
1166
1167   if (http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1168     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
1169   if (http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1170     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
1171
1172   /* Initializing cURL */
1173   multi_handle = curl_multi_init();
1174   if ( NULL == multi_handle )
1175   {
1176     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1177                      "http",
1178                      _("Could not initialize curl multi handle, failed to start http plugin!\n"),
1179                      "transport-http");
1180     libgnunet_plugin_transport_http_done (api);
1181     return NULL;
1182   }
1183   return api;
1184 }
1185
1186 /* end of plugin_transport_template.c */