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