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