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