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