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