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