79ede78d14eeb4278c8757c407091562e6469c0a
[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    * List of open sessions.
168    */
169   struct Session *sessions;
170
171   /**
172    * Number of active sessions
173    */
174
175   unsigned int session_count;
176
177 };
178
179 /**
180  * Daemon for listening for new IPv4 connections.
181  */
182 static struct MHD_Daemon *http_daemon_v4;
183
184 /**
185  * Daemon for listening for new IPv6connections.
186  */
187 static struct MHD_Daemon *http_daemon_v6;
188
189 /**
190  * Our primary task for http daemon handling IPv4 connections
191  */
192 static GNUNET_SCHEDULER_TaskIdentifier http_task_v4;
193
194 /**
195  * Our primary task for http daemon handling IPv6 connections
196  */
197 static GNUNET_SCHEDULER_TaskIdentifier http_task_v6;
198
199
200 /**
201  * Information about this plugin
202  */
203 static struct Plugin *plugin;
204
205 /**
206  * cURL Multihandle
207  */
208 static CURLM *multi_handle;
209
210 /**
211  * Our hostname
212  */
213 static char * hostname;
214
215 /**
216  * Our ASCII encoded, hashed peer identity
217  * This string is used to distinguish between connections and is added to the urls
218  */
219 static struct GNUNET_CRYPTO_HashAsciiEncoded my_ascii_hash_ident;
220
221
222 /**
223  * Finds a http session in our linked list using peer identity as a key
224  * @param peer peeridentity
225  * @return http session corresponding to peer identity
226  */
227 static struct Session * find_session_by_pi( const struct GNUNET_PeerIdentity *peer )
228 {
229   struct Session * cur;
230   GNUNET_HashCode hc_peer;
231   GNUNET_HashCode hc_current;
232
233   cur = plugin->sessions;
234   hc_peer = peer->hashPubKey;
235   while (cur != NULL)
236   {
237     hc_current = cur->sender.hashPubKey;
238     if ( 0 == GNUNET_CRYPTO_hash_cmp( &hc_peer, &hc_current))
239       return cur;
240     cur = plugin->sessions->next;
241   }
242   return NULL;
243 }
244
245 #if 0
246 /**
247  * Finds a http session in our linked list using peer identity as a key
248  * @param peer peeridentity
249  * @return http session corresponding to peer identity
250  */
251 static struct Session * find_session_by_ip( char * ip )
252 {
253   /*
254   struct Session * cur;
255
256   cur = plugin->sessions;
257   while (cur != NULL)
258   {
259     hc_current = cur->sender.hashPubKey;
260     if ( 0 == GNUNET_CRYPTO_hash_cmp( &hc_peer, &hc_current))
261       return cur;
262     cur = plugin->sessions->next;
263   }
264   */
265   return NULL;
266 }
267 #endif
268
269 #if 0
270 /**
271  * Creates a http session in our linked list by ip address
272  * Only ip is set here, all other fields have to be set by calling method
273  * @param peer peeridentity
274  * @return created http session
275  */
276 static struct Session * create_session_by_ip ( struct sockaddr_in * addr )
277 {
278   struct Session * cur;
279   struct Session * last_in_list;
280   /* Create a new session object */
281   cur = GNUNET_malloc (sizeof (struct Session));
282   // FIXME: memcpy( &(cur->ip), , sizeof( struct GNUNET_PeerIdentity ) );
283
284   cur->next = NULL;
285
286   /* Insert into linked list */
287   last_in_list = plugin->sessions;
288   while (last_in_list->next != NULL)
289   {
290     last_in_list = last_in_list->next;
291   }
292   last_in_list->next = cur;
293
294   return cur;
295 }
296 #endif
297
298 /**
299  * Callback called by MHD when a connection is terminated
300  */
301 static void requestCompletedCallback (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
302 {
303   struct Session * cs;
304
305   cs = *httpSessionCache;
306   if (cs != NULL)
307   {
308     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection from peer `%s' was terminated\n",GNUNET_i2s(&cs->sender));
309     /* session set to inactive */
310     cs->is_active = GNUNET_NO;
311     cs->is_put_in_progress = GNUNET_NO;
312   }
313   return;
314 }
315
316 /**
317  * Check if we are allowed to connect to the given IP.
318  */
319 static int
320 acceptPolicyCallback (void *cls,
321                       const struct sockaddr *addr, socklen_t addr_len)
322 {
323   /* Every connection is accepted, nothing more to do here */
324   return MHD_YES;
325 }
326
327
328 /**
329  * Process GET or PUT request received via MHD.  For
330  * GET, queue response that will send back our pending
331  * messages.  For PUT, process incoming data and send
332  * to GNUnet core.  In either case, check if a session
333  * already exists and create a new one if not.
334  */
335 static int
336 accessHandlerCallback (void *cls,
337                        struct MHD_Connection *session,
338                        const char *url,
339                        const char *method,
340                        const char *version,
341                        const char *upload_data,
342                        size_t * upload_data_size, void **httpSessionCache)
343 {
344   struct MHD_Response *response;
345   struct Session * cs;
346   struct Session * cs_temp;
347   const union MHD_ConnectionInfo * conn_info;
348   struct sockaddr_in  *addrin;
349   struct sockaddr_in6 *addrin6;
350   char * address = NULL;
351   struct GNUNET_PeerIdentity pi_in;
352   int res = GNUNET_NO;
353
354   if ( NULL == *httpSessionCache)
355   {
356     /* check url for peer identity */
357     res = GNUNET_CRYPTO_hash_from_string ( &url[1], &(pi_in.hashPubKey));
358     if ( GNUNET_SYSERR == res )
359     {
360       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident\n");
361       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
362       res = MHD_queue_response (session, MHD_HTTP_NOT_FOUND, response);
363       MHD_destroy_response (response);
364       return res;
365     }
366     conn_info = MHD_get_connection_info(session, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
367     /* Incoming IPv4 connection */
368     if ( AF_INET == conn_info->client_addr->sin_family)
369     {
370       address = GNUNET_malloc (INET_ADDRSTRLEN);
371       addrin = conn_info->client_addr;
372       inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
373     }
374     /* Incoming IPv6 connection */
375     if ( AF_INET6 == conn_info->client_addr->sin_family)
376     {
377       address = GNUNET_malloc (INET6_ADDRSTRLEN);
378       addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
379       inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
380     }
381     /* find existing session for address */
382     cs = NULL;
383     if (plugin->session_count > 0)
384     {
385       cs = plugin->sessions;
386       while ( NULL != cs)
387       {
388
389         /* Comparison based on ip address */
390         // res = (0 == memcmp(&(conn_info->client_addr->sin_addr),&(cs->addr->sin_addr), sizeof (struct in_addr))) ? GNUNET_YES : GNUNET_NO;
391
392         /* Comparison based on ip address, port number and address family */
393         // res = (0 == memcmp((conn_info->client_addr),(cs->addr), sizeof (struct sockaddr_in))) ? GNUNET_YES : GNUNET_NO;
394
395         /* Comparison based on PeerIdentity */
396         res = (0 == memcmp(&pi_in,&(cs->sender), sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_YES : GNUNET_NO;
397
398         if ( GNUNET_YES  == res)
399         {
400           /* existing session for this address found */
401           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session `%s' found\n",address);
402           break;
403         }
404         cs = cs->next;
405       }
406     }
407     /* no existing session, create a new one*/
408     if (cs == NULL )
409     {
410       /* create new session object */
411       cs = GNUNET_malloc ( sizeof( struct Session) );
412       cs->addr = GNUNET_malloc ( sizeof (struct sockaddr_in) );
413
414       cs->ip = address;
415       memcpy(cs->addr, conn_info->client_addr, sizeof (struct sockaddr_in));
416       memcpy(&cs->sender, &pi_in, sizeof (struct GNUNET_PeerIdentity));
417       cs->next = NULL;
418       cs->is_active = GNUNET_YES;
419
420       /* Insert session into linked list */
421       if ( plugin->sessions == NULL)
422       {
423         plugin->sessions = cs;
424         plugin->session_count = 1;
425       }
426       cs_temp = plugin->sessions;
427       while ( cs_temp->next != NULL )
428       {
429         cs_temp = cs_temp->next;
430       }
431       if (cs_temp != cs )
432       {
433         cs_temp->next = cs;
434         plugin->session_count++;
435       }
436       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"New Session `%s' inserted, count %u \n", address, plugin->session_count);
437     }
438     /* Set closure */
439     if (*httpSessionCache == NULL)
440     {
441       *httpSessionCache = cs;
442     }
443     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);
444   }
445   else
446   {
447     cs = *httpSessionCache;
448   }
449
450   /* Is it a PUT or a GET request */
451   if ( 0 == strcmp (MHD_HTTP_METHOD_PUT, method) )
452   {
453     /* New  */
454     if ((*upload_data_size == 0) && (cs->is_put_in_progress == GNUNET_NO))
455     {
456       /* not yet ready */
457       cs->is_put_in_progress = GNUNET_YES;
458       return MHD_YES;
459     }
460     if ( *upload_data_size > 0 )
461     {
462       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"PUT URL: `%s'\n",url);
463       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"PUT Request: %lu bytes: `%s' \n", (*upload_data_size), upload_data);
464       /* No data left */
465       *upload_data_size = 0;
466       /* do something with the data */
467       return MHD_YES;
468     }
469     if ((*upload_data_size == 0) && (cs->is_put_in_progress == GNUNET_YES))
470     {
471       cs->is_put_in_progress = GNUNET_NO;
472       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
473       res = MHD_queue_response (session, MHD_HTTP_OK, response);
474       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Sent HTTP/1.1: 200 OK as PUT Response\n",HTTP_PUT_RESPONSE, strlen (HTTP_PUT_RESPONSE), res );
475       MHD_destroy_response (response);
476       return res;
477     }
478   }
479   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
480   {
481     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request\n");
482     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"URL: `%s'\n",url);
483     response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
484     res = MHD_queue_response (session, MHD_HTTP_OK, response);
485     MHD_destroy_response (response);
486     return res;
487   }
488   return MHD_NO;
489 }
490
491
492 /**
493  * Call MHD to process pending requests and then go back
494  * and schedule the next run.
495  */
496 static void http_daemon_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
497
498 /**
499  * Function that queries MHD's select sets and
500  * starts the task waiting for them.
501  */
502 static GNUNET_SCHEDULER_TaskIdentifier
503 http_daemon_prepare (struct MHD_Daemon *daemon_handle)
504 {
505   GNUNET_SCHEDULER_TaskIdentifier ret;
506   fd_set rs;
507   fd_set ws;
508   fd_set es;
509   struct GNUNET_NETWORK_FDSet *wrs;
510   struct GNUNET_NETWORK_FDSet *wws;
511   struct GNUNET_NETWORK_FDSet *wes;
512   int max;
513   unsigned long long timeout;
514   int haveto;
515   struct GNUNET_TIME_Relative tv;
516
517   FD_ZERO(&rs);
518   FD_ZERO(&ws);
519   FD_ZERO(&es);
520   wrs = GNUNET_NETWORK_fdset_create ();
521   wes = GNUNET_NETWORK_fdset_create ();
522   wws = GNUNET_NETWORK_fdset_create ();
523   max = -1;
524   GNUNET_assert (MHD_YES ==
525                  MHD_get_fdset (daemon_handle,
526                                 &rs,
527                                 &ws,
528                                 &es,
529                                 &max));
530   haveto = MHD_get_timeout (daemon_handle, &timeout);
531   if (haveto == MHD_YES)
532     tv.value = (uint64_t) timeout;
533   else
534     tv = GNUNET_TIME_UNIT_FOREVER_REL;
535   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
536   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
537   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
538   ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
539                                      GNUNET_SCHEDULER_PRIORITY_HIGH,
540                                      GNUNET_SCHEDULER_NO_TASK,
541                                      tv,
542                                      wrs,
543                                      wws,
544                                      &http_daemon_run,
545                                      daemon_handle);
546   GNUNET_NETWORK_fdset_destroy (wrs);
547   GNUNET_NETWORK_fdset_destroy (wws);
548   GNUNET_NETWORK_fdset_destroy (wes);
549   return ret;
550 }
551
552 /**
553  * Call MHD to process pending requests and then go back
554  * and schedule the next run.
555  */
556 static void
557 http_daemon_run (void *cls,
558             const struct GNUNET_SCHEDULER_TaskContext *tc)
559 {
560   struct MHD_Daemon *daemon_handle = cls;
561
562   if (daemon_handle == http_daemon_v4)
563     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
564
565   if (daemon_handle == http_daemon_v6)
566     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
567
568   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
569     return;
570
571
572
573   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
574   if (daemon_handle == http_daemon_v4)
575     http_task_v4 = http_daemon_prepare (daemon_handle);
576   if (daemon_handle == http_daemon_v6)
577     http_task_v6 = http_daemon_prepare (daemon_handle);
578   return;
579 }
580
581 static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
582 {
583   size_t retcode;
584   /*
585   fprintf(stdout, "*** Read callback: size %u, size nmemb: %u \n", size, nmemb);
586   retcode = fread(ptr, size, nmemb, stream);
587    */
588   retcode = 0;
589   return retcode;
590 }
591
592 /**
593  * Function that can be used by the transport service to transmit
594  * a message using the plugin.
595  *
596  * @param cls closure
597  * @param target who should receive this message
598  * @param priority how important is the message
599  * @param msgbuf the message to transmit
600  * @param msgbuf_size number of bytes in 'msgbuf'
601  * @param timeout when should we time out
602  * @param session which session must be used (or NULL for "any")
603  * @param addr the address to use (can be NULL if the plugin
604  *                is "on its own" (i.e. re-use existing TCP connection))
605  * @param addrlen length of the address in bytes
606  * @param force_address GNUNET_YES if the plugin MUST use the given address,
607  *                otherwise the plugin may use other addresses or
608  *                existing connections (if available)
609  * @param cont continuation to call once the message has
610  *        been transmitted (or if the transport is ready
611  *        for the next transmission call; or if the
612  *        peer disconnected...)
613  * @param cont_cls closure for cont
614  * @return number of bytes used (on the physical network, with overheads);
615  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
616  *         and does NOT mean that the message was not transmitted (DV)
617  */
618 static ssize_t
619 http_plugin_send (void *cls,
620                       const struct GNUNET_PeerIdentity *
621                       target,
622                       const char *msgbuf,
623                       size_t msgbuf_size,
624                       unsigned int priority,
625                       struct GNUNET_TIME_Relative timeout,
626                       struct Session *session,
627                       const void *addr,
628                       size_t addrlen,
629                       int force_address,
630                       GNUNET_TRANSPORT_TransmitContinuation
631                       cont, void *cont_cls)
632 {
633   struct Session* ses;
634   struct Session* ses_temp;
635   int bytes_sent = 0;
636   unsigned int i_timeout;
637   /*  struct Plugin *plugin = cls; */
638   CURL *curl_handle;
639   /* CURLcode res; */
640
641   /* find session for peer */
642   ses = find_session_by_pi (target);
643
644   if ( ses == NULL)
645   {
646     /* create new session object */
647     ses = GNUNET_malloc ( sizeof( struct Session) );
648     ses->addr = GNUNET_malloc ( sizeof (struct sockaddr_in) );
649
650     //ses->ip = address;
651     // memcpy(ses->addr, conn_info->client_addr, sizeof (struct sockaddr_in));
652     memcpy(&ses->sender, &target, sizeof (struct GNUNET_PeerIdentity));
653     ses->next = NULL;
654     ses->is_active = GNUNET_YES;
655
656     /* Insert session into linked list */
657     if ( plugin->sessions == NULL)
658     {
659       plugin->sessions = ses;
660       plugin->session_count = 1;
661     }
662     ses_temp = plugin->sessions;
663     while ( ses_temp->next != NULL )
664     {
665       ses_temp = ses_temp->next;
666     }
667     if (ses_temp != ses )
668     {
669       ses_temp->next = ses;
670       plugin->session_count++;
671     }
672     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"New Session `%s' inserted, count %u \n", GNUNET_i2s(target), plugin->session_count);  }
673
674   char *url = "";
675
676
677   curl_handle = curl_easy_init();
678   if( NULL == curl_handle)
679   {
680     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Getting cURL handle failed\n");
681     return -1;
682   }
683
684   i_timeout = ( timeout.value / 1000);
685
686   curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
687   curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION, read_callback);
688   curl_easy_setopt(curl_handle, CURLOPT_UPLOAD, 1L);
689   curl_easy_setopt(curl_handle, CURLOPT_PUT, 1L);
690   curl_easy_setopt(curl_handle, CURLOPT_URL, url);
691   curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, timeout);
692   curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
693   curl_easy_setopt(curl_handle, CURLOPT_READDATA, msgbuf);
694   curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE_LARGE,
695                   (curl_off_t)msgbuf_size);
696
697   return bytes_sent;
698 }
699
700
701
702 /**
703  * Function that can be used to force the plugin to disconnect
704  * from the given peer and cancel all previous transmissions
705  * (and their continuationc).
706  *
707  * @param cls closure
708  * @param target peer from which to disconnect
709  */
710 static void
711 http_plugin_disconnect (void *cls,
712                             const struct GNUNET_PeerIdentity *target)
713 {
714   // struct Plugin *plugin = cls;
715   // FIXME
716 }
717
718
719 /**
720  * Convert the transports address to a nice, human-readable
721  * format.
722  *
723  * @param cls closure
724  * @param type name of the transport that generated the address
725  * @param addr one of the addresses of the host, NULL for the last address
726  *        the specific address format depends on the transport
727  * @param addrlen length of the address
728  * @param numeric should (IP) addresses be displayed in numeric form?
729  * @param timeout after how long should we give up?
730  * @param asc function to call on each string
731  * @param asc_cls closure for asc
732  */
733 static void
734 http_plugin_address_pretty_printer (void *cls,
735                                         const char *type,
736                                         const void *addr,
737                                         size_t addrlen,
738                                         int numeric,
739                                         struct GNUNET_TIME_Relative timeout,
740                                         GNUNET_TRANSPORT_AddressStringCallback
741                                         asc, void *asc_cls)
742 {
743   asc (asc_cls, NULL);
744 }
745
746
747
748 /**
749  * Another peer has suggested an address for this
750  * peer and transport plugin.  Check that this could be a valid
751  * address.  If so, consider adding it to the list
752  * of addresses.
753  *
754  * @param cls closure
755  * @param addr pointer to the address
756  * @param addrlen length of addr
757  * @return GNUNET_OK if this is a plausible address for this peer
758  *         and transport
759  */
760 static int
761 http_plugin_address_suggested (void *cls,
762                                   void *addr, size_t addrlen)
763 {
764   /* struct Plugin *plugin = cls; */
765
766   /* check if the address is plausible; if so,
767      add it to our list! */
768   return GNUNET_OK;
769 }
770
771
772 /**
773  * Function called for a quick conversion of the binary address to
774  * a numeric address.  Note that the caller must not free the
775  * address and that the next call to this function is allowed
776  * to override the address again.
777  *
778  * @param cls closure
779  * @param addr binary address
780  * @param addrlen length of the address
781  * @return string representing the same address
782  */
783 static const char*
784 http_plugin_address_to_string (void *cls,
785                                    const void *addr,
786                                    size_t addrlen)
787 {
788   GNUNET_break (0);
789   return NULL;
790 }
791
792 /**
793  * Exit point from the plugin.
794  */
795 void *
796 libgnunet_plugin_transport_http_done (void *cls)
797 {
798   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
799   struct Plugin *plugin = api->cls;
800   struct Session * cs;
801   struct Session * cs_next;
802
803   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unloading http plugin...\n");
804
805   if ( http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
806   {
807     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v4);
808     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
809   }
810
811   if ( http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
812   {
813     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v6);
814     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
815   }
816
817   if (http_daemon_v4 != NULL)
818   {
819     MHD_stop_daemon (http_daemon_v4);
820     http_daemon_v4 = NULL;
821   }
822   if (http_daemon_v6 != NULL)
823   {
824     MHD_stop_daemon (http_daemon_v6);
825     http_daemon_v6 = NULL;
826   }
827
828   curl_multi_cleanup(multi_handle);
829
830   /* free all sessions */
831   cs = plugin->sessions;
832   while ( NULL != cs)
833     {
834       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing session to `%s'\n",cs->ip);
835       cs_next = cs->next;
836       GNUNET_free (cs->ip);
837       GNUNET_free (cs->addr);
838       GNUNET_free (cs);
839       plugin->session_count--;
840       cs = cs_next;
841     }
842
843   GNUNET_free (plugin);
844   GNUNET_free (api);
845   return NULL;
846 }
847
848
849 /**
850  * Entry point for the plugin.
851  */
852 void *
853 libgnunet_plugin_transport_http_init (void *cls)
854 {
855   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
856   struct GNUNET_TRANSPORT_PluginFunctions *api;
857   unsigned int timeout;
858   struct GNUNET_TIME_Relative gn_timeout;
859   long long unsigned int port;
860
861   plugin = GNUNET_malloc (sizeof (struct Plugin));
862   plugin->env = env;
863   plugin->sessions = NULL;
864   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
865   api->cls = plugin;
866   api->send = &http_plugin_send;
867   api->disconnect = &http_plugin_disconnect;
868   api->address_pretty_printer = &http_plugin_address_pretty_printer;
869   api->check_address = &http_plugin_address_suggested;
870   api->address_to_string = &http_plugin_address_to_string;
871
872   hostname = GNUNET_RESOLVER_local_fqdn_get ();
873
874   /* Hashing our identity to use it in URLs */
875   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &my_ascii_hash_ident);
876
877   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
878   /* Reading port number from config file */
879   if ((GNUNET_OK !=
880        GNUNET_CONFIGURATION_get_value_number (env->cfg,
881                                               "transport-http",
882                                               "PORT",
883                                               &port)) ||
884       (port > 65535) )
885     {
886       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
887                        "http",
888                        _
889                        ("Require valid port number for transport plugin `%s' in configuration!\n"),
890                        "transport-http");
891       libgnunet_plugin_transport_http_done (api);
892       return NULL;
893     }
894
895   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
896   timeout = ( gn_timeout.value / 1000);
897   if ((http_daemon_v4 == NULL) && (http_daemon_v6 == NULL) && (port != 0))
898     {
899     http_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
900                                        port,
901                                        &acceptPolicyCallback,
902                                        NULL , &accessHandlerCallback, NULL,
903                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
904                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
905                                        MHD_OPTION_CONNECTION_TIMEOUT, timeout,
906                                        /* FIXME: set correct limit */
907                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
908                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
909                                        MHD_OPTION_END);
910     http_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
911                                        port,
912                                        &acceptPolicyCallback,
913                                        NULL , &accessHandlerCallback, NULL,
914                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
915                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
916                                        MHD_OPTION_CONNECTION_TIMEOUT, timeout,
917                                        /* FIXME: set correct limit */
918                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
919                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
920                                        MHD_OPTION_END);
921     }
922   if (http_daemon_v4 != NULL)
923     http_task_v4 = http_daemon_prepare (http_daemon_v4);
924   if (http_daemon_v6 != NULL)
925     http_task_v6 = http_daemon_prepare (http_daemon_v6);
926
927   if (http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
928     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
929   if (http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
930     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
931
932   /* Initializing cURL */
933   multi_handle = curl_multi_init();
934
935   return api;
936 }
937
938 /* end of plugin_transport_template.c */