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