(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 GNUNET_MessageHeader *gn_msg;
384
385   gn_msg = NULL;
386
387   if ( NULL == *httpSessionCache)
388   {
389     /* check url for peer identity */
390     res = GNUNET_CRYPTO_hash_from_string ( &url[1], &(pi_in.hashPubKey));
391     if ( GNUNET_SYSERR == res )
392     {
393       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident\n");
394       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
395       res = MHD_queue_response (session, MHD_HTTP_NOT_FOUND, response);
396       MHD_destroy_response (response);
397       return res;
398     }
399     conn_info = MHD_get_connection_info(session, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
400     /* Incoming IPv4 connection */
401     if ( AF_INET == conn_info->client_addr->sin_family)
402     {
403       address = GNUNET_malloc (INET_ADDRSTRLEN);
404       addrin = conn_info->client_addr;
405       inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
406     }
407     /* Incoming IPv6 connection */
408     if ( AF_INET6 == conn_info->client_addr->sin_family)
409     {
410       address = GNUNET_malloc (INET6_ADDRSTRLEN);
411       addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
412       inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
413     }
414     /* find existing session for address */
415     cs = NULL;
416     if (plugin->session_count > 0)
417     {
418       cs = plugin->sessions;
419       while ( NULL != cs)
420       {
421
422         /* Comparison based on ip address */
423         // res = (0 == memcmp(&(conn_info->client_addr->sin_addr),&(cs->addr->sin_addr), sizeof (struct in_addr))) ? GNUNET_YES : GNUNET_NO;
424
425         /* Comparison based on ip address, port number and address family */
426         // res = (0 == memcmp((conn_info->client_addr),(cs->addr), sizeof (struct sockaddr_in))) ? GNUNET_YES : GNUNET_NO;
427
428         /* Comparison based on PeerIdentity */
429         res = (0 == memcmp(&pi_in,&(cs->sender), sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_YES : GNUNET_NO;
430
431         if ( GNUNET_YES  == res)
432         {
433           /* existing session for this address found */
434           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session `%s' found\n",address);
435           break;
436         }
437         cs = cs->next;
438       }
439     }
440     /* no existing session, create a new one*/
441     if (cs == NULL )
442     {
443       /* create new session object */
444       cs = GNUNET_malloc ( sizeof( struct Session) );
445       cs->addr = GNUNET_malloc ( sizeof (struct sockaddr_in) );
446
447       cs->ip = address;
448       memcpy(cs->addr, conn_info->client_addr, sizeof (struct sockaddr_in));
449       memcpy(&cs->sender, &pi_in, sizeof (struct GNUNET_PeerIdentity));
450       cs->next = NULL;
451       cs->is_active = GNUNET_YES;
452
453       /* Insert session into linked list */
454       if ( plugin->sessions == NULL)
455       {
456         plugin->sessions = cs;
457         plugin->session_count = 1;
458       }
459       cs_temp = plugin->sessions;
460       while ( cs_temp->next != NULL )
461       {
462         cs_temp = cs_temp->next;
463       }
464       if (cs_temp != cs )
465       {
466         cs_temp->next = cs;
467         plugin->session_count++;
468       }
469       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"New Session `%s' inserted, count %u \n", address, plugin->session_count);
470     }
471     /* Set closure */
472     if (*httpSessionCache == NULL)
473     {
474       *httpSessionCache = cs;
475     }
476     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);
477   }
478   else
479   {
480     cs = *httpSessionCache;
481   }
482   /* Is it a PUT or a GET request */
483   if ( 0 == strcmp (MHD_HTTP_METHOD_PUT, method) )
484   {
485     /* New  */
486     if ((*upload_data_size == 0) && (cs->is_put_in_progress == GNUNET_NO))
487     {
488       /* not yet ready */
489       cs->is_put_in_progress = GNUNET_YES;
490       return MHD_YES;
491     }
492     if ( *upload_data_size > 0 )
493     {
494       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"PUT URL: `%s'\n",url);
495       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"PUT Request: %lu bytes: `%s' \n", (*upload_data_size), upload_data);
496       /* No data left */
497       bytes_recv = *upload_data_size ;
498       *upload_data_size = 0;
499
500       /* checking size */
501       if (bytes_recv < sizeof (struct GNUNET_MessageHeader))
502       {
503         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Message too small, is %u bytes, has to be at least %u '\n",bytes_recv, sizeof(struct GNUNET_MessageHeader));
504         return MHD_NO;
505       }
506
507       if ( bytes_recv > GNUNET_SERVER_MAX_MESSAGE_SIZE)
508       {
509         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Message too big, is %u bytes, maximum %u '\n",bytes_recv, GNUNET_SERVER_MAX_MESSAGE_SIZE);
510         return MHD_NO;
511       }
512
513       struct GNUNET_MessageHeader * gn_msg = GNUNET_malloc (bytes_recv);
514       memcpy (gn_msg,upload_data,bytes_recv);
515
516       if ( ntohs(gn_msg->size) != bytes_recv )
517       {
518         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Message has incorrect size, is %u bytes vs %u recieved'\n",ntohs(gn_msg->size) , bytes_recv);
519         GNUNET_free (gn_msg);
520         return MHD_NO;
521       }
522
523       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Message size: `%u'\n",ntohs (gn_msg->size));
524       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Message type: `%u'\n",ntohs (gn_msg->type));
525       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Data load : `%u'\n",ntohs (gn_msg->size)-sizeof(struct GNUNET_MessageHeader));
526
527       /* forwarding message to transport */
528       plugin->env->receive(plugin->env, &(cs->sender), gn_msg, 1, cs , cs->ip, strlen(cs->ip) );
529       return MHD_YES;
530     }
531     if ((*upload_data_size == 0) && (cs->is_put_in_progress == GNUNET_YES))
532     {
533       cs->is_put_in_progress = GNUNET_NO;
534       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
535       res = MHD_queue_response (session, MHD_HTTP_OK, response);
536       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Sent HTTP/1.1: 200 OK as PUT Response\n",HTTP_PUT_RESPONSE, strlen (HTTP_PUT_RESPONSE), res );
537       MHD_destroy_response (response);
538       return res;
539     }
540   }
541   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
542   {
543     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request\n");
544     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"URL: `%s'\n",url);
545     response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
546     res = MHD_queue_response (session, MHD_HTTP_OK, response);
547     MHD_destroy_response (response);
548     return res;
549   }
550   return MHD_NO;
551 }
552
553
554 /**
555  * Call MHD to process pending requests and then go back
556  * and schedule the next run.
557  */
558 static void http_daemon_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
559
560 /**
561  * Function that queries MHD's select sets and
562  * starts the task waiting for them.
563  */
564 static GNUNET_SCHEDULER_TaskIdentifier
565 http_daemon_prepare (struct MHD_Daemon *daemon_handle)
566 {
567   GNUNET_SCHEDULER_TaskIdentifier ret;
568   fd_set rs;
569   fd_set ws;
570   fd_set es;
571   struct GNUNET_NETWORK_FDSet *wrs;
572   struct GNUNET_NETWORK_FDSet *wws;
573   struct GNUNET_NETWORK_FDSet *wes;
574   int max;
575   unsigned long long timeout;
576   int haveto;
577   struct GNUNET_TIME_Relative tv;
578
579   FD_ZERO(&rs);
580   FD_ZERO(&ws);
581   FD_ZERO(&es);
582   wrs = GNUNET_NETWORK_fdset_create ();
583   wes = GNUNET_NETWORK_fdset_create ();
584   wws = GNUNET_NETWORK_fdset_create ();
585   max = -1;
586   GNUNET_assert (MHD_YES ==
587                  MHD_get_fdset (daemon_handle,
588                                 &rs,
589                                 &ws,
590                                 &es,
591                                 &max));
592   haveto = MHD_get_timeout (daemon_handle, &timeout);
593   if (haveto == MHD_YES)
594     tv.value = (uint64_t) timeout;
595   else
596     tv = GNUNET_TIME_UNIT_FOREVER_REL;
597   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
598   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
599   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
600   ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
601                                      GNUNET_SCHEDULER_PRIORITY_HIGH,
602                                      GNUNET_SCHEDULER_NO_TASK,
603                                      tv,
604                                      wrs,
605                                      wws,
606                                      &http_daemon_run,
607                                      daemon_handle);
608   GNUNET_NETWORK_fdset_destroy (wrs);
609   GNUNET_NETWORK_fdset_destroy (wws);
610   GNUNET_NETWORK_fdset_destroy (wes);
611   return ret;
612 }
613
614 /**
615  * Call MHD to process pending requests and then go back
616  * and schedule the next run.
617  */
618 static void
619 http_daemon_run (void *cls,
620             const struct GNUNET_SCHEDULER_TaskContext *tc)
621 {
622   struct MHD_Daemon *daemon_handle = cls;
623
624   if (daemon_handle == http_daemon_v4)
625     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
626
627   if (daemon_handle == http_daemon_v6)
628     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
629
630   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
631     return;
632
633
634
635   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
636   if (daemon_handle == http_daemon_v4)
637     http_task_v4 = http_daemon_prepare (daemon_handle);
638   if (daemon_handle == http_daemon_v6)
639     http_task_v6 = http_daemon_prepare (daemon_handle);
640   return;
641 }
642
643 static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
644 {
645   unsigned int len;
646
647   struct CBC  * cbc = ptr;
648
649   len = strlen(cbc->buf);
650
651   if (( cbc->pos == len) && (len < (size * nmemb)))
652     return 0;
653   memcpy(stream, cbc->buf, len+1);
654   cbc->pos = len;
655   return len;
656 }
657
658 /**
659  * Function that can be used by the transport service to transmit
660  * a message using the plugin.
661  *
662  * @param cls closure
663  * @param target who should receive this message
664  * @param priority how important is the message
665  * @param msgbuf the message to transmit
666  * @param msgbuf_size number of bytes in 'msgbuf'
667  * @param timeout when should we time out
668  * @param session which session must be used (or NULL for "any")
669  * @param addr the address to use (can be NULL if the plugin
670  *                is "on its own" (i.e. re-use existing TCP connection))
671  * @param addrlen length of the address in bytes
672  * @param force_address GNUNET_YES if the plugin MUST use the given address,
673  *                otherwise the plugin may use other addresses or
674  *                existing connections (if available)
675  * @param cont continuation to call once the message has
676  *        been transmitted (or if the transport is ready
677  *        for the next transmission call; or if the
678  *        peer disconnected...)
679  * @param cont_cls closure for cont
680  * @return number of bytes used (on the physical network, with overheads);
681  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
682  *         and does NOT mean that the message was not transmitted (DV)
683  */
684 static ssize_t
685 http_plugin_send (void *cls,
686                       const struct GNUNET_PeerIdentity *
687                       target,
688                       const char *msgbuf,
689                       size_t msgbuf_size,
690                       unsigned int priority,
691                       struct GNUNET_TIME_Relative timeout,
692                       struct Session *session,
693                       const void *addr,
694                       size_t addrlen,
695                       int force_address,
696                       GNUNET_TRANSPORT_TransmitContinuation
697                       cont, void *cont_cls)
698 {
699   struct Session* ses;
700   struct Session* ses_temp;
701   int bytes_sent = 0;
702   unsigned int i_timeout;
703   int still_running;
704   int msgs_left;
705   CURL *curl_handle;
706   CURLMcode mret;
707   CURLMsg *msg;
708
709   /* find session for peer */
710   ses = find_session_by_pi (target);
711
712   if ( ses == NULL)
713   {
714     /* create new session object */
715     ses = GNUNET_malloc ( sizeof( struct Session) );
716     ses->addr = GNUNET_malloc ( sizeof (struct sockaddr_in) );
717
718     //ses->ip = address;
719     // memcpy(ses->addr, conn_info->client_addr, sizeof (struct sockaddr_in));
720     memcpy(&ses->sender, &target, sizeof (struct GNUNET_PeerIdentity));
721     ses->next = NULL;
722     ses->is_active = GNUNET_YES;
723
724     /* Insert session into linked list */
725     if ( plugin->sessions == NULL)
726     {
727       plugin->sessions = ses;
728       plugin->session_count = 1;
729     }
730     ses_temp = plugin->sessions;
731     while ( ses_temp->next != NULL )
732     {
733       ses_temp = ses_temp->next;
734     }
735     if (ses_temp != ses )
736     {
737       ses_temp->next = ses;
738       plugin->session_count++;
739     }
740     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"New Session `%s' inserted, count %u \n", GNUNET_i2s(target), plugin->session_count);  }
741
742   char *url = "";
743
744
745   curl_handle = curl_easy_init();
746   if( NULL == curl_handle)
747   {
748     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Getting cURL handle failed\n");
749     return -1;
750   }
751
752   i_timeout = ( timeout.value / 1000);
753
754   curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
755   curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION, read_callback);
756   curl_easy_setopt(curl_handle, CURLOPT_UPLOAD, 1L);
757   curl_easy_setopt(curl_handle, CURLOPT_PUT, 1L);
758   curl_easy_setopt(curl_handle, CURLOPT_URL, url);
759   curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, timeout);
760   curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
761   curl_easy_setopt(curl_handle, CURLOPT_READDATA, msgbuf);
762   curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE_LARGE,
763                   (curl_off_t)msgbuf_size);
764
765   mret = curl_multi_add_handle(multi_handle, curl_handle);
766   if (mret != CURLM_OK)
767     {
768       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
769                   _("%s failed at %s:%d: `%s'\n"),
770                   "curl_multi_add_handle", __FILE__, __LINE__,
771                   curl_multi_strerror (mret));
772       return -1;
773     }
774
775   while(CURLM_CALL_MULTI_PERFORM == curl_multi_perform(multi_handle, &still_running));
776
777   while(still_running)
778   {
779       struct timeval timeout;
780       int rc; /* select() return code */
781
782       fd_set fdread;
783       fd_set fdwrite;
784       fd_set fdexcep;
785       int maxfd = -1;
786
787       FD_ZERO(&fdread);
788       FD_ZERO(&fdwrite);
789       FD_ZERO(&fdexcep);
790
791       /* set a suitable timeout to play around with */
792       timeout.tv_sec = 1;
793       timeout.tv_usec = 0;
794
795       /* get file descriptors from the transfers */
796       mret = curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
797       if (mret != CURLM_OK)
798       {
799         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
800                     _("%s failed at %s:%d: `%s'\n"),
801                     "curl_multi_fdset", __FILE__, __LINE__,
802                     curl_multi_strerror (mret));
803         return -1;
804       }
805
806       rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
807
808       switch(rc)
809       {
810       case -1:
811         /* select error */
812         break;
813       case 0:
814         /* timeout, do something else */
815         break;
816       default:
817         /* one or more of curl's file descriptors say there's data to read
818            or write */
819         while(CURLM_CALL_MULTI_PERFORM ==
820               curl_multi_perform(multi_handle, &still_running));
821         break;
822       }
823   }
824
825   /* See how the transfers went */
826   while ((msg = curl_multi_info_read(multi_handle, &msgs_left))) {
827     if (msg->msg == CURLMSG_DONE) {
828       int idx, found = 0;
829
830       /* Find out which handle this message is about */
831       for (idx=0; idx<1; idx++) {
832         found = (msg->easy_handle == curl_handle);
833         if(found)
834           break;
835       }
836
837       switch (idx) {
838       case 0:
839         printf("HTTP transfer completed with status %d\n", msg->data.result);
840         break;
841       }
842     }
843   }
844
845
846   return bytes_sent;
847 }
848
849
850
851 /**
852  * Function that can be used to force the plugin to disconnect
853  * from the given peer and cancel all previous transmissions
854  * (and their continuationc).
855  *
856  * @param cls closure
857  * @param target peer from which to disconnect
858  */
859 static void
860 http_plugin_disconnect (void *cls,
861                             const struct GNUNET_PeerIdentity *target)
862 {
863   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_disconnect\n");
864   // struct Plugin *plugin = cls;
865   // FIXME
866 }
867
868
869 /**
870  * Convert the transports address to a nice, human-readable
871  * format.
872  *
873  * @param cls closure
874  * @param type name of the transport that generated the address
875  * @param addr one of the addresses of the host, NULL for the last address
876  *        the specific address format depends on the transport
877  * @param addrlen length of the address
878  * @param numeric should (IP) addresses be displayed in numeric form?
879  * @param timeout after how long should we give up?
880  * @param asc function to call on each string
881  * @param asc_cls closure for asc
882  */
883 static void
884 http_plugin_address_pretty_printer (void *cls,
885                                         const char *type,
886                                         const void *addr,
887                                         size_t addrlen,
888                                         int numeric,
889                                         struct GNUNET_TIME_Relative timeout,
890                                         GNUNET_TRANSPORT_AddressStringCallback
891                                         asc, void *asc_cls)
892 {
893   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_address_pretty_printer\n");
894   asc (asc_cls, NULL);
895 }
896
897
898
899 /**
900  * Another peer has suggested an address for this
901  * peer and transport plugin.  Check that this could be a valid
902  * address.  If so, consider adding it to the list
903  * of addresses.
904  *
905  * @param cls closure
906  * @param addr pointer to the address
907  * @param addrlen length of addr
908  * @return GNUNET_OK if this is a plausible address for this peer
909  *         and transport
910  */
911 static int
912 http_plugin_address_suggested (void *cls,
913                                   void *addr, size_t addrlen)
914 {
915   /* struct Plugin *plugin = cls; */
916
917   /* check if the address is plausible; if so,
918      add it to our list! */
919   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_address_suggested\n");
920   return GNUNET_OK;
921 }
922
923
924 /**
925  * Function called for a quick conversion of the binary address to
926  * a numeric address.  Note that the caller must not free the
927  * address and that the next call to this function is allowed
928  * to override the address again.
929  *
930  * @param cls closure
931  * @param addr binary address
932  * @param addrlen length of the address
933  * @return string representing the same address
934  */
935 static const char*
936 http_plugin_address_to_string (void *cls,
937                                    const void *addr,
938                                    size_t addrlen)
939 {
940   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_address_to_string\n");
941   GNUNET_break (0);
942   return NULL;
943 }
944
945 /**
946  * Exit point from the plugin.
947  */
948 void *
949 libgnunet_plugin_transport_http_done (void *cls)
950 {
951   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
952   struct Plugin *plugin = api->cls;
953   struct Session * cs;
954   struct Session * cs_next;
955
956   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unloading http plugin...\n");
957
958   if ( http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
959   {
960     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v4);
961     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
962   }
963
964   if ( http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
965   {
966     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v6);
967     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
968   }
969
970   if (http_daemon_v4 != NULL)
971   {
972     MHD_stop_daemon (http_daemon_v4);
973     http_daemon_v4 = NULL;
974   }
975   if (http_daemon_v6 != NULL)
976   {
977     MHD_stop_daemon (http_daemon_v6);
978     http_daemon_v6 = NULL;
979   }
980
981   curl_multi_cleanup(multi_handle);
982
983   /* free all sessions */
984   cs = plugin->sessions;
985   while ( NULL != cs)
986     {
987       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing session to `%s'\n",cs->ip);
988       cs_next = cs->next;
989       GNUNET_free (cs->ip);
990       GNUNET_free (cs->addr);
991       GNUNET_free (cs);
992       plugin->session_count--;
993       cs = cs_next;
994     }
995
996   /* GNUNET_SERVICE_stop (plugin->service); */
997
998   GNUNET_free (plugin);
999   GNUNET_free (api);
1000   return NULL;
1001 }
1002
1003
1004 /**
1005  * Entry point for the plugin.
1006  */
1007 void *
1008 libgnunet_plugin_transport_http_init (void *cls)
1009 {
1010   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1011   struct GNUNET_TRANSPORT_PluginFunctions *api;
1012   struct GNUNET_SERVICE_Context *service;
1013   unsigned int timeout;
1014   struct GNUNET_TIME_Relative gn_timeout;
1015   long long unsigned int port;
1016
1017   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
1018
1019   service = NULL;
1020   /*
1021   service = GNUNET_SERVICE_start ("transport-http", env->sched, env->cfg);
1022   if (service == NULL)
1023     {
1024       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "", _
1025                        ("Failed to start service for `%s' transport plugin.\n"),
1026                        "http");
1027       return NULL;
1028     }
1029     */
1030
1031   plugin = GNUNET_malloc (sizeof (struct Plugin));
1032   plugin->env = env;
1033   plugin->sessions = NULL;
1034   plugin->service = service;
1035   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1036   api->cls = plugin;
1037   api->send = &http_plugin_send;
1038   api->disconnect = &http_plugin_disconnect;
1039   api->address_pretty_printer = &http_plugin_address_pretty_printer;
1040   api->check_address = &http_plugin_address_suggested;
1041   api->address_to_string = &http_plugin_address_to_string;
1042
1043   hostname = GNUNET_RESOLVER_local_fqdn_get ();
1044
1045   /* Hashing our identity to use it in URLs */
1046   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &my_ascii_hash_ident);
1047
1048   /* Reading port number from config file */
1049   if ((GNUNET_OK !=
1050        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1051                                               "transport-http",
1052                                               "PORT",
1053                                               &port)) ||
1054       (port > 65535) )
1055     {
1056       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1057                        "http",
1058                        _
1059                        ("Require valid port number for transport plugin `%s' in configuration!\n"),
1060                        "transport-http");
1061       libgnunet_plugin_transport_http_done (api);
1062       return NULL;
1063     }
1064
1065   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1066   timeout = ( gn_timeout.value / 1000);
1067   if ((http_daemon_v4 == NULL) && (http_daemon_v6 == NULL) && (port != 0))
1068     {
1069     http_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
1070                                        port,
1071                                        &acceptPolicyCallback,
1072                                        NULL , &accessHandlerCallback, NULL,
1073                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1074                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1075                                        MHD_OPTION_CONNECTION_TIMEOUT, timeout,
1076                                        /* FIXME: set correct limit */
1077                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1078                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1079                                        MHD_OPTION_END);
1080     http_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
1081                                        port,
1082                                        &acceptPolicyCallback,
1083                                        NULL , &accessHandlerCallback, NULL,
1084                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1085                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1086                                        MHD_OPTION_CONNECTION_TIMEOUT, timeout,
1087                                        /* FIXME: set correct limit */
1088                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1089                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1090                                        MHD_OPTION_END);
1091     }
1092   if (http_daemon_v4 != NULL)
1093     http_task_v4 = http_daemon_prepare (http_daemon_v4);
1094   if (http_daemon_v6 != NULL)
1095     http_task_v6 = http_daemon_prepare (http_daemon_v6);
1096
1097   if (http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1098     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
1099   if (http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1100     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
1101
1102   /* Initializing cURL */
1103   multi_handle = curl_multi_init();
1104   if ( NULL == multi_handle )
1105   {
1106     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1107                      "http",
1108                      _("Could not initialize curl multi handle, failed to start http plugin!\n"),
1109                      "transport-http");
1110     libgnunet_plugin_transport_http_done (api);
1111     return NULL;
1112   }
1113   return api;
1114 }
1115
1116 /* end of plugin_transport_template.c */