(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 "gnunet_os_lib.h"
38 #include "microhttpd.h"
39 #include <curl/curl.h>
40
41 #define DEBUG_HTTP GNUNET_NO
42
43 /**
44  * Text of the response sent back after the last bytes of a PUT
45  * request have been received (just to formally obey the HTTP
46  * protocol).
47  */
48 #define HTTP_PUT_RESPONSE "Thank you!"
49
50 /**
51  * After how long do we expire an address that we
52  * learned from another peer if it is not reconfirmed
53  * by anyone?
54  */
55 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
56
57 /**
58  * Page returned if request invalid
59  */
60 #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>"
61
62 /**
63  * Timeout for a http connect
64  */
65 #define HTTP_CONNECT_TIMEOUT 30
66
67
68 /**
69  * Encapsulation of all of the state of the plugin.
70  */
71 struct Plugin;
72
73 /**
74  * Network format for IPv4 addresses.
75  */
76 struct IPv4HttpAddress
77 {
78   /**
79    * IPv4 address, in network byte order.
80    */
81   uint32_t ipv4_addr;
82
83   /**
84    * Port number, in network byte order.
85    */
86   uint16_t u_port;
87
88 };
89
90
91 /**
92  * Network format for IPv6 addresses.
93  */
94 struct IPv6HttpAddress
95 {
96   /**
97    * IPv6 address.
98    */
99   struct in6_addr ipv6_addr;
100
101   /**
102    * Port number, in network byte order.
103    */
104   uint16_t u6_port;
105
106 };
107
108
109
110 /**
111  *  Message to send using http
112  */
113 struct HTTP_Message
114 {
115   /**
116    * Next field for linked list
117    */
118   struct HTTP_Message * next;
119
120   /**
121    * buffer containing data to send
122    */
123   char *buf;
124
125   /**
126    * amount of data already sent
127    */
128   size_t pos;
129
130   /**
131    * amount of data to sent
132    */
133   size_t len;
134 };
135
136
137 /**
138  * Session handle for connections.
139  */
140 struct Session
141 {
142
143   /**
144    * Stored in a linked list.
145    */
146   struct Session *next;
147
148   /**
149    * Pointer to the global plugin struct.
150    */
151   struct Plugin *plugin;
152
153   /**
154    * Continuation function to call once the transmission buffer
155    * has again space available.  NULL if there is no
156    * continuation to call.
157    */
158   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
159
160   /**
161    * Closure for transmit_cont.
162    */
163   void *transmit_cont_cls;
164
165   /**
166    * To whom are we talking to (set to our identity
167    * if we are still waiting for the welcome message)
168    */
169   struct GNUNET_PeerIdentity sender;
170
171   /**
172    * Sender's url
173    */
174   char * url;
175
176   /**
177    * Sender's ip address to distinguish between incoming connections
178    */
179   char * ip;
180
181   /**
182    * Sender's ip address to distinguish between incoming connections
183    */
184   struct sockaddr_in * addr;
185
186   /**
187    * Did we initiate the connection (GNUNET_YES) or the other peer (GNUNET_NO)?
188    */
189   unsigned int is_client;
190
191   /**
192    * Is the connection active (GNUNET_YES) or terminated (GNUNET_NO)?
193    */
194   unsigned int is_active;
195
196   /**
197    * At what time did we reset last_received last?
198    */
199   struct GNUNET_TIME_Absolute last_quota_update;
200
201   /**
202    * How many bytes have we received since the "last_quota_update"
203    * timestamp?
204    */
205   uint64_t last_received;
206
207   /**
208    * Number of bytes per ms that this peer is allowed
209    * to send to us.
210    */
211   uint32_t quota;
212
213   /**
214    * Is there a HTTP/PUT in progress?
215    */
216   unsigned int is_put_in_progress;
217
218   /**
219    * Encoded hash
220    */
221   struct GNUNET_CRYPTO_HashAsciiEncoded hash;
222
223   struct HTTP_Message * pending_outbound_msg;;
224
225   CURL *curl_handle;
226 };
227
228 /**
229  * Encapsulation of all of the state of the plugin.
230  */
231 struct Plugin
232 {
233   /**
234    * Our environment.
235    */
236   struct GNUNET_TRANSPORT_PluginEnvironment *env;
237
238   /**
239    * Handle to the network service.
240    */
241   struct GNUNET_SERVICE_Context *service;
242
243   unsigned int port_inbound;
244
245   /**
246    * List of open sessions.
247    */
248   struct Session *sessions;
249
250   /**
251    * Number of active sessions
252    */
253
254   unsigned int session_count;
255 };
256
257 /**
258  * Daemon for listening for new IPv4 connections.
259  */
260 static struct MHD_Daemon *http_daemon_v4;
261
262 /**
263  * Daemon for listening for new IPv6connections.
264  */
265 static struct MHD_Daemon *http_daemon_v6;
266
267 /**
268  * Our primary task for http daemon handling IPv4 connections
269  */
270 static GNUNET_SCHEDULER_TaskIdentifier http_task_v4;
271
272 /**
273  * Our primary task for http daemon handling IPv6 connections
274  */
275 static GNUNET_SCHEDULER_TaskIdentifier http_task_v6;
276
277
278 /**
279  * Our primary task for http daemon handling IPv6 connections
280  */
281 static GNUNET_SCHEDULER_TaskIdentifier http_task_send;
282
283
284 /**
285  * Information about this plugin
286  */
287 static struct Plugin *plugin;
288
289 /**
290  * cURL Multihandle
291  */
292 static CURLM *multi_handle;
293
294 /**
295  * Our hostname
296  */
297 static char * hostname;
298
299 /**
300  * Our ASCII encoded, hashed peer identity
301  * This string is used to distinguish between connections and is added to the urls
302  */
303 static struct GNUNET_CRYPTO_HashAsciiEncoded my_ascii_hash_ident;
304
305 struct GNUNET_TIME_Relative timeout;
306
307 /**
308  * Finds a http session in our linked list using peer identity as a key
309  * @param peer peeridentity
310  * @return http session corresponding to peer identity
311  */
312 static struct Session * find_session_by_pi( const struct GNUNET_PeerIdentity *peer )
313 {
314   struct Session * cur;
315   GNUNET_HashCode hc_peer;
316   GNUNET_HashCode hc_current;
317
318   cur = plugin->sessions;
319   hc_peer = peer->hashPubKey;
320   while (cur != NULL)
321   {
322     hc_current = cur->sender.hashPubKey;
323     if ( 0 == GNUNET_CRYPTO_hash_cmp( &hc_peer, &hc_current))
324       return cur;
325     cur = plugin->sessions->next;
326   }
327   return NULL;
328 }
329
330 /**
331  * Finds a http session in our linked list using libcurl handle as a key
332  * Needed when sending data with libcurl to differentiate between sessions
333  * @param handle peeridentity
334  * @return http session corresponding to peer identity
335  */
336 static struct Session * find_session_by_curlhandle( CURL* handle )
337 {
338   struct Session * cur;
339
340   cur = plugin->sessions;
341   while (cur != NULL)
342   {
343     if ( handle == cur->curl_handle )
344       return cur;
345     cur = plugin->sessions->next;
346   }
347   return NULL;
348 }
349
350 /**
351  * Create a new session
352  *
353  * @param address address the peer is using
354  * @param peer identity
355  * @return created session object
356  */
357 static struct Session * create_session (struct sockaddr_in *address, const struct GNUNET_PeerIdentity *peer)
358 {
359   struct sockaddr_in  *addrin;
360   struct sockaddr_in6 *addrin6;
361
362   struct Session * ses = GNUNET_malloc ( sizeof( struct Session) );
363   ses->addr = GNUNET_malloc ( sizeof (struct sockaddr_in) );
364
365   ses->next = NULL;
366   ses->plugin = plugin;
367
368   memcpy(ses->addr, address, sizeof (struct sockaddr_in));
369   if ( AF_INET == address->sin_family)
370   {
371     ses->ip = GNUNET_malloc (INET_ADDRSTRLEN);
372     addrin = address;
373     inet_ntop(addrin->sin_family,&(addrin->sin_addr),ses->ip,INET_ADDRSTRLEN);
374   }
375   if ( AF_INET6 == address->sin_family)
376   {
377     ses->ip = GNUNET_malloc (INET6_ADDRSTRLEN);
378     addrin6 = (struct sockaddr_in6 *) address;
379     inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr) ,ses->ip,INET6_ADDRSTRLEN);
380   }
381   memcpy(&ses->sender, peer, sizeof (struct GNUNET_PeerIdentity));
382   GNUNET_CRYPTO_hash_to_enc(&ses->sender.hashPubKey,&(ses->hash));
383   ses->is_active = GNUNET_NO;
384
385   return ses;
386 }
387
388 /**
389  * Callback called by MHD when a connection is terminated
390  */
391 static void requestCompletedCallback (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
392 {
393   struct Session * cs;
394
395   cs = *httpSessionCache;
396   if (cs != NULL)
397   {
398     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection from peer `%s' was terminated\n",GNUNET_i2s(&cs->sender));
399     /* session set to inactive */
400     cs->is_active = GNUNET_NO;
401     cs->is_put_in_progress = GNUNET_NO;
402   }
403   return;
404 }
405
406 /**
407  * Check if we are allowed to connect to the given IP.
408  */
409 static int
410 acceptPolicyCallback (void *cls,
411                       const struct sockaddr *addr, socklen_t addr_len)
412 {
413   /* Every connection is accepted, nothing more to do here */
414   return MHD_YES;
415 }
416
417
418 /**
419  * Process GET or PUT request received via MHD.  For
420  * GET, queue response that will send back our pending
421  * messages.  For PUT, process incoming data and send
422  * to GNUnet core.  In either case, check if a session
423  * already exists and create a new one if not.
424  */
425 static int
426 accessHandlerCallback (void *cls,
427                        struct MHD_Connection *session,
428                        const char *url,
429                        const char *method,
430                        const char *version,
431                        const char *upload_data,
432                        size_t * upload_data_size, void **httpSessionCache)
433 {
434   struct MHD_Response *response;
435   struct Session * cs;
436   struct Session * cs_temp;
437   const union MHD_ConnectionInfo * conn_info;
438   struct sockaddr_in  *addrin;
439   struct sockaddr_in6 *addrin6;
440   char * address = NULL;
441   struct GNUNET_PeerIdentity pi_in;
442   int res = GNUNET_NO;
443   size_t bytes_recv;
444   struct GNUNET_MessageHeader *gn_msg;
445   int send_error_to_client;
446
447   gn_msg = NULL;
448   send_error_to_client = GNUNET_NO;
449   if ( NULL == *httpSessionCache)
450   {
451     /* check url for peer identity */
452     res = GNUNET_CRYPTO_hash_from_string ( &url[1], &(pi_in.hashPubKey));
453     if ( GNUNET_SYSERR == res )
454     {
455       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident\n");
456       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
457       res = MHD_queue_response (session, MHD_HTTP_NOT_FOUND, response);
458       MHD_destroy_response (response);
459       return res;
460     }
461
462     conn_info = MHD_get_connection_info(session, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
463     /* Incoming IPv4 connection */
464     if ( AF_INET == conn_info->client_addr->sin_family)
465     {
466       address = GNUNET_malloc (INET_ADDRSTRLEN);
467       addrin = conn_info->client_addr;
468       inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
469     }
470     /* Incoming IPv6 connection */
471     if ( AF_INET6 == conn_info->client_addr->sin_family)
472     {
473       address = GNUNET_malloc (INET6_ADDRSTRLEN);
474       addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
475       inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
476     }
477     /* find existing session for address */
478     cs = NULL;
479     if (plugin->session_count > 0)
480     {
481       cs = plugin->sessions;
482       while ( NULL != cs)
483       {
484
485         /* Comparison based on ip address */
486         // res = (0 == memcmp(&(conn_info->client_addr->sin_addr),&(cs->addr->sin_addr), sizeof (struct in_addr))) ? GNUNET_YES : GNUNET_NO;
487
488         /* Comparison based on ip address, port number and address family */
489         // res = (0 == memcmp((conn_info->client_addr),(cs->addr), sizeof (struct sockaddr_in))) ? GNUNET_YES : GNUNET_NO;
490
491         /* Comparison based on PeerIdentity */
492         res = (0 == memcmp(&pi_in,&(cs->sender), sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_YES : GNUNET_NO;
493
494         if ( GNUNET_YES  == res)
495         {
496           /* existing session for this address found */
497           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session `%s' found\n",address);
498           break;
499         }
500         cs = cs->next;
501       }
502     }
503     /* no existing session, create a new one*/
504     if (cs == NULL )
505     {
506       /* create new session object */
507       cs = create_session(conn_info->client_addr, &pi_in);
508
509       /* Insert session into linked list */
510       if ( plugin->sessions == NULL)
511       {
512         plugin->sessions = cs;
513         plugin->session_count = 1;
514       }
515       cs_temp = plugin->sessions;
516       while ( cs_temp->next != NULL )
517       {
518         cs_temp = cs_temp->next;
519       }
520       if (cs_temp != cs )
521       {
522         cs_temp->next = cs;
523         plugin->session_count++;
524       }
525       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"New Session `%s' inserted, count %u \n", address, plugin->session_count);
526     }
527     /* Set closure */
528     if (*httpSessionCache == NULL)
529     {
530       *httpSessionCache = cs;
531     }
532     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);
533   }
534   else
535   {
536     cs = *httpSessionCache;
537   }
538   /* Is it a PUT or a GET request */
539   if ( 0 == strcmp (MHD_HTTP_METHOD_PUT, method) )
540   {
541     /* New  */
542     if ((*upload_data_size == 0) && (cs->is_put_in_progress == GNUNET_NO))
543     {
544       /* not yet ready */
545       cs->is_put_in_progress = GNUNET_YES;
546       cs->is_active = GNUNET_YES;
547       return MHD_YES;
548     }
549     if ( *upload_data_size > 0 )
550     {
551       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"PUT URL: `%s'\n",url);
552       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"PUT Request: %lu bytes: `%s' \n", (*upload_data_size), upload_data);
553       /* No data left */
554       bytes_recv = *upload_data_size ;
555       *upload_data_size = 0;
556
557       /* checking size */
558       if (bytes_recv < sizeof (struct GNUNET_MessageHeader))
559       {
560         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));
561         send_error_to_client = GNUNET_YES;
562       }
563
564       if ( bytes_recv > GNUNET_SERVER_MAX_MESSAGE_SIZE)
565       {
566         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Message too big, is %u bytes, maximum %u '\n",bytes_recv, GNUNET_SERVER_MAX_MESSAGE_SIZE);
567         send_error_to_client = GNUNET_YES;
568       }
569
570       struct GNUNET_MessageHeader * gn_msg = GNUNET_malloc (bytes_recv);
571       memcpy (gn_msg,upload_data,bytes_recv);
572
573       if ( ntohs(gn_msg->size) != bytes_recv )
574       {
575         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Message has incorrect size, is %u bytes vs %u recieved'\n",ntohs(gn_msg->size) , bytes_recv);
576         send_error_to_client = GNUNET_YES;
577       }
578
579       if ( GNUNET_YES == send_error_to_client)
580       {
581         response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
582         res = MHD_queue_response (session, MHD_HTTP_BAD_REQUEST, response);
583         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Sent HTTP/1.1: 400 BAD REQUEST as PUT Response\n",HTTP_PUT_RESPONSE, strlen (HTTP_PUT_RESPONSE), res );
584         MHD_destroy_response (response);
585         GNUNET_free (gn_msg);
586         return MHD_NO;
587       }
588       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Recieved GNUnet message type %u size %u and payload %u \n",ntohs (gn_msg->type), ntohs (gn_msg->size), ntohs (gn_msg->size)-sizeof(struct GNUNET_MessageHeader));
589
590       /* forwarding message to transport */
591       plugin->env->receive(plugin->env, &(cs->sender), gn_msg, 1, cs , cs->ip, strlen(cs->ip) );
592       return MHD_YES;
593     }
594     if ((*upload_data_size == 0) && (cs->is_put_in_progress == GNUNET_YES))
595     {
596       cs->is_put_in_progress = GNUNET_NO;
597       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
598       res = MHD_queue_response (session, MHD_HTTP_OK, response);
599       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Sent HTTP/1.1: 200 OK as PUT Response\n",HTTP_PUT_RESPONSE, strlen (HTTP_PUT_RESPONSE), res );
600       MHD_destroy_response (response);
601       return res;
602     }
603   }
604   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
605   {
606     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request\n");
607     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"URL: `%s'\n",url);
608     response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
609     res = MHD_queue_response (session, MHD_HTTP_OK, response);
610     MHD_destroy_response (response);
611     return res;
612   }
613   return MHD_NO;
614 }
615
616
617 /**
618  * Call MHD to process pending requests and then go back
619  * and schedule the next run.
620  */
621 static void http_daemon_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
622
623 /**
624  * Function that queries MHD's select sets and
625  * starts the task waiting for them.
626  */
627 static GNUNET_SCHEDULER_TaskIdentifier
628 http_daemon_prepare (struct MHD_Daemon *daemon_handle)
629 {
630   GNUNET_SCHEDULER_TaskIdentifier ret;
631   fd_set rs;
632   fd_set ws;
633   fd_set es;
634   struct GNUNET_NETWORK_FDSet *wrs;
635   struct GNUNET_NETWORK_FDSet *wws;
636   struct GNUNET_NETWORK_FDSet *wes;
637   int max;
638   unsigned long long timeout;
639   int haveto;
640   struct GNUNET_TIME_Relative tv;
641
642   FD_ZERO(&rs);
643   FD_ZERO(&ws);
644   FD_ZERO(&es);
645   wrs = GNUNET_NETWORK_fdset_create ();
646   wes = GNUNET_NETWORK_fdset_create ();
647   wws = GNUNET_NETWORK_fdset_create ();
648   max = -1;
649   GNUNET_assert (MHD_YES ==
650                  MHD_get_fdset (daemon_handle,
651                                 &rs,
652                                 &ws,
653                                 &es,
654                                 &max));
655   haveto = MHD_get_timeout (daemon_handle, &timeout);
656   if (haveto == MHD_YES)
657     tv.value = (uint64_t) timeout;
658   else
659     tv = GNUNET_TIME_UNIT_FOREVER_REL;
660   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
661   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
662   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
663   ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
664                                      GNUNET_SCHEDULER_PRIORITY_HIGH,
665                                      GNUNET_SCHEDULER_NO_TASK,
666                                      tv,
667                                      wrs,
668                                      wws,
669                                      &http_daemon_run,
670                                      daemon_handle);
671   GNUNET_NETWORK_fdset_destroy (wrs);
672   GNUNET_NETWORK_fdset_destroy (wws);
673   GNUNET_NETWORK_fdset_destroy (wes);
674   return ret;
675 }
676
677 /**
678  * Call MHD to process pending requests and then go back
679  * and schedule the next run.
680  */
681 static void http_daemon_run (void *cls,
682                              const struct GNUNET_SCHEDULER_TaskContext *tc)
683 {
684   struct MHD_Daemon *daemon_handle = cls;
685
686   if (daemon_handle == http_daemon_v4)
687     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
688
689   if (daemon_handle == http_daemon_v6)
690     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
691
692   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
693     return;
694
695   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
696   if (daemon_handle == http_daemon_v4)
697     http_task_v4 = http_daemon_prepare (daemon_handle);
698   if (daemon_handle == http_daemon_v6)
699     http_task_v6 = http_daemon_prepare (daemon_handle);
700   return;
701 }
702
703 /**
704  * Removes a message from the linked list of messages
705  * @param ses session to remove message from
706  * @param msg message to remove
707  * @return GNUNET_SYSERR if msg not found, GNUNET_OK on success
708  */
709
710 static int remove_http_message(struct Session * ses, struct HTTP_Message * msg)
711 {
712   struct HTTP_Message * cur;
713   struct HTTP_Message * next;
714
715   cur = ses->pending_outbound_msg;
716   next = NULL;
717
718   if (cur == NULL)
719     return GNUNET_SYSERR;
720
721   if (cur == msg)
722   {
723     ses->pending_outbound_msg = cur->next;
724     GNUNET_free (cur->buf);
725     GNUNET_free (cur);
726     cur = NULL;
727     return GNUNET_OK;
728   }
729
730   while (cur->next!=msg)
731   {
732     if (cur->next != NULL)
733       cur = cur->next;
734     else
735       return GNUNET_SYSERR;
736   }
737
738   cur->next = cur->next->next;
739   GNUNET_free (cur->next->buf);
740   GNUNET_free (cur->next);
741   cur->next = NULL;
742   return GNUNET_OK;
743 }
744
745
746 /**
747  * Callback method used with libcurl
748  * Method is called when libcurl needs to read data during sending
749  * @param stream pointer where to write data
750  * @param size size of an individual element
751  * @param nmemb count of elements that can be written to the buffer
752  * @param ptr source pointer, passed to the libcurl handle
753  * @return bytes written to stream
754  */
755 static size_t send_read_callback(void *stream, size_t size, size_t nmemb, void *ptr)
756 {
757   struct Session * ses = ptr;
758   struct HTTP_Message * msg = ses->pending_outbound_msg;
759   unsigned int bytes_sent;
760
761   bytes_sent = 0;
762   if (msg->len > (size * nmemb))
763     return CURL_READFUNC_ABORT;
764
765   if (( msg->pos < msg->len) && (msg->len < (size * nmemb)))
766   {
767     memcpy(stream, msg->buf, msg->len);
768     msg->pos = msg->len;
769     bytes_sent = msg->len;
770   }
771
772   return bytes_sent;
773 }
774
775 /**
776 * Callback method used with libcurl
777 * Method is called when libcurl needs to write data during sending
778 * @param stream pointer where to write data
779 * @param size size of an individual element
780 * @param nmemb count of elements that can be written to the buffer
781 * @param ptr destination pointer, passed to the libcurl handle
782 * @return bytes read from stream
783 */
784 static size_t send_write_callback( void *stream, size_t size, size_t nmemb, void *ptr)
785 {
786   char * data = malloc(size*nmemb +1);
787
788   memcpy( data, stream, size*nmemb);
789   data[size*nmemb] = '\0';
790   /* Just a dummy print for the response recieved for the PUT message */
791   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Recieved %u bytes: `%s' \n", size * nmemb, data);
792   free (data);
793   return (size * nmemb);
794
795 }
796
797 /**
798  * Function setting up file descriptors and scheduling task to run
799  * @param session session to send data to
800  * @return bytes sent to peer
801  */
802 static size_t send_prepare(struct Session* session );
803
804 /**
805  * Function setting up curl handle and selecting message to send
806  * @param ses session to send data to
807  * @return bytes sent to peer
808  */
809 static ssize_t send_select_init (struct Session* ses  )
810 {
811   char * url;
812   int bytes_sent = 0;
813   CURLMcode mret;
814   struct HTTP_Message * msg;
815
816   /* FIFO selection, send oldest msg first, perhaps priority here?  */
817   msg = ses->pending_outbound_msg;
818
819   url = GNUNET_malloc( 7 + strlen(ses->ip) + 7 + strlen ((char *) &(ses->hash)) + 1);
820   /* FIXME: use correct port number */
821   GNUNET_asprintf(&url,"http://%s:%u/%s",ses->ip,12389, (char *) &(ses->hash));
822
823   /* curl_easy_setopt(ses->curl_handle, CURLOPT_VERBOSE, 1L); */
824   curl_easy_setopt(ses->curl_handle, CURLOPT_URL, url);
825   curl_easy_setopt(ses->curl_handle, CURLOPT_PUT, 1L);
826   curl_easy_setopt(ses->curl_handle, CURLOPT_READFUNCTION, send_read_callback);
827   curl_easy_setopt(ses->curl_handle, CURLOPT_READDATA, ses);
828   curl_easy_setopt(ses->curl_handle, CURLOPT_WRITEFUNCTION, send_write_callback);
829   curl_easy_setopt(ses->curl_handle, CURLOPT_READDATA, ses);
830   curl_easy_setopt(ses->curl_handle, CURLOPT_INFILESIZE_LARGE, (curl_off_t) msg->len);
831   curl_easy_setopt(ses->curl_handle, CURLOPT_TIMEOUT, (timeout.value / 1000 ));
832   curl_easy_setopt(ses->curl_handle, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
833
834   mret = curl_multi_add_handle(multi_handle, ses->curl_handle);
835   if (mret != CURLM_OK)
836   {
837     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
838                 _("%s failed at %s:%d: `%s'\n"),
839                 "curl_multi_add_handle", __FILE__, __LINE__,
840                 curl_multi_strerror (mret));
841     return -1;
842   }
843   bytes_sent = send_prepare (ses );
844   GNUNET_free ( url );
845   return bytes_sent;
846 }
847
848 static void send_execute (void *cls,
849              const struct GNUNET_SCHEDULER_TaskContext *tc)
850 {
851   int running;
852   struct CURLMsg *msg;
853   CURLMcode mret;
854   struct Session * cs = NULL;
855
856   http_task_send = GNUNET_SCHEDULER_NO_TASK;
857   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
858     return;
859
860   do
861     {
862       running = 0;
863       mret = curl_multi_perform (multi_handle, &running);
864       if (running == 0)
865         {
866           do
867             {
868
869               msg = curl_multi_info_read (multi_handle, &running);
870               GNUNET_break (msg != NULL);
871               if (msg == NULL)
872                 break;
873               /* get session for affected curl handle */
874               cs = find_session_by_curlhandle (msg->easy_handle);
875               GNUNET_assert ( cs != NULL );
876               switch (msg->msg)
877                 {
878
879                 case CURLMSG_DONE:
880                   if ( (msg->data.result != CURLE_OK) &&
881                        (msg->data.result != CURLE_GOT_NOTHING) )
882                     {
883
884                     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
885                                _("%s failed for `%s' at %s:%d: `%s'\n"),
886                                "curl_multi_perform",
887                                cs->ip,
888                                __FILE__,
889                                __LINE__,
890                                curl_easy_strerror (msg->data.result));
891                     /* sending msg failed*/
892                     if ( NULL != cs->transmit_cont)
893                       cs->transmit_cont (NULL,&cs->sender,GNUNET_SYSERR);
894                     }
895                   else
896                     {
897                     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
898                                 "Send to %s completed.\n", cs->ip);
899                     if (GNUNET_OK != remove_http_message(cs, cs->pending_outbound_msg))
900                       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message could not be removed from session `%s'", GNUNET_i2s(&cs->sender));
901
902                     curl_easy_cleanup(cs->curl_handle);
903                     cs->curl_handle=NULL;
904
905                     /* send pending messages */
906                     if (cs->pending_outbound_msg != NULL)
907                       send_select_init (cs);
908
909                     /* Calling transmit continuation  */
910                     if ( NULL != cs->transmit_cont)
911                       cs->transmit_cont (NULL,&cs->sender,GNUNET_OK);
912                     }
913                   return;
914                 default:
915                   break;
916                 }
917
918             }
919           while ( (running > 0) );
920         }
921     }
922   while (mret == CURLM_CALL_MULTI_PERFORM);
923   send_prepare(cls);
924 }
925
926
927 /**
928  * Function setting up file descriptors and scheduling task to run
929  * @param ses session to send data to
930  * @return bytes sent to peer
931  */
932 static size_t send_prepare(struct Session* session )
933 {
934   fd_set rs;
935   fd_set ws;
936   fd_set es;
937   int max;
938   struct GNUNET_NETWORK_FDSet *grs;
939   struct GNUNET_NETWORK_FDSet *gws;
940   long to;
941   CURLMcode mret;
942
943   max = -1;
944   FD_ZERO (&rs);
945   FD_ZERO (&ws);
946   FD_ZERO (&es);
947   mret = curl_multi_fdset (multi_handle, &rs, &ws, &es, &max);
948   if (mret != CURLM_OK)
949     {
950       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
951                   _("%s failed at %s:%d: `%s'\n"),
952                   "curl_multi_fdset", __FILE__, __LINE__,
953                   curl_multi_strerror (mret));
954       return -1;
955     }
956   mret = curl_multi_timeout (multi_handle, &to);
957   if (mret != CURLM_OK)
958     {
959       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
960                   _("%s failed at %s:%d: `%s'\n"),
961                   "curl_multi_timeout", __FILE__, __LINE__,
962                   curl_multi_strerror (mret));
963       return -1;
964     }
965
966   grs = GNUNET_NETWORK_fdset_create ();
967   gws = GNUNET_NETWORK_fdset_create ();
968   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
969   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
970   http_task_send = GNUNET_SCHEDULER_add_select (plugin->env->sched,
971                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
972                                    GNUNET_SCHEDULER_NO_TASK,
973                                    GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 0),
974                                    grs,
975                                    gws,
976                                    &send_execute,
977                                    session);
978   GNUNET_NETWORK_fdset_destroy (gws);
979   GNUNET_NETWORK_fdset_destroy (grs);
980
981   /* FIXME: return bytes REALLY sent */
982   return 0;
983 }
984
985 /**
986  * Function that can be used by the transport service to transmit
987  * a message using the plugin.
988  *
989  * @param cls closure
990  * @param target who should receive this message
991  * @param priority how important is the message
992  * @param msgbuf the message to transmit
993  * @param msgbuf_size number of bytes in 'msgbuf'
994  * @param to when should we time out
995  * @param session which session must be used (or NULL for "any")
996  * @param addr the address to use (can be NULL if the plugin
997  *                is "on its own" (i.e. re-use existing TCP connection))
998  * @param addrlen length of the address in bytes
999  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1000  *                otherwise the plugin may use other addresses or
1001  *                existing connections (if available)
1002  * @param cont continuation to call once the message has
1003  *        been transmitted (or if the transport is ready
1004  *        for the next transmission call; or if the
1005  *        peer disconnected...)
1006  * @param cont_cls closure for cont
1007  * @return number of bytes used (on the physical network, with overheads);
1008  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1009  *         and does NOT mean that the message was not transmitted (DV)
1010  */
1011 static ssize_t
1012 http_plugin_send (void *cls,
1013                       const struct GNUNET_PeerIdentity *target,
1014                       const char *msgbuf,
1015                       size_t msgbuf_size,
1016                       unsigned int priority,
1017                       struct GNUNET_TIME_Relative to,
1018                       struct Session *session,
1019                       const void *addr,
1020                       size_t addrlen,
1021                       int force_address,
1022                       GNUNET_TRANSPORT_TransmitContinuation cont,
1023                       void *cont_cls)
1024 {
1025   struct Session* ses;
1026   struct Session* ses_temp;
1027   struct HTTP_Message * msg;
1028   struct HTTP_Message * tmp;
1029   int bytes_sent = 0;
1030
1031   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Transport told plugin to send to peer `%s'\n",GNUNET_i2s(target));
1032
1033   /* find session for peer */
1034   ses = find_session_by_pi (target);
1035   if (NULL != ses )
1036     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Existing session for peer `%s' found\n", GNUNET_i2s(target));
1037   if ( ses == NULL)
1038   {
1039     /* create new session object */
1040
1041     /*FIXME: what is const void * really? Assuming struct sockaddr_in * ! */
1042     ses = create_session((struct sockaddr_in *) addr, target);
1043     ses->is_active = GNUNET_YES;
1044     ses->transmit_cont = cont;
1045
1046     /* Insert session into linked list */
1047     if ( plugin->sessions == NULL)
1048     {
1049       plugin->sessions = ses;
1050       plugin->session_count = 1;
1051     }
1052     ses_temp = plugin->sessions;
1053     while ( ses_temp->next != NULL )
1054     {
1055       ses_temp = ses_temp->next;
1056     }
1057     if (ses_temp != ses )
1058     {
1059       ses_temp->next = ses;
1060       plugin->session_count++;
1061     }
1062     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"New Session `%s' inserted, count %u \n", GNUNET_i2s(target), plugin->session_count);
1063   }
1064
1065   ses->curl_handle = curl_easy_init();
1066   if( NULL == ses->curl_handle)
1067   {
1068     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Getting cURL handle failed\n");
1069     return -1;
1070   }
1071
1072   if ( NULL != cont)
1073     ses->transmit_cont = cont;
1074   timeout = to;
1075   /* setting up message */
1076   msg = GNUNET_malloc (sizeof (struct HTTP_Message));
1077   msg->next = NULL;
1078   msg->len = msgbuf_size;
1079   msg->pos = 0;
1080   msg->buf = GNUNET_malloc (msgbuf_size);
1081   memcpy (msg->buf,msgbuf, msgbuf_size);
1082
1083   /* insert created message in list of pending messages */
1084
1085   if (ses->pending_outbound_msg == NULL)
1086   {
1087     ses->pending_outbound_msg = msg;
1088   }
1089   tmp = ses->pending_outbound_msg;
1090   while ( NULL != tmp->next)
1091   {
1092     tmp = tmp->next;
1093   }
1094   if ( tmp != msg)
1095     tmp->next = msg;
1096
1097   bytes_sent = send_select_init (ses);
1098   return bytes_sent;
1099
1100 }
1101
1102
1103
1104 /**
1105  * Function that can be used to force the plugin to disconnect
1106  * from the given peer and cancel all previous transmissions
1107  * (and their continuationc).
1108  *
1109  * @param cls closure
1110  * @param target peer from which to disconnect
1111  */
1112 static void
1113 http_plugin_disconnect (void *cls,
1114                             const struct GNUNET_PeerIdentity *target)
1115 {
1116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_disconnect\n");
1117   // struct Plugin *plugin = cls;
1118   // FIXME
1119 }
1120
1121
1122 /**
1123  * Convert the transports address to a nice, human-readable
1124  * format.
1125  *
1126  * @param cls closure
1127  * @param type name of the transport that generated the address
1128  * @param addr one of the addresses of the host, NULL for the last address
1129  *        the specific address format depends on the transport
1130  * @param addrlen length of the address
1131  * @param numeric should (IP) addresses be displayed in numeric form?
1132  * @param timeout after how long should we give up?
1133  * @param asc function to call on each string
1134  * @param asc_cls closure for asc
1135  */
1136 static void
1137 http_plugin_address_pretty_printer (void *cls,
1138                                         const char *type,
1139                                         const void *addr,
1140                                         size_t addrlen,
1141                                         int numeric,
1142                                         struct GNUNET_TIME_Relative timeout,
1143                                         GNUNET_TRANSPORT_AddressStringCallback
1144                                         asc, void *asc_cls)
1145 {
1146   const struct IPv4HttpAddress *t4;
1147   const struct IPv6HttpAddress *t6;
1148   struct sockaddr_in a4;
1149   struct sockaddr_in6 a6;
1150   char * address;
1151   char * ret;
1152   unsigned int port;
1153
1154   if (addrlen == sizeof (struct IPv6HttpAddress))
1155     {
1156       address = GNUNET_malloc (INET6_ADDRSTRLEN);
1157       t6 = addr;
1158       a6.sin6_addr = t6->ipv6_addr;
1159       inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
1160       port = ntohs(t6->u6_port);
1161     }
1162   else if (addrlen == sizeof (struct IPv4HttpAddress))
1163     {
1164       address = GNUNET_malloc (INET_ADDRSTRLEN);
1165       t4 = addr;
1166       a4.sin_addr.s_addr =  t4->ipv4_addr;
1167       inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
1168       port = ntohs(t4->u_port);
1169     }
1170   else
1171     {
1172       /* invalid address */
1173       GNUNET_break_op (0);
1174       asc (asc_cls, NULL);
1175       return;
1176     }
1177
1178   ret = GNUNET_malloc(strlen(address) +14);
1179   GNUNET_asprintf(&ret,"http://%s:%u/",address,port);
1180   GNUNET_free (address);
1181   asc (asc_cls, ret);
1182 }
1183
1184
1185
1186 /**
1187  * Another peer has suggested an address for this
1188  * peer and transport plugin.  Check that this could be a valid
1189  * address.  If so, consider adding it to the list
1190  * of addresses.
1191  *
1192  * @param cls closure
1193  * @param addr pointer to the address
1194  * @param addrlen length of addr
1195  * @return GNUNET_OK if this is a plausible address for this peer
1196  *         and transport
1197  */
1198 static int
1199 http_plugin_address_suggested (void *cls,
1200                                   void *addr, size_t addrlen)
1201 {
1202   /* struct Plugin *plugin = cls; */
1203
1204   /* check if the address is plausible; if so,
1205      add it to our list! */
1206   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Plugin: http_plugin_address_suggested\n");
1207   return GNUNET_OK;
1208 }
1209
1210
1211 /**
1212  * Function called for a quick conversion of the binary address to
1213  * a numeric address.  Note that the caller must not free the
1214  * address and that the next call to this function is allowed
1215  * to override the address again.
1216  *
1217  * @param cls closure
1218  * @param addr binary address
1219  * @param addrlen length of the address
1220  * @return string representing the same address
1221  */
1222 static const char*
1223 http_plugin_address_to_string (void *cls,
1224                                    const void *addr,
1225                                    size_t addrlen)
1226 {
1227   const struct IPv4HttpAddress *t4;
1228   const struct IPv6HttpAddress *t6;
1229   struct sockaddr_in a4;
1230   struct sockaddr_in6 a6;
1231   char * address;
1232   char * ret;
1233   unsigned int port;
1234
1235   if (addrlen == sizeof (struct IPv6HttpAddress))
1236     {
1237       address = GNUNET_malloc (INET6_ADDRSTRLEN);
1238       t6 = addr;
1239       a6.sin6_addr = t6->ipv6_addr;
1240       inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
1241       port = ntohs(t6->u6_port);
1242     }
1243   else if (addrlen == sizeof (struct IPv4HttpAddress))
1244     {
1245       address = GNUNET_malloc (INET_ADDRSTRLEN);
1246       t4 = addr;
1247       a4.sin_addr.s_addr =  t4->ipv4_addr;
1248       inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
1249       port = ntohs(t4->u_port);
1250     }
1251   else
1252     {
1253       /* invalid address */
1254       return NULL;
1255     }
1256
1257   ret = GNUNET_malloc(strlen(address) +6);
1258   GNUNET_asprintf(&ret,"%s:%u",address,port);
1259   GNUNET_free (address);
1260   return ret;
1261 }
1262
1263 /**
1264  * Add the IP of our network interface to the list of
1265  * our external IP addresses.
1266  *
1267  * @param cls the 'struct Plugin*'
1268  * @param name name of the interface
1269  * @param isDefault do we think this may be our default interface
1270  * @param addr address of the interface
1271  * @param addrlen number of bytes in addr
1272  * @return GNUNET_OK to continue iterating
1273  */
1274 static int
1275 process_interfaces (void *cls,
1276                     const char *name,
1277                     int isDefault,
1278                     const struct sockaddr *addr, socklen_t addrlen)
1279 {
1280   struct IPv4HttpAddress t4;
1281   struct IPv6HttpAddress t6;
1282   int af;
1283   void *arg;
1284   uint16_t args;
1285
1286
1287
1288   af = addr->sa_family;
1289   if (af == AF_INET)
1290     {
1291       if (INADDR_LOOPBACK == ntohl(((struct sockaddr_in *) addr)->sin_addr.s_addr))
1292       {
1293         /* skip loopback addresses */
1294         return GNUNET_OK;
1295       }
1296       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1297       t4.u_port = htons (plugin->port_inbound);
1298       arg = &t4;
1299       args = sizeof (t4);
1300     }
1301   else if (af == AF_INET6)
1302     {
1303       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1304         {
1305           /* skip link local addresses */
1306           return GNUNET_OK;
1307         }
1308       if (IN6_IS_ADDR_LOOPBACK (&((struct sockaddr_in6 *) addr)->sin6_addr))
1309         {
1310           /* skip loopback addresses */
1311           return GNUNET_OK;
1312         }
1313       memcpy (&t6.ipv6_addr,
1314               &((struct sockaddr_in6 *) addr)->sin6_addr,
1315               sizeof (struct in6_addr));
1316       t6.u6_port = htons (plugin->port_inbound);
1317       arg = &t6;
1318       args = sizeof (t6);
1319     }
1320   else
1321     {
1322       GNUNET_break (0);
1323       return GNUNET_OK;
1324     }
1325   plugin->env->notify_address(plugin->env->cls,"http",arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1326
1327   return GNUNET_OK;
1328 }
1329
1330 /**
1331  * Exit point from the plugin.
1332  */
1333 void *
1334 libgnunet_plugin_transport_http_done (void *cls)
1335 {
1336   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1337   struct Plugin *plugin = api->cls;
1338   struct Session * cs;
1339   struct Session * cs_next;
1340   CURLMcode mret;
1341
1342   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unloading http plugin...\n");
1343
1344   if ( http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1345   {
1346     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v4);
1347     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
1348   }
1349
1350   if ( http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1351   {
1352     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v6);
1353     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1354   }
1355
1356   if ( http_task_send != GNUNET_SCHEDULER_NO_TASK)
1357   {
1358     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_send);
1359     http_task_send = GNUNET_SCHEDULER_NO_TASK;
1360   }
1361
1362   if (http_daemon_v4 != NULL)
1363   {
1364     MHD_stop_daemon (http_daemon_v4);
1365     http_daemon_v4 = NULL;
1366   }
1367   if (http_daemon_v6 != NULL)
1368   {
1369     MHD_stop_daemon (http_daemon_v6);
1370     http_daemon_v6 = NULL;
1371   }
1372
1373   mret = curl_multi_cleanup(multi_handle);
1374   if ( CURLM_OK != mret)
1375     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed");
1376
1377   /* free all sessions */
1378   cs = plugin->sessions;
1379
1380   while ( NULL != cs)
1381     {
1382       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing session to `%s'\n",cs->ip);
1383
1384       cs_next = cs->next;
1385       /* freeing messages */
1386       struct HTTP_Message *cur;
1387       struct HTTP_Message *tmp;
1388       cur = cs->pending_outbound_msg;
1389
1390       while (cur != NULL)
1391       {
1392          tmp = cur->next;
1393          if (NULL != cur->buf)
1394            GNUNET_free (cur->buf);
1395          GNUNET_free (cur);
1396          cur = tmp;
1397       }
1398
1399       GNUNET_free (cs->ip);
1400       GNUNET_free (cs->addr);
1401       GNUNET_free (cs);
1402       plugin->session_count--;
1403       cs = cs_next;
1404
1405     }
1406
1407   /* GNUNET_SERVICE_stop (plugin->service); */
1408   GNUNET_free (hostname);
1409   GNUNET_free (plugin);
1410   GNUNET_free (api);
1411   return NULL;
1412 }
1413
1414
1415 /**
1416  * Entry point for the plugin.
1417  */
1418 void *
1419 libgnunet_plugin_transport_http_init (void *cls)
1420 {
1421   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1422   struct GNUNET_TRANSPORT_PluginFunctions *api;
1423   struct GNUNET_SERVICE_Context *service;
1424   unsigned int timeout;
1425   struct GNUNET_TIME_Relative gn_timeout;
1426   long long unsigned int port;
1427
1428   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
1429
1430   service = NULL;
1431   /*
1432   service = GNUNET_SERVICE_start ("transport-http", env->sched, env->cfg);
1433   if (service == NULL)
1434     {
1435       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "", _
1436                        ("Failed to start service for `%s' transport plugin.\n"),
1437                        "http");
1438       return NULL;
1439     }
1440     */
1441
1442   plugin = GNUNET_malloc (sizeof (struct Plugin));
1443   plugin->env = env;
1444   plugin->sessions = NULL;
1445   plugin->service = service;
1446   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1447   api->cls = plugin;
1448   api->send = &http_plugin_send;
1449   api->disconnect = &http_plugin_disconnect;
1450   api->address_pretty_printer = &http_plugin_address_pretty_printer;
1451   api->check_address = &http_plugin_address_suggested;
1452   api->address_to_string = &http_plugin_address_to_string;
1453
1454   hostname = GNUNET_RESOLVER_local_fqdn_get ();
1455
1456   /* Hashing our identity to use it in URLs */
1457   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &my_ascii_hash_ident);
1458
1459   /* Reading port number from config file */
1460   if ((GNUNET_OK !=
1461        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1462                                               "transport-http",
1463                                               "PORT",
1464                                               &port)) ||
1465       (port > 65535) )
1466     {
1467       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1468                        "http",
1469                        _
1470                        ("Require valid port number for transport plugin `%s' in configuration!\n"),
1471                        "transport-http");
1472       libgnunet_plugin_transport_http_done (api);
1473       return NULL;
1474     }
1475   plugin->port_inbound = port;
1476   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1477   timeout = ( gn_timeout.value / 1000);
1478   if ((http_daemon_v4 == NULL) && (http_daemon_v6 == NULL) && (port != 0))
1479     {
1480     http_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
1481                                        port,
1482                                        &acceptPolicyCallback,
1483                                        NULL , &accessHandlerCallback, NULL,
1484                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1485                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1486                                        MHD_OPTION_CONNECTION_TIMEOUT, timeout,
1487                                        /* FIXME: set correct limit */
1488                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1489                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1490                                        MHD_OPTION_END);
1491     http_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
1492                                        port,
1493                                        &acceptPolicyCallback,
1494                                        NULL , &accessHandlerCallback, NULL,
1495                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
1496                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
1497                                        MHD_OPTION_CONNECTION_TIMEOUT, timeout,
1498                                        /* FIXME: set correct limit */
1499                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
1500                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
1501                                        MHD_OPTION_END);
1502     }
1503   if (http_daemon_v4 != NULL)
1504     http_task_v4 = http_daemon_prepare (http_daemon_v4);
1505   if (http_daemon_v6 != NULL)
1506     http_task_v6 = http_daemon_prepare (http_daemon_v6);
1507
1508   if (http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1509     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
1510   if (http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1511     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
1512
1513
1514   /* Initializing cURL */
1515   multi_handle = curl_multi_init();
1516   if ( NULL == multi_handle )
1517   {
1518     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1519                      "http",
1520                      _("Could not initialize curl multi handle, failed to start http plugin!\n"),
1521                      "transport-http");
1522     libgnunet_plugin_transport_http_done (api);
1523     return NULL;
1524   }
1525
1526   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1527
1528   return api;
1529 }
1530
1531 /* end of plugin_transport_template.c */