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