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