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