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