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