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