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