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