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