(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  *  Message to send using http
74  */
75 struct HTTP_Message
76 {
77   /**
78    * Next field for linked list
79    */
80   struct HTTP_Message * next;
81
82   /**
83    * buffer containing data to send
84    */
85   char *buf;
86
87   /**
88    * amount of data already sent
89    */
90   size_t pos;
91
92   /**
93    * amount of data to sent
94    */
95   size_t size;
96
97   size_t len;
98 };
99
100
101 /**
102  * Session handle for connections.
103  */
104 struct Session
105 {
106
107   /**
108    * Stored in a linked list.
109    */
110   struct Session *next;
111
112   /**
113    * Pointer to the global plugin struct.
114    */
115   struct Plugin *plugin;
116
117   /**
118    * Continuation function to call once the transmission buffer
119    * has again space available.  NULL if there is no
120    * continuation to call.
121    */
122   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
123
124   /**
125    * Closure for transmit_cont.
126    */
127   void *transmit_cont_cls;
128
129   /**
130    * To whom are we talking to (set to our identity
131    * if we are still waiting for the welcome message)
132    */
133   struct GNUNET_PeerIdentity sender;
134
135   /**
136    * Sender's url
137    */
138   char * url;
139
140   /**
141    * Sender's ip address to distinguish between incoming connections
142    */
143   char * ip;
144
145   /**
146    * Sender's ip address to distinguish between incoming connections
147    */
148   struct sockaddr_in * addr;
149
150   /**
151    * Did we initiate the connection (GNUNET_YES) or the other peer (GNUNET_NO)?
152    */
153   unsigned int is_client;
154
155   /**
156    * Is the connection active (GNUNET_YES) or terminated (GNUNET_NO)?
157    */
158   unsigned int is_active;
159
160   /**
161    * At what time did we reset last_received last?
162    */
163   struct GNUNET_TIME_Absolute last_quota_update;
164
165   /**
166    * How many bytes have we received since the "last_quota_update"
167    * timestamp?
168    */
169   uint64_t last_received;
170
171   /**
172    * Number of bytes per ms that this peer is allowed
173    * to send to us.
174    */
175   uint32_t quota;
176
177   /**
178    * Is there a HTTP/PUT in progress?
179    */
180   unsigned int is_put_in_progress;
181
182   /**
183    * Encoded hash
184    */
185   struct GNUNET_CRYPTO_HashAsciiEncoded hash;
186
187   struct HTTP_Message * pending_outbound_msg;;
188
189   CURL *curl_handle;
190 };
191
192 /**
193  * Encapsulation of all of the state of the plugin.
194  */
195 struct Plugin
196 {
197   /**
198    * Our environment.
199    */
200   struct GNUNET_TRANSPORT_PluginEnvironment *env;
201
202   /**
203    * Handle to the network service.
204    */
205   struct GNUNET_SERVICE_Context *service;
206
207   /**
208    * List of open sessions.
209    */
210   struct Session *sessions;
211
212   /**
213    * Number of active sessions
214    */
215
216   unsigned int session_count;
217 };
218
219 /**
220  * Daemon for listening for new IPv4 connections.
221  */
222 static struct MHD_Daemon *http_daemon_v4;
223
224 /**
225  * Daemon for listening for new IPv6connections.
226  */
227 static struct MHD_Daemon *http_daemon_v6;
228
229 /**
230  * Our primary task for http daemon handling IPv4 connections
231  */
232 static GNUNET_SCHEDULER_TaskIdentifier http_task_v4;
233
234 /**
235  * Our primary task for http daemon handling IPv6 connections
236  */
237 static GNUNET_SCHEDULER_TaskIdentifier http_task_v6;
238
239
240 /**
241  * Our primary task for http daemon handling IPv6 connections
242  */
243 static GNUNET_SCHEDULER_TaskIdentifier http_task_send;
244
245
246 /**
247  * Information about this plugin
248  */
249 static struct Plugin *plugin;
250
251 /**
252  * cURL Multihandle
253  */
254 static CURLM *multi_handle;
255
256 /**
257  * Our hostname
258  */
259 static char * hostname;
260
261 /**
262  * Our ASCII encoded, hashed peer identity
263  * This string is used to distinguish between connections and is added to the urls
264  */
265 static struct GNUNET_CRYPTO_HashAsciiEncoded my_ascii_hash_ident;
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         send_error_to_client = GNUNET_YES;
520       }
521
522       if ( GNUNET_YES == send_error_to_client)
523       {
524         response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
525         res = MHD_queue_response (session, MHD_HTTP_BAD_REQUEST, response);
526         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 );
527         MHD_destroy_response (response);
528         GNUNET_free (gn_msg);
529         return MHD_NO;
530       }
531       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));
532
533       /* forwarding message to transport */
534       plugin->env->receive(plugin->env, &(cs->sender), gn_msg, 1, cs , cs->ip, strlen(cs->ip) );
535       return MHD_YES;
536     }
537     if ((*upload_data_size == 0) && (cs->is_put_in_progress == GNUNET_YES))
538     {
539       cs->is_put_in_progress = GNUNET_NO;
540       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
541       res = MHD_queue_response (session, MHD_HTTP_OK, response);
542       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Sent HTTP/1.1: 200 OK as PUT Response\n",HTTP_PUT_RESPONSE, strlen (HTTP_PUT_RESPONSE), res );
543       MHD_destroy_response (response);
544       return res;
545     }
546   }
547   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
548   {
549     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request\n");
550     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"URL: `%s'\n",url);
551     response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
552     res = MHD_queue_response (session, MHD_HTTP_OK, response);
553     MHD_destroy_response (response);
554     return res;
555   }
556   return MHD_NO;
557 }
558
559
560 /**
561  * Call MHD to process pending requests and then go back
562  * and schedule the next run.
563  */
564 static void http_daemon_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
565
566 /**
567  * Function that queries MHD's select sets and
568  * starts the task waiting for them.
569  */
570 static GNUNET_SCHEDULER_TaskIdentifier
571 http_daemon_prepare (struct MHD_Daemon *daemon_handle)
572 {
573   GNUNET_SCHEDULER_TaskIdentifier ret;
574   fd_set rs;
575   fd_set ws;
576   fd_set es;
577   struct GNUNET_NETWORK_FDSet *wrs;
578   struct GNUNET_NETWORK_FDSet *wws;
579   struct GNUNET_NETWORK_FDSet *wes;
580   int max;
581   unsigned long long timeout;
582   int haveto;
583   struct GNUNET_TIME_Relative tv;
584
585   FD_ZERO(&rs);
586   FD_ZERO(&ws);
587   FD_ZERO(&es);
588   wrs = GNUNET_NETWORK_fdset_create ();
589   wes = GNUNET_NETWORK_fdset_create ();
590   wws = GNUNET_NETWORK_fdset_create ();
591   max = -1;
592   GNUNET_assert (MHD_YES ==
593                  MHD_get_fdset (daemon_handle,
594                                 &rs,
595                                 &ws,
596                                 &es,
597                                 &max));
598   haveto = MHD_get_timeout (daemon_handle, &timeout);
599   if (haveto == MHD_YES)
600     tv.value = (uint64_t) timeout;
601   else
602     tv = GNUNET_TIME_UNIT_FOREVER_REL;
603   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
604   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
605   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
606   ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
607                                      GNUNET_SCHEDULER_PRIORITY_HIGH,
608                                      GNUNET_SCHEDULER_NO_TASK,
609                                      tv,
610                                      wrs,
611                                      wws,
612                                      &http_daemon_run,
613                                      daemon_handle);
614   GNUNET_NETWORK_fdset_destroy (wrs);
615   GNUNET_NETWORK_fdset_destroy (wws);
616   GNUNET_NETWORK_fdset_destroy (wes);
617   return ret;
618 }
619
620 /**
621  * Call MHD to process pending requests and then go back
622  * and schedule the next run.
623  */
624 static void
625 http_daemon_run (void *cls,
626             const struct GNUNET_SCHEDULER_TaskContext *tc)
627 {
628   struct MHD_Daemon *daemon_handle = cls;
629
630   if (daemon_handle == http_daemon_v4)
631     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
632
633   if (daemon_handle == http_daemon_v6)
634     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
635
636   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
637     return;
638
639
640
641   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
642   if (daemon_handle == http_daemon_v4)
643     http_task_v4 = http_daemon_prepare (daemon_handle);
644   if (daemon_handle == http_daemon_v6)
645     http_task_v6 = http_daemon_prepare (daemon_handle);
646   return;
647 }
648
649 /**
650  * Removes a message from the linked list of messages
651  */
652
653 static int remove_http_message(struct Session * ses, struct HTTP_Message * msg)
654 {
655   struct HTTP_Message * cur;
656   struct HTTP_Message * next;
657
658   cur = ses->pending_outbound_msg;
659   next = NULL;
660
661   if (cur == NULL)
662     return GNUNET_SYSERR;
663
664   if (cur == msg)
665   {
666     ses->pending_outbound_msg = cur->next;
667     GNUNET_free (cur->buf);
668     GNUNET_free (cur);
669     return GNUNET_OK;
670   }
671
672   while (cur->next!=msg)
673   {
674     if (cur->next != NULL)
675       cur = cur->next;
676     else
677       return GNUNET_SYSERR;
678   }
679
680   cur->next = cur->next->next;
681   GNUNET_free (cur->next->buf);
682   GNUNET_free (cur->next);
683   return GNUNET_OK;
684
685
686 }
687
688 static size_t send_read_callback(void *stream, size_t size, size_t nmemb, void *ptr)
689 {
690   struct Session * ses = ptr;
691   struct HTTP_Message * msg = ses->pending_outbound_msg;
692   unsigned int bytes_sent;
693
694   bytes_sent = 0;
695   if (msg->len > (size * nmemb))
696     return CURL_READFUNC_ABORT;
697
698   if (( msg->pos < msg->len) && (msg->len < (size * nmemb)))
699   {
700     memcpy(stream, msg->buf, msg->len);
701     msg->pos = msg->len;
702     bytes_sent = msg->len;
703   }
704
705   return bytes_sent;
706 }
707
708
709 static size_t send_prepare(struct Session* session );
710
711 static void send_execute (void *cls,
712              const struct GNUNET_SCHEDULER_TaskContext *tc)
713 {
714   int running;
715   struct CURLMsg *msg;
716   CURLMcode mret;
717   struct Session * cs = cls;
718
719   http_task_send = GNUNET_SCHEDULER_NO_TASK;
720   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
721     return;
722
723   do
724     {
725       running = 0;
726       mret = curl_multi_perform (multi_handle, &running);
727       //GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"send_execute %u\n", running);
728       if (running == 0)
729         {
730           do
731             {
732
733               msg = curl_multi_info_read (multi_handle, &running);
734               GNUNET_break (msg != NULL);
735               if (msg == NULL)
736                 break;
737               switch (msg->msg)
738                 {
739                 case CURLMSG_DONE:
740                   if ( (msg->data.result != CURLE_OK) &&
741                        (msg->data.result != CURLE_GOT_NOTHING) )
742                     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
743                                _("%s failed for `%s' at %s:%d: `%s'\n"),
744                                "curl_multi_perform",
745                                cs->ip,
746                                __FILE__,
747                                __LINE__,
748                                curl_easy_strerror (msg->data.result));
749                   else
750                     {
751                     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
752                                 "Send to %s completed.\n", cs->ip);
753                     if (GNUNET_OK != remove_http_message(cs, cs->pending_outbound_msg))
754                         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message could not be removed from session `%s'", GNUNET_i2s(&cs->sender));
755
756                     curl_easy_cleanup(cs->curl_handle);
757                     cs->curl_handle=NULL;
758
759                     /* Calling transmit continuation  */
760                     if ( NULL != cs->transmit_cont)
761                       cs->transmit_cont (NULL,&cs->sender,GNUNET_OK);
762                     }
763                   return;
764                 default:
765                   break;
766                 }
767
768             }
769           while ( (running > 0) );
770         }
771     }
772   while (mret == CURLM_CALL_MULTI_PERFORM);
773   send_prepare(cls);
774 }
775
776
777 static size_t send_prepare(struct Session* session )
778 {
779   fd_set rs;
780   fd_set ws;
781   fd_set es;
782   int max;
783   struct GNUNET_NETWORK_FDSet *grs;
784   struct GNUNET_NETWORK_FDSet *gws;
785   long to;
786   CURLMcode mret;
787
788 //  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"send_prepare\n");
789   max = -1;
790   FD_ZERO (&rs);
791   FD_ZERO (&ws);
792   FD_ZERO (&es);
793   mret = curl_multi_fdset (multi_handle, &rs, &ws, &es, &max);
794   if (mret != CURLM_OK)
795     {
796       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
797                   _("%s failed at %s:%d: `%s'\n"),
798                   "curl_multi_fdset", __FILE__, __LINE__,
799                   curl_multi_strerror (mret));
800       return -1;
801     }
802   mret = curl_multi_timeout (multi_handle, &to);
803   if (mret != CURLM_OK)
804     {
805       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
806                   _("%s failed at %s:%d: `%s'\n"),
807                   "curl_multi_timeout", __FILE__, __LINE__,
808                   curl_multi_strerror (mret));
809       return -1;
810     }
811
812   grs = GNUNET_NETWORK_fdset_create ();
813   gws = GNUNET_NETWORK_fdset_create ();
814   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
815   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
816   http_task_send = GNUNET_SCHEDULER_add_select (plugin->env->sched,
817                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
818                                    GNUNET_SCHEDULER_NO_TASK,
819                                    GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 0),
820                                    grs,
821                                    gws,
822                                    &send_execute,
823                                    session);
824   GNUNET_NETWORK_fdset_destroy (gws);
825   GNUNET_NETWORK_fdset_destroy (grs);
826
827   /* FIXME: return bytes REALLY sent */
828   return 0;
829 }
830
831
832 /**
833  * Function that can be used by the transport service to transmit
834  * a message using the plugin.
835  *
836  * @param cls closure
837  * @param target who should receive this message
838  * @param priority how important is the message
839  * @param msgbuf the message to transmit
840  * @param msgbuf_size number of bytes in 'msgbuf'
841  * @param timeout when should we time out
842  * @param session which session must be used (or NULL for "any")
843  * @param addr the address to use (can be NULL if the plugin
844  *                is "on its own" (i.e. re-use existing TCP connection))
845  * @param addrlen length of the address in bytes
846  * @param force_address GNUNET_YES if the plugin MUST use the given address,
847  *                otherwise the plugin may use other addresses or
848  *                existing connections (if available)
849  * @param cont continuation to call once the message has
850  *        been transmitted (or if the transport is ready
851  *        for the next transmission call; or if the
852  *        peer disconnected...)
853  * @param cont_cls closure for cont
854  * @return number of bytes used (on the physical network, with overheads);
855  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
856  *         and does NOT mean that the message was not transmitted (DV)
857  */
858 static ssize_t
859 http_plugin_send (void *cls,
860                       const struct GNUNET_PeerIdentity *target,
861                       const char *msgbuf,
862                       size_t msgbuf_size,
863                       unsigned int priority,
864                       struct GNUNET_TIME_Relative timeout,
865                       struct Session *session,
866                       const void *addr,
867                       size_t addrlen,
868                       int force_address,
869                       GNUNET_TRANSPORT_TransmitContinuation cont,
870                       void *cont_cls)
871 {
872   struct Session* ses;
873   struct Session* ses_temp;
874   struct HTTP_Message * msg;
875   struct HTTP_Message * tmp;
876   int bytes_sent = 0;
877   CURLMcode mret;
878   char * url;
879
880   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Transport told plugin to send to peer `%s'\n",GNUNET_i2s(target));
881
882   /* find session for peer */
883   ses = find_session_by_pi (target);
884   if (NULL != ses )
885     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Existing session for peer `%s' found\n", GNUNET_i2s(target));
886   if ( ses == NULL)
887   {
888     /* create new session object */
889
890     /*FIXME: what is const void * really? Assuming struct sockaddr_in * ! */
891     ses = create_session((struct sockaddr_in *) addr, target);
892     ses->is_active = GNUNET_YES;
893     ses->transmit_cont = cont;
894
895     /* Insert session into linked list */
896     if ( plugin->sessions == NULL)
897     {
898       plugin->sessions = ses;
899       plugin->session_count = 1;
900     }
901     ses_temp = plugin->sessions;
902     while ( ses_temp->next != NULL )
903     {
904       ses_temp = ses_temp->next;
905     }
906     if (ses_temp != ses )
907     {
908       ses_temp->next = ses;
909       plugin->session_count++;
910     }
911     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"New Session `%s' inserted, count %u \n", GNUNET_i2s(target), plugin->session_count);
912   }
913
914   ses->curl_handle = curl_easy_init();
915   if( NULL == ses->curl_handle)
916   {
917     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Getting cURL handle failed\n");
918     return -1;
919   }
920
921   url = GNUNET_malloc( 7 + strlen(ses->ip) + 7 + strlen ((char *) &(ses->hash)) + 1);
922   /* FIXME: use correct port number */
923   GNUNET_asprintf(&url,"http://%s:%u/%s",ses->ip,12389, (char *) &(ses->hash));
924
925   if ( NULL != cont)
926     ses->transmit_cont = cont;
927
928   /* setting up message */
929   msg = GNUNET_malloc (sizeof (struct HTTP_Message));
930   msg->next = NULL;
931   msg->len = msgbuf_size;
932   msg->pos = 0;
933   msg->buf = GNUNET_malloc (msgbuf_size);
934   memcpy (msg->buf,msgbuf, msgbuf_size);
935
936   /* insert created message in list of pending messages */
937
938   if (ses->pending_outbound_msg == NULL)
939   {
940     ses->pending_outbound_msg = msg;
941   }
942   tmp = ses->pending_outbound_msg;
943   while ( NULL != tmp->next)
944   {
945     tmp = tmp->next;
946   }
947   if ( tmp != msg)
948     tmp->next = msg;
949
950   struct HTTP_Message * msg2 = GNUNET_malloc (sizeof (struct HTTP_Message));
951
952   if (ses->pending_outbound_msg == NULL)
953   {
954     ses->pending_outbound_msg = msg2;
955   }
956   tmp = ses->pending_outbound_msg;
957   while ( NULL != tmp->next)
958   {
959     tmp = tmp->next;
960   }
961   if ( tmp != msg2)
962     tmp->next = msg2;
963
964   /* curl_easy_setopt(ses->curl_handle, CURLOPT_VERBOSE, 1L); */
965   curl_easy_setopt(ses->curl_handle, CURLOPT_URL, url);
966   curl_easy_setopt(ses->curl_handle, CURLOPT_PUT, 1L);
967   curl_easy_setopt(ses->curl_handle, CURLOPT_READFUNCTION, send_read_callback);
968   curl_easy_setopt(ses->curl_handle, CURLOPT_READDATA, ses);
969   curl_easy_setopt(ses->curl_handle, CURLOPT_INFILESIZE_LARGE, (curl_off_t) msg->len);
970   curl_easy_setopt(ses->curl_handle, CURLOPT_TIMEOUT, (timeout.value / 1000 ));
971   curl_easy_setopt(ses->curl_handle, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
972
973   mret = curl_multi_add_handle(multi_handle, ses->curl_handle);
974   if (mret != CURLM_OK)
975   {
976     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
977                 _("%s failed at %s:%d: `%s'\n"),
978                 "curl_multi_add_handle", __FILE__, __LINE__,
979                 curl_multi_strerror (mret));
980     return -1;
981   }
982   bytes_sent = send_prepare (ses );
983   GNUNET_free ( url );
984   return bytes_sent;
985 }
986
987
988
989 /**
990  * Function that can be used to force the plugin to disconnect
991  * from the given peer and cancel all previous transmissions
992  * (and their continuationc).
993  *
994  * @param cls closure
995  * @param target peer from which to disconnect
996  */
997 static void
998 http_plugin_disconnect (void *cls,
999                             const struct GNUNET_PeerIdentity *target)
1000 {
1001   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_disconnect\n");
1002   // struct Plugin *plugin = cls;
1003   // FIXME
1004 }
1005
1006
1007 /**
1008  * Convert the transports address to a nice, human-readable
1009  * format.
1010  *
1011  * @param cls closure
1012  * @param type name of the transport that generated the address
1013  * @param addr one of the addresses of the host, NULL for the last address
1014  *        the specific address format depends on the transport
1015  * @param addrlen length of the address
1016  * @param numeric should (IP) addresses be displayed in numeric form?
1017  * @param timeout after how long should we give up?
1018  * @param asc function to call on each string
1019  * @param asc_cls closure for asc
1020  */
1021 static void
1022 http_plugin_address_pretty_printer (void *cls,
1023                                         const char *type,
1024                                         const void *addr,
1025                                         size_t addrlen,
1026                                         int numeric,
1027                                         struct GNUNET_TIME_Relative timeout,
1028                                         GNUNET_TRANSPORT_AddressStringCallback
1029                                         asc, void *asc_cls)
1030 {
1031   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_address_pretty_printer\n");
1032   asc (asc_cls, NULL);
1033 }
1034
1035
1036
1037 /**
1038  * Another peer has suggested an address for this
1039  * peer and transport plugin.  Check that this could be a valid
1040  * address.  If so, consider adding it to the list
1041  * of addresses.
1042  *
1043  * @param cls closure
1044  * @param addr pointer to the address
1045  * @param addrlen length of addr
1046  * @return GNUNET_OK if this is a plausible address for this peer
1047  *         and transport
1048  */
1049 static int
1050 http_plugin_address_suggested (void *cls,
1051                                   void *addr, size_t addrlen)
1052 {
1053   /* struct Plugin *plugin = cls; */
1054
1055   /* check if the address is plausible; if so,
1056      add it to our list! */
1057   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_address_suggested\n");
1058   return GNUNET_OK;
1059 }
1060
1061
1062 /**
1063  * Function called for a quick conversion of the binary address to
1064  * a numeric address.  Note that the caller must not free the
1065  * address and that the next call to this function is allowed
1066  * to override the address again.
1067  *
1068  * @param cls closure
1069  * @param addr binary address
1070  * @param addrlen length of the address
1071  * @return string representing the same address
1072  */
1073 static const char*
1074 http_plugin_address_to_string (void *cls,
1075                                    const void *addr,
1076                                    size_t addrlen)
1077 {
1078   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_address_to_string\n");
1079   GNUNET_break (0);
1080   return NULL;
1081 }
1082
1083 /**
1084  * Exit point from the plugin.
1085  */
1086 void *
1087 libgnunet_plugin_transport_http_done (void *cls)
1088 {
1089   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1090   struct Plugin *plugin = api->cls;
1091   struct Session * cs;
1092   struct Session * cs_next;
1093   CURLMcode mret;
1094
1095   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unloading http plugin...\n");
1096
1097   if ( http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1098   {
1099     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v4);
1100     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
1101   }
1102
1103   if ( http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1104   {
1105     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v6);
1106     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1107   }
1108
1109   if ( http_task_send != GNUNET_SCHEDULER_NO_TASK)
1110   {
1111     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_send);
1112     http_task_send = GNUNET_SCHEDULER_NO_TASK;
1113   }
1114
1115   if (http_daemon_v4 != NULL)
1116   {
1117     MHD_stop_daemon (http_daemon_v4);
1118     http_daemon_v4 = NULL;
1119   }
1120   if (http_daemon_v6 != NULL)
1121   {
1122     MHD_stop_daemon (http_daemon_v6);
1123     http_daemon_v6 = NULL;
1124   }
1125
1126   mret = curl_multi_cleanup(multi_handle);
1127   if ( CURLM_OK != mret)
1128     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed");
1129
1130   /* free all sessions */
1131   cs = plugin->sessions;
1132
1133   while ( NULL != cs)
1134     {
1135       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing session to `%s'\n",cs->ip);
1136
1137       cs_next = cs->next;
1138       /* freeing messages */
1139       struct HTTP_Message *cur;
1140       struct HTTP_Message *tmp;
1141       cur = cs->pending_outbound_msg;
1142
1143       while (cur != NULL)
1144       {
1145          tmp = cur->next;
1146          GNUNET_free (cur->buf);
1147          GNUNET_free (cur);
1148          cur = tmp;
1149       }
1150
1151
1152       GNUNET_free (cs->ip);
1153       GNUNET_free (cs->addr);
1154       GNUNET_free (cs);
1155       plugin->session_count--;
1156       cs = cs_next;
1157
1158     }
1159
1160   /* GNUNET_SERVICE_stop (plugin->service); */
1161   GNUNET_free (plugin);
1162   GNUNET_free (api);
1163   return NULL;
1164 }
1165
1166
1167 /**
1168  * Entry point for the plugin.
1169  */
1170 void *
1171 libgnunet_plugin_transport_http_init (void *cls)
1172 {
1173   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1174   struct GNUNET_TRANSPORT_PluginFunctions *api;
1175   struct GNUNET_SERVICE_Context *service;
1176   unsigned int timeout;
1177   struct GNUNET_TIME_Relative gn_timeout;
1178   long long unsigned int port;
1179
1180   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
1181
1182   service = NULL;
1183   /*
1184   service = GNUNET_SERVICE_start ("transport-http", env->sched, env->cfg);
1185   if (service == NULL)
1186     {
1187       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "", _
1188                        ("Failed to start service for `%s' transport plugin.\n"),
1189                        "http");
1190       return NULL;
1191     }
1192     */
1193
1194   plugin = GNUNET_malloc (sizeof (struct Plugin));
1195   plugin->env = env;
1196   plugin->sessions = NULL;
1197   plugin->service = service;
1198   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1199   api->cls = plugin;
1200   api->send = &http_plugin_send;
1201   api->disconnect = &http_plugin_disconnect;
1202   api->address_pretty_printer = &http_plugin_address_pretty_printer;
1203   api->check_address = &http_plugin_address_suggested;
1204   api->address_to_string = &http_plugin_address_to_string;
1205
1206   hostname = GNUNET_RESOLVER_local_fqdn_get ();
1207
1208   /* Hashing our identity to use it in URLs */
1209   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &my_ascii_hash_ident);
1210
1211   /* Reading port number from config file */
1212   if ((GNUNET_OK !=
1213        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1214                                               "transport-http",
1215                                               "PORT",
1216                                               &port)) ||
1217       (port > 65535) )
1218     {
1219       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1220                        "http",
1221                        _
1222                        ("Require valid port number for transport plugin `%s' in configuration!\n"),
1223                        "transport-http");
1224       libgnunet_plugin_transport_http_done (api);
1225       return NULL;
1226     }
1227
1228   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1229   timeout = ( gn_timeout.value / 1000);
1230   if ((http_daemon_v4 == NULL) && (http_daemon_v6 == NULL) && (port != 0))
1231     {
1232     http_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
1233                                        port,
1234                                        &acceptPolicyCallback,
1235                                        NULL , &accessHandlerCallback, NULL,
1236                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1237                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1238                                        MHD_OPTION_CONNECTION_TIMEOUT, timeout,
1239                                        /* FIXME: set correct limit */
1240                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1241                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1242                                        MHD_OPTION_END);
1243     http_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
1244                                        port,
1245                                        &acceptPolicyCallback,
1246                                        NULL , &accessHandlerCallback, NULL,
1247                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1248                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1249                                        MHD_OPTION_CONNECTION_TIMEOUT, timeout,
1250                                        /* FIXME: set correct limit */
1251                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1252                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1253                                        MHD_OPTION_END);
1254     }
1255   if (http_daemon_v4 != NULL)
1256     http_task_v4 = http_daemon_prepare (http_daemon_v4);
1257   if (http_daemon_v6 != NULL)
1258     http_task_v6 = http_daemon_prepare (http_daemon_v6);
1259
1260   if (http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1261     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
1262   if (http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1263     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
1264
1265   /* Initializing cURL */
1266   multi_handle = curl_multi_init();
1267   if ( NULL == multi_handle )
1268   {
1269     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1270                      "http",
1271                      _("Could not initialize curl multi handle, failed to start http plugin!\n"),
1272                      "transport-http");
1273     libgnunet_plugin_transport_http_done (api);
1274     return NULL;
1275   }
1276   return api;
1277 }
1278
1279 /* end of plugin_transport_template.c */